server_WO3f6Mge.mjs 244 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994
  1. globalThis.process ??= {}; globalThis.process.env ??= {};
  2. const ASTRO_VERSION = "5.14.3";
  3. const REROUTE_DIRECTIVE_HEADER = "X-Astro-Reroute";
  4. const REWRITE_DIRECTIVE_HEADER_KEY = "X-Astro-Rewrite";
  5. const REWRITE_DIRECTIVE_HEADER_VALUE = "yes";
  6. const NOOP_MIDDLEWARE_HEADER = "X-Astro-Noop";
  7. const ROUTE_TYPE_HEADER = "X-Astro-Route-Type";
  8. const DEFAULT_404_COMPONENT = "astro-default-404.astro";
  9. const REDIRECT_STATUS_CODES = [301, 302, 303, 307, 308, 300, 304];
  10. const REROUTABLE_STATUS_CODES = [404, 500];
  11. const clientAddressSymbol = Symbol.for("astro.clientAddress");
  12. const originPathnameSymbol = Symbol.for("astro.originPathname");
  13. const responseSentSymbol = Symbol.for("astro.responseSent");
  14. function normalizeLF(code) {
  15. return code.replace(/\r\n|\r(?!\n)|\n/g, "\n");
  16. }
  17. function codeFrame(src, loc) {
  18. if (!loc || loc.line === void 0 || loc.column === void 0) {
  19. return "";
  20. }
  21. const lines = normalizeLF(src).split("\n").map((ln) => ln.replace(/\t/g, " "));
  22. const visibleLines = [];
  23. for (let n = -2; n <= 2; n++) {
  24. if (lines[loc.line + n]) visibleLines.push(loc.line + n);
  25. }
  26. let gutterWidth = 0;
  27. for (const lineNo of visibleLines) {
  28. let w = `> ${lineNo}`;
  29. if (w.length > gutterWidth) gutterWidth = w.length;
  30. }
  31. let output = "";
  32. for (const lineNo of visibleLines) {
  33. const isFocusedLine = lineNo === loc.line - 1;
  34. output += isFocusedLine ? "> " : " ";
  35. output += `${lineNo + 1} | ${lines[lineNo]}
  36. `;
  37. if (isFocusedLine)
  38. output += `${Array.from({ length: gutterWidth }).join(" ")} | ${Array.from({
  39. length: loc.column
  40. }).join(" ")}^
  41. `;
  42. }
  43. return output;
  44. }
  45. class AstroError extends Error {
  46. loc;
  47. title;
  48. hint;
  49. frame;
  50. type = "AstroError";
  51. constructor(props, options) {
  52. const { name, title, message, stack, location, hint, frame } = props;
  53. super(message, options);
  54. this.title = title;
  55. this.name = name;
  56. if (message) this.message = message;
  57. this.stack = stack ? stack : this.stack;
  58. this.loc = location;
  59. this.hint = hint;
  60. this.frame = frame;
  61. }
  62. setLocation(location) {
  63. this.loc = location;
  64. }
  65. setName(name) {
  66. this.name = name;
  67. }
  68. setMessage(message) {
  69. this.message = message;
  70. }
  71. setHint(hint) {
  72. this.hint = hint;
  73. }
  74. setFrame(source, location) {
  75. this.frame = codeFrame(source, location);
  76. }
  77. static is(err) {
  78. return err.type === "AstroError";
  79. }
  80. }
  81. const ClientAddressNotAvailable = {
  82. name: "ClientAddressNotAvailable",
  83. title: "`Astro.clientAddress` is not available in current adapter.",
  84. message: (adapterName) => `\`Astro.clientAddress\` is not available in the \`${adapterName}\` adapter. File an issue with the adapter to add support.`
  85. };
  86. const PrerenderClientAddressNotAvailable = {
  87. name: "PrerenderClientAddressNotAvailable",
  88. title: "`Astro.clientAddress` cannot be used inside prerendered routes.",
  89. message: (name) => `\`Astro.clientAddress\` cannot be used inside prerendered route ${name}`
  90. };
  91. const StaticClientAddressNotAvailable = {
  92. name: "StaticClientAddressNotAvailable",
  93. title: "`Astro.clientAddress` is not available in prerendered pages.",
  94. message: "`Astro.clientAddress` is only available on pages that are server-rendered.",
  95. hint: "See https://docs.astro.build/en/guides/on-demand-rendering/ for more information on how to enable SSR."
  96. };
  97. const NoMatchingStaticPathFound = {
  98. name: "NoMatchingStaticPathFound",
  99. title: "No static path found for requested path.",
  100. message: (pathName) => `A \`getStaticPaths()\` route pattern was matched, but no matching static path was found for requested path \`${pathName}\`.`,
  101. hint: (possibleRoutes) => `Possible dynamic routes being matched: ${possibleRoutes.join(", ")}.`
  102. };
  103. const OnlyResponseCanBeReturned = {
  104. name: "OnlyResponseCanBeReturned",
  105. title: "Invalid type returned by Astro page.",
  106. message: (route, returnedValue) => `Route \`${route ? route : ""}\` returned a \`${returnedValue}\`. Only a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from Astro files.`,
  107. hint: "See https://docs.astro.build/en/guides/on-demand-rendering/#response for more information."
  108. };
  109. const MissingMediaQueryDirective = {
  110. name: "MissingMediaQueryDirective",
  111. title: "Missing value for `client:media` directive.",
  112. message: 'Media query not provided for `client:media` directive. A media query similar to `client:media="(max-width: 600px)"` must be provided'
  113. };
  114. const NoMatchingRenderer = {
  115. name: "NoMatchingRenderer",
  116. title: "No matching renderer found.",
  117. message: (componentName, componentExtension, plural, validRenderersCount) => `Unable to render \`${componentName}\`.
  118. ${validRenderersCount > 0 ? `There ${plural ? "are" : "is"} ${validRenderersCount} renderer${plural ? "s" : ""} configured in your \`astro.config.mjs\` file,
  119. but ${plural ? "none were" : "it was not"} able to server-side render \`${componentName}\`.` : `No valid renderer was found ${componentExtension ? `for the \`.${componentExtension}\` file extension.` : `for this file extension.`}`}`,
  120. hint: (probableRenderers) => `Did you mean to enable the ${probableRenderers} integration?
  121. See https://docs.astro.build/en/guides/framework-components/ for more information on how to install and configure integrations.`
  122. };
  123. const NoClientOnlyHint = {
  124. name: "NoClientOnlyHint",
  125. title: "Missing hint on client:only directive.",
  126. message: (componentName) => `Unable to render \`${componentName}\`. When using the \`client:only\` hydration strategy, Astro needs a hint to use the correct renderer.`,
  127. hint: (probableRenderers) => `Did you mean to pass \`client:only="${probableRenderers}"\`? See https://docs.astro.build/en/reference/directives-reference/#clientonly for more information on client:only`
  128. };
  129. const InvalidGetStaticPathsEntry = {
  130. name: "InvalidGetStaticPathsEntry",
  131. title: "Invalid entry inside getStaticPath's return value",
  132. message: (entryType) => `Invalid entry returned by getStaticPaths. Expected an object, got \`${entryType}\``,
  133. hint: "If you're using a `.map` call, you might be looking for `.flatMap()` instead. See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
  134. };
  135. const InvalidGetStaticPathsReturn = {
  136. name: "InvalidGetStaticPathsReturn",
  137. title: "Invalid value returned by getStaticPaths.",
  138. message: (returnType) => `Invalid type returned by \`getStaticPaths\`. Expected an \`array\`, got \`${returnType}\``,
  139. hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
  140. };
  141. const GetStaticPathsExpectedParams = {
  142. name: "GetStaticPathsExpectedParams",
  143. title: "Missing params property on `getStaticPaths` route.",
  144. message: "Missing or empty required `params` property on `getStaticPaths` route.",
  145. hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
  146. };
  147. const GetStaticPathsInvalidRouteParam = {
  148. name: "GetStaticPathsInvalidRouteParam",
  149. title: "Invalid value for `getStaticPaths` route parameter.",
  150. message: (key, value, valueType) => `Invalid getStaticPaths route parameter for \`${key}\`. Expected undefined, a string or a number, received \`${valueType}\` (\`${value}\`)`,
  151. hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
  152. };
  153. const GetStaticPathsRequired = {
  154. name: "GetStaticPathsRequired",
  155. title: "`getStaticPaths()` function required for dynamic routes.",
  156. message: "`getStaticPaths()` function is required for dynamic routes. Make sure that you `export` a `getStaticPaths` function from your dynamic route.",
  157. hint: `See https://docs.astro.build/en/guides/routing/#dynamic-routes for more information on dynamic routes.
  158. If you meant for this route to be server-rendered, set \`export const prerender = false;\` in the page.`
  159. };
  160. const ReservedSlotName = {
  161. name: "ReservedSlotName",
  162. title: "Invalid slot name.",
  163. message: (slotName) => `Unable to create a slot named \`${slotName}\`. \`${slotName}\` is a reserved slot name. Please update the name of this slot.`
  164. };
  165. const NoMatchingImport = {
  166. name: "NoMatchingImport",
  167. title: "No import found for component.",
  168. message: (componentName) => `Could not render \`${componentName}\`. No matching import has been found for \`${componentName}\`.`,
  169. hint: "Please make sure the component is properly imported."
  170. };
  171. const InvalidComponentArgs = {
  172. name: "InvalidComponentArgs",
  173. title: "Invalid component arguments.",
  174. message: (name) => `Invalid arguments passed to${name ? ` <${name}>` : ""} component.`,
  175. hint: "Astro components cannot be rendered directly via function call, such as `Component()` or `{items.map(Component)}`."
  176. };
  177. const PageNumberParamNotFound = {
  178. name: "PageNumberParamNotFound",
  179. title: "Page number param not found.",
  180. message: (paramName) => `[paginate()] page number param \`${paramName}\` not found in your filepath.`,
  181. hint: "Rename your file to `[page].astro` or `[...page].astro`."
  182. };
  183. const ImageMissingAlt = {
  184. name: "ImageMissingAlt",
  185. title: 'Image missing required "alt" property.',
  186. message: 'Image missing "alt" property. "alt" text is required to describe important images on the page.',
  187. hint: 'Use an empty string ("") for decorative images.'
  188. };
  189. const InvalidImageService = {
  190. name: "InvalidImageService",
  191. title: "Error while loading image service.",
  192. message: "There was an error loading the configured image service. Please see the stack trace for more information."
  193. };
  194. const MissingImageDimension = {
  195. name: "MissingImageDimension",
  196. title: "Missing image dimensions",
  197. message: (missingDimension, imageURL) => `Missing ${missingDimension === "both" ? "width and height attributes" : `${missingDimension} attribute`} for ${imageURL}. When using remote images, both dimensions are required in order to avoid CLS.`,
  198. hint: "If your image is inside your `src` folder, you probably meant to import it instead. See [the Imports guide for more information](https://docs.astro.build/en/guides/imports/#other-assets). You can also use `inferSize={true}` for remote images to get the original dimensions."
  199. };
  200. const FailedToFetchRemoteImageDimensions = {
  201. name: "FailedToFetchRemoteImageDimensions",
  202. title: "Failed to retrieve remote image dimensions",
  203. message: (imageURL) => `Failed to get the dimensions for ${imageURL}.`,
  204. hint: "Verify your remote image URL is accurate, and that you are not using `inferSize` with a file located in your `public/` folder."
  205. };
  206. const UnsupportedImageFormat = {
  207. name: "UnsupportedImageFormat",
  208. title: "Unsupported image format",
  209. message: (format, imagePath, supportedFormats) => `Received unsupported format \`${format}\` from \`${imagePath}\`. Currently only ${supportedFormats.join(
  210. ", "
  211. )} are supported by our image services.`,
  212. hint: "Using an `img` tag directly instead of the `Image` component might be what you're looking for."
  213. };
  214. const UnsupportedImageConversion = {
  215. name: "UnsupportedImageConversion",
  216. title: "Unsupported image conversion",
  217. message: "Converting between vector (such as SVGs) and raster (such as PNGs and JPEGs) images is not currently supported."
  218. };
  219. const PrerenderDynamicEndpointPathCollide = {
  220. name: "PrerenderDynamicEndpointPathCollide",
  221. title: "Prerendered dynamic endpoint has path collision.",
  222. message: (pathname) => `Could not render \`${pathname}\` with an \`undefined\` param as the generated path will collide during prerendering. Prevent passing \`undefined\` as \`params\` for the endpoint's \`getStaticPaths()\` function, or add an additional extension to the endpoint's filename.`,
  223. hint: (filename) => `Rename \`${filename}\` to \`${filename.replace(/\.(?:js|ts)/, (m) => `.json` + m)}\``
  224. };
  225. const ExpectedImage = {
  226. name: "ExpectedImage",
  227. title: "Expected src to be an image.",
  228. message: (src, typeofOptions, fullOptions) => `Expected \`src\` property for \`getImage\` or \`<Image />\` to be either an ESM imported image or a string with the path of a remote image. Received \`${src}\` (type: \`${typeofOptions}\`).
  229. Full serialized options received: \`${fullOptions}\`.`,
  230. hint: "This error can often happen because of a wrong path. Make sure the path to your image is correct. If you're passing an async function, make sure to call and await it."
  231. };
  232. const ExpectedImageOptions = {
  233. name: "ExpectedImageOptions",
  234. title: "Expected image options.",
  235. message: (options) => `Expected getImage() parameter to be an object. Received \`${options}\`.`
  236. };
  237. const ExpectedNotESMImage = {
  238. name: "ExpectedNotESMImage",
  239. title: "Expected image options, not an ESM-imported image.",
  240. message: "An ESM-imported image cannot be passed directly to `getImage()`. Instead, pass an object with the image in the `src` property.",
  241. hint: "Try changing `getImage(myImage)` to `getImage({ src: myImage })`"
  242. };
  243. const IncompatibleDescriptorOptions = {
  244. name: "IncompatibleDescriptorOptions",
  245. title: "Cannot set both `densities` and `widths`",
  246. message: "Only one of `densities` or `widths` can be specified. In most cases, you'll probably want to use only `widths` if you require specific widths.",
  247. hint: "Those attributes are used to construct a `srcset` attribute, which cannot have both `x` and `w` descriptors."
  248. };
  249. const NoImageMetadata = {
  250. name: "NoImageMetadata",
  251. title: "Could not process image metadata.",
  252. message: (imagePath) => `Could not process image metadata${imagePath ? ` for \`${imagePath}\`` : ""}.`,
  253. hint: "This is often caused by a corrupted or malformed image. Re-exporting the image from your image editor may fix this issue."
  254. };
  255. const ResponseSentError = {
  256. name: "ResponseSentError",
  257. title: "Unable to set response.",
  258. message: "The response has already been sent to the browser and cannot be altered."
  259. };
  260. const MiddlewareNoDataOrNextCalled = {
  261. name: "MiddlewareNoDataOrNextCalled",
  262. title: "The middleware didn't return a `Response`.",
  263. message: "Make sure your middleware returns a `Response` object, either directly or by returning the `Response` from calling the `next` function."
  264. };
  265. const MiddlewareNotAResponse = {
  266. name: "MiddlewareNotAResponse",
  267. title: "The middleware returned something that is not a `Response` object.",
  268. message: "Any data returned from middleware must be a valid `Response` object."
  269. };
  270. const EndpointDidNotReturnAResponse = {
  271. name: "EndpointDidNotReturnAResponse",
  272. title: "The endpoint did not return a `Response`.",
  273. message: "An endpoint must return either a `Response`, or a `Promise` that resolves with a `Response`."
  274. };
  275. const LocalsNotAnObject = {
  276. name: "LocalsNotAnObject",
  277. title: "Value assigned to `locals` is not accepted.",
  278. message: "`locals` can only be assigned to an object. Other values like numbers, strings, etc. are not accepted.",
  279. hint: "If you tried to remove some information from the `locals` object, try to use `delete` or set the property to `undefined`."
  280. };
  281. const LocalsReassigned = {
  282. name: "LocalsReassigned",
  283. title: "`locals` must not be reassigned.",
  284. message: "`locals` can not be assigned directly.",
  285. hint: "Set a `locals` property instead."
  286. };
  287. const AstroResponseHeadersReassigned = {
  288. name: "AstroResponseHeadersReassigned",
  289. title: "`Astro.response.headers` must not be reassigned.",
  290. message: "Individual headers can be added to and removed from `Astro.response.headers`, but it must not be replaced with another instance of `Headers` altogether.",
  291. hint: "Consider using `Astro.response.headers.add()`, and `Astro.response.headers.delete()`."
  292. };
  293. const LocalImageUsedWrongly = {
  294. name: "LocalImageUsedWrongly",
  295. title: "Local images must be imported.",
  296. message: (imageFilePath) => `\`Image\`'s and \`getImage\`'s \`src\` parameter must be an imported image or an URL, it cannot be a string filepath. Received \`${imageFilePath}\`.`,
  297. hint: "If you want to use an image from your `src` folder, you need to either import it or if the image is coming from a content collection, use the [image() schema helper](https://docs.astro.build/en/guides/images/#images-in-content-collections). See https://docs.astro.build/en/guides/images/#src-required for more information on the `src` property."
  298. };
  299. const AstroGlobUsedOutside = {
  300. name: "AstroGlobUsedOutside",
  301. title: "Astro.glob() used outside of an Astro file.",
  302. message: (globStr) => `\`Astro.glob(${globStr})\` can only be used in \`.astro\` files. \`import.meta.glob(${globStr})\` can be used instead to achieve a similar result.`,
  303. hint: "See Vite's documentation on `import.meta.glob` for more information: https://vite.dev/guide/features.html#glob-import"
  304. };
  305. const AstroGlobNoMatch = {
  306. name: "AstroGlobNoMatch",
  307. title: "Astro.glob() did not match any files.",
  308. message: (globStr) => `\`Astro.glob(${globStr})\` did not return any matching files.`,
  309. hint: "Check the pattern for typos."
  310. };
  311. const MissingSharp = {
  312. name: "MissingSharp",
  313. title: "Could not find Sharp.",
  314. message: "Could not find Sharp. Please install Sharp (`sharp`) manually into your project or migrate to another image service.",
  315. hint: "See Sharp's installation instructions for more information: https://sharp.pixelplumbing.com/install. If you are not relying on `astro:assets` to optimize, transform, or process any images, you can configure a passthrough image service instead of installing Sharp. See https://docs.astro.build/en/reference/errors/missing-sharp for more information.\n\nSee https://docs.astro.build/en/guides/images/#default-image-service for more information on how to migrate to another image service."
  316. };
  317. const i18nNoLocaleFoundInPath = {
  318. name: "i18nNoLocaleFoundInPath",
  319. title: "The path doesn't contain any locale",
  320. message: "You tried to use an i18n utility on a path that doesn't contain any locale. You can use `pathHasLocale` first to determine if the path has a locale."
  321. };
  322. const RewriteWithBodyUsed = {
  323. name: "RewriteWithBodyUsed",
  324. title: "Cannot use Astro.rewrite after the request body has been read",
  325. message: "Astro.rewrite() cannot be used if the request body has already been read. If you need to read the body, first clone the request."
  326. };
  327. const ForbiddenRewrite = {
  328. name: "ForbiddenRewrite",
  329. title: "Forbidden rewrite to a static route.",
  330. message: (from, to, component) => `You tried to rewrite the on-demand route '${from}' with the static route '${to}', when using the 'server' output.
  331. The static route '${to}' is rendered by the component
  332. '${component}', which is marked as prerendered. This is a forbidden operation because during the build the component '${component}' is compiled to an
  333. HTML file, which can't be retrieved at runtime by Astro.`,
  334. hint: (component) => `Add \`export const prerender = false\` to the component '${component}', or use a Astro.redirect().`
  335. };
  336. const ExperimentalFontsNotEnabled = {
  337. name: "ExperimentalFontsNotEnabled",
  338. title: "Experimental fonts are not enabled",
  339. message: "The Font component is used but experimental fonts have not been registered in the config.",
  340. hint: "Check that you have enabled experimental fonts and also configured your preferred fonts."
  341. };
  342. const FontFamilyNotFound = {
  343. name: "FontFamilyNotFound",
  344. title: "Font family not found",
  345. message: (family) => `No data was found for the \`"${family}"\` family passed to the \`<Font>\` component.`,
  346. hint: "This is often caused by a typo. Check that the `<Font />` component or `getFontData()` function are using a `cssVariable` specified in your config."
  347. };
  348. const CspNotEnabled = {
  349. name: "CspNotEnabled",
  350. title: "CSP feature isn't enabled",
  351. message: "The `experimental.csp` configuration isn't enabled."
  352. };
  353. const ActionsReturnedInvalidDataError = {
  354. name: "ActionsReturnedInvalidDataError",
  355. title: "Action handler returned invalid data.",
  356. message: (error) => `Action handler returned invalid data. Handlers should return serializable data types like objects, arrays, strings, and numbers. Parse error: ${error}`,
  357. hint: "See the devalue library for all supported types: https://github.com/rich-harris/devalue"
  358. };
  359. const ActionNotFoundError = {
  360. name: "ActionNotFoundError",
  361. title: "Action not found.",
  362. message: (actionName) => `The server received a request for an action named \`${actionName}\` but could not find a match. If you renamed an action, check that you've updated your \`actions/index\` file and your calling code to match.`,
  363. hint: "You can run `astro check` to detect type errors caused by mismatched action names."
  364. };
  365. const SessionStorageInitError = {
  366. name: "SessionStorageInitError",
  367. title: "Session storage could not be initialized.",
  368. message: (error, driver) => `Error when initializing session storage${driver ? ` with driver \`${driver}\`` : ""}. \`${error ?? ""}\``,
  369. hint: "For more information, see https://docs.astro.build/en/guides/sessions/"
  370. };
  371. const SessionStorageSaveError = {
  372. name: "SessionStorageSaveError",
  373. title: "Session data could not be saved.",
  374. message: (error, driver) => `Error when saving session data${driver ? ` with driver \`${driver}\`` : ""}. \`${error ?? ""}\``,
  375. hint: "For more information, see https://docs.astro.build/en/guides/sessions/"
  376. };
  377. function validateArgs(args) {
  378. if (args.length !== 3) return false;
  379. if (!args[0] || typeof args[0] !== "object") return false;
  380. return true;
  381. }
  382. function baseCreateComponent(cb, moduleId, propagation) {
  383. const name = moduleId?.split("/").pop()?.replace(".astro", "") ?? "";
  384. const fn = (...args) => {
  385. if (!validateArgs(args)) {
  386. throw new AstroError({
  387. ...InvalidComponentArgs,
  388. message: InvalidComponentArgs.message(name)
  389. });
  390. }
  391. return cb(...args);
  392. };
  393. Object.defineProperty(fn, "name", { value: name, writable: false });
  394. fn.isAstroComponentFactory = true;
  395. fn.moduleId = moduleId;
  396. fn.propagation = propagation;
  397. return fn;
  398. }
  399. function createComponentWithOptions(opts) {
  400. const cb = baseCreateComponent(opts.factory, opts.moduleId, opts.propagation);
  401. return cb;
  402. }
  403. function createComponent(arg1, moduleId, propagation) {
  404. if (typeof arg1 === "function") {
  405. return baseCreateComponent(arg1, moduleId, propagation);
  406. } else {
  407. return createComponentWithOptions(arg1);
  408. }
  409. }
  410. function createAstroGlobFn() {
  411. const globHandler = (importMetaGlobResult) => {
  412. console.warn(`Astro.glob is deprecated and will be removed in a future major version of Astro.
  413. Use import.meta.glob instead: https://vitejs.dev/guide/features.html#glob-import`);
  414. if (typeof importMetaGlobResult === "string") {
  415. throw new AstroError({
  416. ...AstroGlobUsedOutside,
  417. message: AstroGlobUsedOutside.message(JSON.stringify(importMetaGlobResult))
  418. });
  419. }
  420. let allEntries = [...Object.values(importMetaGlobResult)];
  421. if (allEntries.length === 0) {
  422. throw new AstroError({
  423. ...AstroGlobNoMatch,
  424. message: AstroGlobNoMatch.message(JSON.stringify(importMetaGlobResult))
  425. });
  426. }
  427. return Promise.all(allEntries.map((fn) => fn()));
  428. };
  429. return globHandler;
  430. }
  431. function createAstro(site) {
  432. return {
  433. site: void 0,
  434. generator: `Astro v${ASTRO_VERSION}`,
  435. glob: createAstroGlobFn()
  436. };
  437. }
  438. let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY = true;
  439. if (typeof process !== "undefined") {
  440. ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});
  441. isTTY = process.stdout && process.stdout.isTTY;
  442. }
  443. const $ = {
  444. enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY)
  445. };
  446. function init(x, y) {
  447. let rgx = new RegExp(`\\x1b\\[${y}m`, "g");
  448. let open = `\x1B[${x}m`, close = `\x1B[${y}m`;
  449. return function(txt) {
  450. if (!$.enabled || txt == null) return txt;
  451. return open + (!!~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;
  452. };
  453. }
  454. const bold = init(1, 22);
  455. const dim = init(2, 22);
  456. const red = init(31, 39);
  457. const green = init(32, 39);
  458. const yellow = init(33, 39);
  459. const blue = init(34, 39);
  460. async function renderEndpoint(mod, context, isPrerendered, logger) {
  461. const { request, url } = context;
  462. const method = request.method.toUpperCase();
  463. let handler = mod[method] ?? mod["ALL"];
  464. if (!handler && method === "HEAD" && mod["GET"]) {
  465. handler = mod["GET"];
  466. }
  467. if (isPrerendered && !["GET", "HEAD"].includes(method)) {
  468. logger.warn(
  469. "router",
  470. `${url.pathname} ${bold(
  471. method
  472. )} requests are not available in static endpoints. Mark this page as server-rendered (\`export const prerender = false;\`) or update your config to \`output: 'server'\` to make all your pages server-rendered by default.`
  473. );
  474. }
  475. if (handler === void 0) {
  476. logger.warn(
  477. "router",
  478. `No API Route handler exists for the method "${method}" for the route "${url.pathname}".
  479. Found handlers: ${Object.keys(mod).map((exp) => JSON.stringify(exp)).join(", ")}
  480. ` + ("all" in mod ? `One of the exported handlers is "all" (lowercase), did you mean to export 'ALL'?
  481. ` : "")
  482. );
  483. return new Response(null, { status: 404 });
  484. }
  485. if (typeof handler !== "function") {
  486. logger.error(
  487. "router",
  488. `The route "${url.pathname}" exports a value for the method "${method}", but it is of the type ${typeof handler} instead of a function.`
  489. );
  490. return new Response(null, { status: 500 });
  491. }
  492. let response = await handler.call(mod, context);
  493. if (!response || response instanceof Response === false) {
  494. throw new AstroError(EndpointDidNotReturnAResponse);
  495. }
  496. if (REROUTABLE_STATUS_CODES.includes(response.status)) {
  497. try {
  498. response.headers.set(REROUTE_DIRECTIVE_HEADER, "no");
  499. } catch (err) {
  500. if (err.message?.includes("immutable")) {
  501. response = new Response(response.body, response);
  502. response.headers.set(REROUTE_DIRECTIVE_HEADER, "no");
  503. } else {
  504. throw err;
  505. }
  506. }
  507. }
  508. if (method === "HEAD") {
  509. return new Response(null, response);
  510. }
  511. return response;
  512. }
  513. /**
  514. * Copyright (C) 2017-present by Andrea Giammarchi - @WebReflection
  515. *
  516. * Permission is hereby granted, free of charge, to any person obtaining a copy
  517. * of this software and associated documentation files (the "Software"), to deal
  518. * in the Software without restriction, including without limitation the rights
  519. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  520. * copies of the Software, and to permit persons to whom the Software is
  521. * furnished to do so, subject to the following conditions:
  522. *
  523. * The above copyright notice and this permission notice shall be included in
  524. * all copies or substantial portions of the Software.
  525. *
  526. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  527. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  528. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  529. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  530. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  531. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  532. * THE SOFTWARE.
  533. */
  534. const {replace} = '';
  535. const ca = /[&<>'"]/g;
  536. const esca = {
  537. '&': '&amp;',
  538. '<': '&lt;',
  539. '>': '&gt;',
  540. "'": '&#39;',
  541. '"': '&quot;'
  542. };
  543. const pe = m => esca[m];
  544. /**
  545. * Safely escape HTML entities such as `&`, `<`, `>`, `"`, and `'`.
  546. * @param {string} es the input to safely escape
  547. * @returns {string} the escaped input, and it **throws** an error if
  548. * the input type is unexpected, except for boolean and numbers,
  549. * converted as string.
  550. */
  551. const escape = es => replace.call(es, ca, pe);
  552. function isPromise(value) {
  553. return !!value && typeof value === "object" && "then" in value && typeof value.then === "function";
  554. }
  555. async function* streamAsyncIterator(stream) {
  556. const reader = stream.getReader();
  557. try {
  558. while (true) {
  559. const { done, value } = await reader.read();
  560. if (done) return;
  561. yield value;
  562. }
  563. } finally {
  564. reader.releaseLock();
  565. }
  566. }
  567. const escapeHTML = escape;
  568. class HTMLBytes extends Uint8Array {
  569. }
  570. Object.defineProperty(HTMLBytes.prototype, Symbol.toStringTag, {
  571. get() {
  572. return "HTMLBytes";
  573. }
  574. });
  575. class HTMLString extends String {
  576. get [Symbol.toStringTag]() {
  577. return "HTMLString";
  578. }
  579. }
  580. const markHTMLString = (value) => {
  581. if (value instanceof HTMLString) {
  582. return value;
  583. }
  584. if (typeof value === "string") {
  585. return new HTMLString(value);
  586. }
  587. return value;
  588. };
  589. function isHTMLString(value) {
  590. return Object.prototype.toString.call(value) === "[object HTMLString]";
  591. }
  592. function markHTMLBytes(bytes) {
  593. return new HTMLBytes(bytes);
  594. }
  595. function hasGetReader(obj) {
  596. return typeof obj.getReader === "function";
  597. }
  598. async function* unescapeChunksAsync(iterable) {
  599. if (hasGetReader(iterable)) {
  600. for await (const chunk of streamAsyncIterator(iterable)) {
  601. yield unescapeHTML(chunk);
  602. }
  603. } else {
  604. for await (const chunk of iterable) {
  605. yield unescapeHTML(chunk);
  606. }
  607. }
  608. }
  609. function* unescapeChunks(iterable) {
  610. for (const chunk of iterable) {
  611. yield unescapeHTML(chunk);
  612. }
  613. }
  614. function unescapeHTML(str) {
  615. if (!!str && typeof str === "object") {
  616. if (str instanceof Uint8Array) {
  617. return markHTMLBytes(str);
  618. } else if (str instanceof Response && str.body) {
  619. const body = str.body;
  620. return unescapeChunksAsync(body);
  621. } else if (typeof str.then === "function") {
  622. return Promise.resolve(str).then((value) => {
  623. return unescapeHTML(value);
  624. });
  625. } else if (str[Symbol.for("astro:slot-string")]) {
  626. return str;
  627. } else if (Symbol.iterator in str) {
  628. return unescapeChunks(str);
  629. } else if (Symbol.asyncIterator in str || hasGetReader(str)) {
  630. return unescapeChunksAsync(str);
  631. }
  632. }
  633. return markHTMLString(str);
  634. }
  635. const AstroJSX = "astro:jsx";
  636. function isVNode(vnode) {
  637. return vnode && typeof vnode === "object" && vnode[AstroJSX];
  638. }
  639. function isAstroComponentFactory(obj) {
  640. return obj == null ? false : obj.isAstroComponentFactory === true;
  641. }
  642. function isAPropagatingComponent(result, factory) {
  643. const hint = getPropagationHint(result, factory);
  644. return hint === "in-tree" || hint === "self";
  645. }
  646. function getPropagationHint(result, factory) {
  647. let hint = factory.propagation || "none";
  648. if (factory.moduleId && result.componentMetadata.has(factory.moduleId) && hint === "none") {
  649. hint = result.componentMetadata.get(factory.moduleId).propagation;
  650. }
  651. return hint;
  652. }
  653. function r(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f);}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}
  654. const PROP_TYPE = {
  655. Value: 0,
  656. JSON: 1,
  657. // Actually means Array
  658. RegExp: 2,
  659. Date: 3,
  660. Map: 4,
  661. Set: 5,
  662. BigInt: 6,
  663. URL: 7,
  664. Uint8Array: 8,
  665. Uint16Array: 9,
  666. Uint32Array: 10,
  667. Infinity: 11
  668. };
  669. function serializeArray(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
  670. if (parents.has(value)) {
  671. throw new Error(`Cyclic reference detected while serializing props for <${metadata.displayName} client:${metadata.hydrate}>!
  672. Cyclic references cannot be safely serialized for client-side usage. Please remove the cyclic reference.`);
  673. }
  674. parents.add(value);
  675. const serialized = value.map((v) => {
  676. return convertToSerializedForm(v, metadata, parents);
  677. });
  678. parents.delete(value);
  679. return serialized;
  680. }
  681. function serializeObject(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
  682. if (parents.has(value)) {
  683. throw new Error(`Cyclic reference detected while serializing props for <${metadata.displayName} client:${metadata.hydrate}>!
  684. Cyclic references cannot be safely serialized for client-side usage. Please remove the cyclic reference.`);
  685. }
  686. parents.add(value);
  687. const serialized = Object.fromEntries(
  688. Object.entries(value).map(([k, v]) => {
  689. return [k, convertToSerializedForm(v, metadata, parents)];
  690. })
  691. );
  692. parents.delete(value);
  693. return serialized;
  694. }
  695. function convertToSerializedForm(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
  696. const tag = Object.prototype.toString.call(value);
  697. switch (tag) {
  698. case "[object Date]": {
  699. return [PROP_TYPE.Date, value.toISOString()];
  700. }
  701. case "[object RegExp]": {
  702. return [PROP_TYPE.RegExp, value.source];
  703. }
  704. case "[object Map]": {
  705. return [PROP_TYPE.Map, serializeArray(Array.from(value), metadata, parents)];
  706. }
  707. case "[object Set]": {
  708. return [PROP_TYPE.Set, serializeArray(Array.from(value), metadata, parents)];
  709. }
  710. case "[object BigInt]": {
  711. return [PROP_TYPE.BigInt, value.toString()];
  712. }
  713. case "[object URL]": {
  714. return [PROP_TYPE.URL, value.toString()];
  715. }
  716. case "[object Array]": {
  717. return [PROP_TYPE.JSON, serializeArray(value, metadata, parents)];
  718. }
  719. case "[object Uint8Array]": {
  720. return [PROP_TYPE.Uint8Array, Array.from(value)];
  721. }
  722. case "[object Uint16Array]": {
  723. return [PROP_TYPE.Uint16Array, Array.from(value)];
  724. }
  725. case "[object Uint32Array]": {
  726. return [PROP_TYPE.Uint32Array, Array.from(value)];
  727. }
  728. default: {
  729. if (value !== null && typeof value === "object") {
  730. return [PROP_TYPE.Value, serializeObject(value, metadata, parents)];
  731. }
  732. if (value === Infinity) {
  733. return [PROP_TYPE.Infinity, 1];
  734. }
  735. if (value === -Infinity) {
  736. return [PROP_TYPE.Infinity, -1];
  737. }
  738. if (value === void 0) {
  739. return [PROP_TYPE.Value];
  740. }
  741. return [PROP_TYPE.Value, value];
  742. }
  743. }
  744. }
  745. function serializeProps(props, metadata) {
  746. const serialized = JSON.stringify(serializeObject(props, metadata));
  747. return serialized;
  748. }
  749. const transitionDirectivesToCopyOnIsland = Object.freeze([
  750. "data-astro-transition-scope",
  751. "data-astro-transition-persist",
  752. "data-astro-transition-persist-props"
  753. ]);
  754. function extractDirectives(inputProps, clientDirectives) {
  755. let extracted = {
  756. isPage: false,
  757. hydration: null,
  758. props: {},
  759. propsWithoutTransitionAttributes: {}
  760. };
  761. for (const [key, value] of Object.entries(inputProps)) {
  762. if (key.startsWith("server:")) {
  763. if (key === "server:root") {
  764. extracted.isPage = true;
  765. }
  766. }
  767. if (key.startsWith("client:")) {
  768. if (!extracted.hydration) {
  769. extracted.hydration = {
  770. directive: "",
  771. value: "",
  772. componentUrl: "",
  773. componentExport: { value: "" }
  774. };
  775. }
  776. switch (key) {
  777. case "client:component-path": {
  778. extracted.hydration.componentUrl = value;
  779. break;
  780. }
  781. case "client:component-export": {
  782. extracted.hydration.componentExport.value = value;
  783. break;
  784. }
  785. // This is a special prop added to prove that the client hydration method
  786. // was added statically.
  787. case "client:component-hydration": {
  788. break;
  789. }
  790. case "client:display-name": {
  791. break;
  792. }
  793. default: {
  794. extracted.hydration.directive = key.split(":")[1];
  795. extracted.hydration.value = value;
  796. if (!clientDirectives.has(extracted.hydration.directive)) {
  797. const hydrationMethods = Array.from(clientDirectives.keys()).map((d) => `client:${d}`).join(", ");
  798. throw new Error(
  799. `Error: invalid hydration directive "${key}". Supported hydration methods: ${hydrationMethods}`
  800. );
  801. }
  802. if (extracted.hydration.directive === "media" && typeof extracted.hydration.value !== "string") {
  803. throw new AstroError(MissingMediaQueryDirective);
  804. }
  805. break;
  806. }
  807. }
  808. } else {
  809. extracted.props[key] = value;
  810. if (!transitionDirectivesToCopyOnIsland.includes(key)) {
  811. extracted.propsWithoutTransitionAttributes[key] = value;
  812. }
  813. }
  814. }
  815. for (const sym of Object.getOwnPropertySymbols(inputProps)) {
  816. extracted.props[sym] = inputProps[sym];
  817. extracted.propsWithoutTransitionAttributes[sym] = inputProps[sym];
  818. }
  819. return extracted;
  820. }
  821. async function generateHydrateScript(scriptOptions, metadata) {
  822. const { renderer, result, astroId, props, attrs } = scriptOptions;
  823. const { hydrate, componentUrl, componentExport } = metadata;
  824. if (!componentExport.value) {
  825. throw new AstroError({
  826. ...NoMatchingImport,
  827. message: NoMatchingImport.message(metadata.displayName)
  828. });
  829. }
  830. const island = {
  831. children: "",
  832. props: {
  833. // This is for HMR, probably can avoid it in prod
  834. uid: astroId
  835. }
  836. };
  837. if (attrs) {
  838. for (const [key, value] of Object.entries(attrs)) {
  839. island.props[key] = escapeHTML(value);
  840. }
  841. }
  842. island.props["component-url"] = await result.resolve(decodeURI(componentUrl));
  843. if (renderer.clientEntrypoint) {
  844. island.props["component-export"] = componentExport.value;
  845. island.props["renderer-url"] = await result.resolve(
  846. decodeURI(renderer.clientEntrypoint.toString())
  847. );
  848. island.props["props"] = escapeHTML(serializeProps(props, metadata));
  849. }
  850. island.props["ssr"] = "";
  851. island.props["client"] = hydrate;
  852. let beforeHydrationUrl = await result.resolve("astro:scripts/before-hydration.js");
  853. if (beforeHydrationUrl.length) {
  854. island.props["before-hydration-url"] = beforeHydrationUrl;
  855. }
  856. island.props["opts"] = escapeHTML(
  857. JSON.stringify({
  858. name: metadata.displayName,
  859. value: metadata.hydrateArgs || ""
  860. })
  861. );
  862. transitionDirectivesToCopyOnIsland.forEach((name) => {
  863. if (typeof props[name] !== "undefined") {
  864. island.props[name] = props[name];
  865. }
  866. });
  867. return island;
  868. }
  869. /**
  870. * shortdash - https://github.com/bibig/node-shorthash
  871. *
  872. * @license
  873. *
  874. * (The MIT License)
  875. *
  876. * Copyright (c) 2013 Bibig <bibig@me.com>
  877. *
  878. * Permission is hereby granted, free of charge, to any person
  879. * obtaining a copy of this software and associated documentation
  880. * files (the "Software"), to deal in the Software without
  881. * restriction, including without limitation the rights to use,
  882. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  883. * copies of the Software, and to permit persons to whom the
  884. * Software is furnished to do so, subject to the following
  885. * conditions:
  886. *
  887. * The above copyright notice and this permission notice shall be
  888. * included in all copies or substantial portions of the Software.
  889. *
  890. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  891. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  892. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  893. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  894. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  895. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  896. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  897. * OTHER DEALINGS IN THE SOFTWARE.
  898. */
  899. const dictionary = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY";
  900. const binary = dictionary.length;
  901. function bitwise(str) {
  902. let hash = 0;
  903. if (str.length === 0) return hash;
  904. for (let i = 0; i < str.length; i++) {
  905. const ch = str.charCodeAt(i);
  906. hash = (hash << 5) - hash + ch;
  907. hash = hash & hash;
  908. }
  909. return hash;
  910. }
  911. function shorthash(text) {
  912. let num;
  913. let result = "";
  914. let integer = bitwise(text);
  915. const sign = integer < 0 ? "Z" : "";
  916. integer = Math.abs(integer);
  917. while (integer >= binary) {
  918. num = integer % binary;
  919. integer = Math.floor(integer / binary);
  920. result = dictionary[num] + result;
  921. }
  922. if (integer > 0) {
  923. result = dictionary[integer] + result;
  924. }
  925. return sign + result;
  926. }
  927. const headAndContentSym = Symbol.for("astro.headAndContent");
  928. function isHeadAndContent(obj) {
  929. return typeof obj === "object" && obj !== null && !!obj[headAndContentSym];
  930. }
  931. function createThinHead() {
  932. return {
  933. [headAndContentSym]: true
  934. };
  935. }
  936. var astro_island_prebuilt_default = `(()=>{var A=Object.defineProperty;var g=(i,o,a)=>o in i?A(i,o,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[o]=a;var d=(i,o,a)=>g(i,typeof o!="symbol"?o+"":o,a);{let i={0:t=>m(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t),11:t=>1/0*t},o=t=>{let[l,e]=t;return l in i?i[l](e):void 0},a=t=>t.map(o),m=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([l,e])=>[l,o(e)]));class y extends HTMLElement{constructor(){super(...arguments);d(this,"Component");d(this,"hydrator");d(this,"hydrate",async()=>{var b;if(!this.hydrator||!this.isConnected)return;let e=(b=this.parentElement)==null?void 0:b.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let c=this.querySelectorAll("astro-slot"),n={},h=this.querySelectorAll("template[data-astro-template]");for(let r of h){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("data-astro-template")||"default"]=r.innerHTML,r.remove())}for(let r of c){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("name")||"default"]=r.innerHTML)}let p;try{p=this.hasAttribute("props")?m(JSON.parse(this.getAttribute("props"))):{}}catch(r){let s=this.getAttribute("component-url")||"<unknown>",v=this.getAttribute("component-export");throw v&&(s+=\` (export \${v})\`),console.error(\`[hydrate] Error parsing props for component \${s}\`,this.getAttribute("props"),r),r}let u;await this.hydrator(this)(this.Component,p,n,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))});d(this,"unmount",()=>{this.isConnected||this.dispatchEvent(new CustomEvent("astro:unmount"))})}disconnectedCallback(){document.removeEventListener("astro:after-swap",this.unmount),document.addEventListener("astro:after-swap",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute("await-children")||document.readyState==="interactive"||document.readyState==="complete")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener("DOMContentLoaded",e),c.disconnect(),this.childrenConnectedCallback()},c=new MutationObserver(()=>{var n;((n=this.lastChild)==null?void 0:n.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue==="astro:end"&&(this.lastChild.remove(),e())});c.observe(this,{childList:!0}),document.addEventListener("DOMContentLoaded",e)}}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute("opts")),c=this.getAttribute("client");if(Astro[c]===void 0){window.addEventListener(\`astro:\${c}\`,()=>this.start(),{once:!0});return}try{await Astro[c](async()=>{let n=this.getAttribute("renderer-url"),[h,{default:p}]=await Promise.all([import(this.getAttribute("component-url")),n?import(n):()=>()=>{}]),u=this.getAttribute("component-export")||"default";if(!u.includes("."))this.Component=h[u];else{this.Component=h;for(let f of u.split("."))this.Component=this.Component[f]}return this.hydrator=p,this.hydrate},e,this)}catch(n){console.error(\`[astro-island] Error hydrating \${this.getAttribute("component-url")}\`,n)}}attributeChangedCallback(){this.hydrate()}}d(y,"observedAttributes",["props"]),customElements.get("astro-island")||customElements.define("astro-island",y)}})();`;
  937. const ISLAND_STYLES = "astro-island,astro-slot,astro-static-slot{display:contents}";
  938. function determineIfNeedsHydrationScript(result) {
  939. if (result._metadata.hasHydrationScript) {
  940. return false;
  941. }
  942. return result._metadata.hasHydrationScript = true;
  943. }
  944. function determinesIfNeedsDirectiveScript(result, directive) {
  945. if (result._metadata.hasDirectives.has(directive)) {
  946. return false;
  947. }
  948. result._metadata.hasDirectives.add(directive);
  949. return true;
  950. }
  951. function getDirectiveScriptText(result, directive) {
  952. const clientDirectives = result.clientDirectives;
  953. const clientDirective = clientDirectives.get(directive);
  954. if (!clientDirective) {
  955. throw new Error(`Unknown directive: ${directive}`);
  956. }
  957. return clientDirective;
  958. }
  959. function getPrescripts(result, type, directive) {
  960. switch (type) {
  961. case "both":
  962. return `<style>${ISLAND_STYLES}</style><script>${getDirectiveScriptText(result, directive)}</script><script>${astro_island_prebuilt_default}</script>`;
  963. case "directive":
  964. return `<script>${getDirectiveScriptText(result, directive)}</script>`;
  965. }
  966. }
  967. function renderCspContent(result) {
  968. const finalScriptHashes = /* @__PURE__ */ new Set();
  969. const finalStyleHashes = /* @__PURE__ */ new Set();
  970. for (const scriptHash of result.scriptHashes) {
  971. finalScriptHashes.add(`'${scriptHash}'`);
  972. }
  973. for (const styleHash of result.styleHashes) {
  974. finalStyleHashes.add(`'${styleHash}'`);
  975. }
  976. for (const styleHash of result._metadata.extraStyleHashes) {
  977. finalStyleHashes.add(`'${styleHash}'`);
  978. }
  979. for (const scriptHash of result._metadata.extraScriptHashes) {
  980. finalScriptHashes.add(`'${scriptHash}'`);
  981. }
  982. let directives;
  983. if (result.directives.length > 0) {
  984. directives = result.directives.join(";") + ";";
  985. }
  986. let scriptResources = "'self'";
  987. if (result.scriptResources.length > 0) {
  988. scriptResources = result.scriptResources.map((r) => `${r}`).join(" ");
  989. }
  990. let styleResources = "'self'";
  991. if (result.styleResources.length > 0) {
  992. styleResources = result.styleResources.map((r) => `${r}`).join(" ");
  993. }
  994. const strictDynamic = result.isStrictDynamic ? ` 'strict-dynamic'` : "";
  995. const scriptSrc = `script-src ${scriptResources} ${Array.from(finalScriptHashes).join(" ")}${strictDynamic};`;
  996. const styleSrc = `style-src ${styleResources} ${Array.from(finalStyleHashes).join(" ")};`;
  997. return [directives, scriptSrc, styleSrc].filter(Boolean).join(" ");
  998. }
  999. const RenderInstructionSymbol = Symbol.for("astro:render");
  1000. function createRenderInstruction(instruction) {
  1001. return Object.defineProperty(instruction, RenderInstructionSymbol, {
  1002. value: true
  1003. });
  1004. }
  1005. function isRenderInstruction(chunk) {
  1006. return chunk && typeof chunk === "object" && chunk[RenderInstructionSymbol];
  1007. }
  1008. const voidElementNames = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;
  1009. const htmlBooleanAttributes = /^(?:allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|inert|loop|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|selected|itemscope)$/i;
  1010. const AMPERSAND_REGEX = /&/g;
  1011. const DOUBLE_QUOTE_REGEX = /"/g;
  1012. const STATIC_DIRECTIVES = /* @__PURE__ */ new Set(["set:html", "set:text"]);
  1013. const toIdent = (k) => k.trim().replace(/(?!^)\b\w|\s+|\W+/g, (match, index) => {
  1014. if (/\W/.test(match)) return "";
  1015. return index === 0 ? match : match.toUpperCase();
  1016. });
  1017. const toAttributeString = (value, shouldEscape = true) => shouldEscape ? String(value).replace(AMPERSAND_REGEX, "&#38;").replace(DOUBLE_QUOTE_REGEX, "&#34;") : value;
  1018. const kebab = (k) => k.toLowerCase() === k ? k : k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
  1019. const toStyleString = (obj) => Object.entries(obj).filter(([_, v]) => typeof v === "string" && v.trim() || typeof v === "number").map(([k, v]) => {
  1020. if (k[0] !== "-" && k[1] !== "-") return `${kebab(k)}:${v}`;
  1021. return `${k}:${v}`;
  1022. }).join(";");
  1023. function defineScriptVars(vars) {
  1024. let output = "";
  1025. for (const [key, value] of Object.entries(vars)) {
  1026. output += `const ${toIdent(key)} = ${JSON.stringify(value)?.replace(
  1027. /<\/script>/g,
  1028. "\\x3C/script>"
  1029. )};
  1030. `;
  1031. }
  1032. return markHTMLString(output);
  1033. }
  1034. function formatList(values) {
  1035. if (values.length === 1) {
  1036. return values[0];
  1037. }
  1038. return `${values.slice(0, -1).join(", ")} or ${values[values.length - 1]}`;
  1039. }
  1040. function isCustomElement(tagName) {
  1041. return tagName.includes("-");
  1042. }
  1043. function handleBooleanAttribute(key, value, shouldEscape, tagName) {
  1044. if (tagName && isCustomElement(tagName)) {
  1045. return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
  1046. }
  1047. return markHTMLString(value ? ` ${key}` : "");
  1048. }
  1049. function addAttribute(value, key, shouldEscape = true, tagName = "") {
  1050. if (value == null) {
  1051. return "";
  1052. }
  1053. if (STATIC_DIRECTIVES.has(key)) {
  1054. console.warn(`[astro] The "${key}" directive cannot be applied dynamically at runtime. It will not be rendered as an attribute.
  1055. Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the dynamic spread syntax (\`{...{ "${key}": value }}\`).`);
  1056. return "";
  1057. }
  1058. if (key === "class:list") {
  1059. const listValue = toAttributeString(clsx(value), shouldEscape);
  1060. if (listValue === "") {
  1061. return "";
  1062. }
  1063. return markHTMLString(` ${key.slice(0, -5)}="${listValue}"`);
  1064. }
  1065. if (key === "style" && !(value instanceof HTMLString)) {
  1066. if (Array.isArray(value) && value.length === 2) {
  1067. return markHTMLString(
  1068. ` ${key}="${toAttributeString(`${toStyleString(value[0])};${value[1]}`, shouldEscape)}"`
  1069. );
  1070. }
  1071. if (typeof value === "object") {
  1072. return markHTMLString(` ${key}="${toAttributeString(toStyleString(value), shouldEscape)}"`);
  1073. }
  1074. }
  1075. if (key === "className") {
  1076. return markHTMLString(` class="${toAttributeString(value, shouldEscape)}"`);
  1077. }
  1078. if (typeof value === "string" && value.includes("&") && isHttpUrl(value)) {
  1079. return markHTMLString(` ${key}="${toAttributeString(value, false)}"`);
  1080. }
  1081. if (htmlBooleanAttributes.test(key)) {
  1082. return handleBooleanAttribute(key, value, shouldEscape, tagName);
  1083. }
  1084. if (value === "") {
  1085. return markHTMLString(` ${key}`);
  1086. }
  1087. if (key === "popover" && typeof value === "boolean") {
  1088. return handleBooleanAttribute(key, value, shouldEscape, tagName);
  1089. }
  1090. if (key === "download" && typeof value === "boolean") {
  1091. return handleBooleanAttribute(key, value, shouldEscape, tagName);
  1092. }
  1093. return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
  1094. }
  1095. function internalSpreadAttributes(values, shouldEscape = true, tagName) {
  1096. let output = "";
  1097. for (const [key, value] of Object.entries(values)) {
  1098. output += addAttribute(value, key, shouldEscape, tagName);
  1099. }
  1100. return markHTMLString(output);
  1101. }
  1102. function renderElement$1(name, { props: _props, children = "" }, shouldEscape = true) {
  1103. const { lang: _, "data-astro-id": astroId, "define:vars": defineVars, ...props } = _props;
  1104. if (defineVars) {
  1105. if (name === "style") {
  1106. delete props["is:global"];
  1107. delete props["is:scoped"];
  1108. }
  1109. if (name === "script") {
  1110. delete props.hoist;
  1111. children = defineScriptVars(defineVars) + "\n" + children;
  1112. }
  1113. }
  1114. if ((children == null || children == "") && voidElementNames.test(name)) {
  1115. return `<${name}${internalSpreadAttributes(props, shouldEscape, name)}>`;
  1116. }
  1117. return `<${name}${internalSpreadAttributes(props, shouldEscape, name)}>${children}</${name}>`;
  1118. }
  1119. const noop = () => {
  1120. };
  1121. class BufferedRenderer {
  1122. chunks = [];
  1123. renderPromise;
  1124. destination;
  1125. /**
  1126. * Determines whether buffer has been flushed
  1127. * to the final destination.
  1128. */
  1129. flushed = false;
  1130. constructor(destination, renderFunction) {
  1131. this.destination = destination;
  1132. this.renderPromise = renderFunction(this);
  1133. if (isPromise(this.renderPromise)) {
  1134. Promise.resolve(this.renderPromise).catch(noop);
  1135. }
  1136. }
  1137. write(chunk) {
  1138. if (this.flushed) {
  1139. this.destination.write(chunk);
  1140. } else {
  1141. this.chunks.push(chunk);
  1142. }
  1143. }
  1144. flush() {
  1145. if (this.flushed) {
  1146. throw new Error("The render buffer has already been flushed.");
  1147. }
  1148. this.flushed = true;
  1149. for (const chunk of this.chunks) {
  1150. this.destination.write(chunk);
  1151. }
  1152. return this.renderPromise;
  1153. }
  1154. }
  1155. function createBufferedRenderer(destination, renderFunction) {
  1156. return new BufferedRenderer(destination, renderFunction);
  1157. }
  1158. const isNode = typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]";
  1159. const isDeno = typeof Deno !== "undefined";
  1160. function promiseWithResolvers() {
  1161. let resolve, reject;
  1162. const promise = new Promise((_resolve, _reject) => {
  1163. resolve = _resolve;
  1164. reject = _reject;
  1165. });
  1166. return {
  1167. promise,
  1168. resolve,
  1169. reject
  1170. };
  1171. }
  1172. const VALID_PROTOCOLS = ["http:", "https:"];
  1173. function isHttpUrl(url) {
  1174. try {
  1175. const parsedUrl = new URL(url);
  1176. return VALID_PROTOCOLS.includes(parsedUrl.protocol);
  1177. } catch {
  1178. return false;
  1179. }
  1180. }
  1181. const uniqueElements = (item, index, all) => {
  1182. const props = JSON.stringify(item.props);
  1183. const children = item.children;
  1184. return index === all.findIndex((i) => JSON.stringify(i.props) === props && i.children == children);
  1185. };
  1186. function renderAllHeadContent(result) {
  1187. result._metadata.hasRenderedHead = true;
  1188. let content = "";
  1189. if (result.shouldInjectCspMetaTags && result.cspDestination === "meta") {
  1190. content += renderElement$1(
  1191. "meta",
  1192. {
  1193. props: {
  1194. "http-equiv": "content-security-policy",
  1195. content: renderCspContent(result)
  1196. },
  1197. children: ""
  1198. },
  1199. false
  1200. );
  1201. }
  1202. const styles = Array.from(result.styles).filter(uniqueElements).map(
  1203. (style) => style.props.rel === "stylesheet" ? renderElement$1("link", style) : renderElement$1("style", style)
  1204. );
  1205. result.styles.clear();
  1206. const scripts = Array.from(result.scripts).filter(uniqueElements).map((script) => {
  1207. if (result.userAssetsBase) {
  1208. script.props.src = (result.base === "/" ? "" : result.base) + result.userAssetsBase + script.props.src;
  1209. }
  1210. return renderElement$1("script", script, false);
  1211. });
  1212. const links = Array.from(result.links).filter(uniqueElements).map((link) => renderElement$1("link", link, false));
  1213. content += styles.join("\n") + links.join("\n") + scripts.join("\n");
  1214. if (result._metadata.extraHead.length > 0) {
  1215. for (const part of result._metadata.extraHead) {
  1216. content += part;
  1217. }
  1218. }
  1219. return markHTMLString(content);
  1220. }
  1221. function renderHead() {
  1222. return createRenderInstruction({ type: "head" });
  1223. }
  1224. function maybeRenderHead() {
  1225. return createRenderInstruction({ type: "maybe-head" });
  1226. }
  1227. function encodeHexUpperCase(data) {
  1228. let result = "";
  1229. for (let i = 0; i < data.length; i++) {
  1230. result += alphabetUpperCase[data[i] >> 4];
  1231. result += alphabetUpperCase[data[i] & 0x0f];
  1232. }
  1233. return result;
  1234. }
  1235. function decodeHex(data) {
  1236. if (data.length % 2 !== 0) {
  1237. throw new Error("Invalid hex string");
  1238. }
  1239. const result = new Uint8Array(data.length / 2);
  1240. for (let i = 0; i < data.length; i += 2) {
  1241. if (!(data[i] in decodeMap)) {
  1242. throw new Error("Invalid character");
  1243. }
  1244. if (!(data[i + 1] in decodeMap)) {
  1245. throw new Error("Invalid character");
  1246. }
  1247. result[i / 2] |= decodeMap[data[i]] << 4;
  1248. result[i / 2] |= decodeMap[data[i + 1]];
  1249. }
  1250. return result;
  1251. }
  1252. const alphabetUpperCase = "0123456789ABCDEF";
  1253. const decodeMap = {
  1254. "0": 0,
  1255. "1": 1,
  1256. "2": 2,
  1257. "3": 3,
  1258. "4": 4,
  1259. "5": 5,
  1260. "6": 6,
  1261. "7": 7,
  1262. "8": 8,
  1263. "9": 9,
  1264. a: 10,
  1265. A: 10,
  1266. b: 11,
  1267. B: 11,
  1268. c: 12,
  1269. C: 12,
  1270. d: 13,
  1271. D: 13,
  1272. e: 14,
  1273. E: 14,
  1274. f: 15,
  1275. F: 15
  1276. };
  1277. var EncodingPadding$1;
  1278. (function (EncodingPadding) {
  1279. EncodingPadding[EncodingPadding["Include"] = 0] = "Include";
  1280. EncodingPadding[EncodingPadding["None"] = 1] = "None";
  1281. })(EncodingPadding$1 || (EncodingPadding$1 = {}));
  1282. var DecodingPadding$1;
  1283. (function (DecodingPadding) {
  1284. DecodingPadding[DecodingPadding["Required"] = 0] = "Required";
  1285. DecodingPadding[DecodingPadding["Ignore"] = 1] = "Ignore";
  1286. })(DecodingPadding$1 || (DecodingPadding$1 = {}));
  1287. function encodeBase64(bytes) {
  1288. return encodeBase64_internal(bytes, base64Alphabet, EncodingPadding.Include);
  1289. }
  1290. function encodeBase64_internal(bytes, alphabet, padding) {
  1291. let result = "";
  1292. for (let i = 0; i < bytes.byteLength; i += 3) {
  1293. let buffer = 0;
  1294. let bufferBitSize = 0;
  1295. for (let j = 0; j < 3 && i + j < bytes.byteLength; j++) {
  1296. buffer = (buffer << 8) | bytes[i + j];
  1297. bufferBitSize += 8;
  1298. }
  1299. for (let j = 0; j < 4; j++) {
  1300. if (bufferBitSize >= 6) {
  1301. result += alphabet[(buffer >> (bufferBitSize - 6)) & 0x3f];
  1302. bufferBitSize -= 6;
  1303. }
  1304. else if (bufferBitSize > 0) {
  1305. result += alphabet[(buffer << (6 - bufferBitSize)) & 0x3f];
  1306. bufferBitSize = 0;
  1307. }
  1308. else if (padding === EncodingPadding.Include) {
  1309. result += "=";
  1310. }
  1311. }
  1312. }
  1313. return result;
  1314. }
  1315. const base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  1316. function decodeBase64(encoded) {
  1317. return decodeBase64_internal(encoded, base64DecodeMap, DecodingPadding.Required);
  1318. }
  1319. function decodeBase64_internal(encoded, decodeMap, padding) {
  1320. const result = new Uint8Array(Math.ceil(encoded.length / 4) * 3);
  1321. let totalBytes = 0;
  1322. for (let i = 0; i < encoded.length; i += 4) {
  1323. let chunk = 0;
  1324. let bitsRead = 0;
  1325. for (let j = 0; j < 4; j++) {
  1326. if (padding === DecodingPadding.Required && encoded[i + j] === "=") {
  1327. continue;
  1328. }
  1329. if (padding === DecodingPadding.Ignore &&
  1330. (i + j >= encoded.length || encoded[i + j] === "=")) {
  1331. continue;
  1332. }
  1333. if (j > 0 && encoded[i + j - 1] === "=") {
  1334. throw new Error("Invalid padding");
  1335. }
  1336. if (!(encoded[i + j] in decodeMap)) {
  1337. throw new Error("Invalid character");
  1338. }
  1339. chunk |= decodeMap[encoded[i + j]] << ((3 - j) * 6);
  1340. bitsRead += 6;
  1341. }
  1342. if (bitsRead < 24) {
  1343. let unused;
  1344. if (bitsRead === 12) {
  1345. unused = chunk & 0xffff;
  1346. }
  1347. else if (bitsRead === 18) {
  1348. unused = chunk & 0xff;
  1349. }
  1350. else {
  1351. throw new Error("Invalid padding");
  1352. }
  1353. if (unused !== 0) {
  1354. throw new Error("Invalid padding");
  1355. }
  1356. }
  1357. const byteLength = Math.floor(bitsRead / 8);
  1358. for (let i = 0; i < byteLength; i++) {
  1359. result[totalBytes] = (chunk >> (16 - i * 8)) & 0xff;
  1360. totalBytes++;
  1361. }
  1362. }
  1363. return result.slice(0, totalBytes);
  1364. }
  1365. var EncodingPadding;
  1366. (function (EncodingPadding) {
  1367. EncodingPadding[EncodingPadding["Include"] = 0] = "Include";
  1368. EncodingPadding[EncodingPadding["None"] = 1] = "None";
  1369. })(EncodingPadding || (EncodingPadding = {}));
  1370. var DecodingPadding;
  1371. (function (DecodingPadding) {
  1372. DecodingPadding[DecodingPadding["Required"] = 0] = "Required";
  1373. DecodingPadding[DecodingPadding["Ignore"] = 1] = "Ignore";
  1374. })(DecodingPadding || (DecodingPadding = {}));
  1375. const base64DecodeMap = {
  1376. "0": 52,
  1377. "1": 53,
  1378. "2": 54,
  1379. "3": 55,
  1380. "4": 56,
  1381. "5": 57,
  1382. "6": 58,
  1383. "7": 59,
  1384. "8": 60,
  1385. "9": 61,
  1386. A: 0,
  1387. B: 1,
  1388. C: 2,
  1389. D: 3,
  1390. E: 4,
  1391. F: 5,
  1392. G: 6,
  1393. H: 7,
  1394. I: 8,
  1395. J: 9,
  1396. K: 10,
  1397. L: 11,
  1398. M: 12,
  1399. N: 13,
  1400. O: 14,
  1401. P: 15,
  1402. Q: 16,
  1403. R: 17,
  1404. S: 18,
  1405. T: 19,
  1406. U: 20,
  1407. V: 21,
  1408. W: 22,
  1409. X: 23,
  1410. Y: 24,
  1411. Z: 25,
  1412. a: 26,
  1413. b: 27,
  1414. c: 28,
  1415. d: 29,
  1416. e: 30,
  1417. f: 31,
  1418. g: 32,
  1419. h: 33,
  1420. i: 34,
  1421. j: 35,
  1422. k: 36,
  1423. l: 37,
  1424. m: 38,
  1425. n: 39,
  1426. o: 40,
  1427. p: 41,
  1428. q: 42,
  1429. r: 43,
  1430. s: 44,
  1431. t: 45,
  1432. u: 46,
  1433. v: 47,
  1434. w: 48,
  1435. x: 49,
  1436. y: 50,
  1437. z: 51,
  1438. "+": 62,
  1439. "/": 63
  1440. };
  1441. var util;
  1442. (function (util) {
  1443. util.assertEqual = (_) => { };
  1444. function assertIs(_arg) { }
  1445. util.assertIs = assertIs;
  1446. function assertNever(_x) {
  1447. throw new Error();
  1448. }
  1449. util.assertNever = assertNever;
  1450. util.arrayToEnum = (items) => {
  1451. const obj = {};
  1452. for (const item of items) {
  1453. obj[item] = item;
  1454. }
  1455. return obj;
  1456. };
  1457. util.getValidEnumValues = (obj) => {
  1458. const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
  1459. const filtered = {};
  1460. for (const k of validKeys) {
  1461. filtered[k] = obj[k];
  1462. }
  1463. return util.objectValues(filtered);
  1464. };
  1465. util.objectValues = (obj) => {
  1466. return util.objectKeys(obj).map(function (e) {
  1467. return obj[e];
  1468. });
  1469. };
  1470. util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
  1471. ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
  1472. : (object) => {
  1473. const keys = [];
  1474. for (const key in object) {
  1475. if (Object.prototype.hasOwnProperty.call(object, key)) {
  1476. keys.push(key);
  1477. }
  1478. }
  1479. return keys;
  1480. };
  1481. util.find = (arr, checker) => {
  1482. for (const item of arr) {
  1483. if (checker(item))
  1484. return item;
  1485. }
  1486. return undefined;
  1487. };
  1488. util.isInteger = typeof Number.isInteger === "function"
  1489. ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
  1490. : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
  1491. function joinValues(array, separator = " | ") {
  1492. return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
  1493. }
  1494. util.joinValues = joinValues;
  1495. util.jsonStringifyReplacer = (_, value) => {
  1496. if (typeof value === "bigint") {
  1497. return value.toString();
  1498. }
  1499. return value;
  1500. };
  1501. })(util || (util = {}));
  1502. var objectUtil;
  1503. (function (objectUtil) {
  1504. objectUtil.mergeShapes = (first, second) => {
  1505. return {
  1506. ...first,
  1507. ...second, // second overwrites first
  1508. };
  1509. };
  1510. })(objectUtil || (objectUtil = {}));
  1511. const ZodParsedType = util.arrayToEnum([
  1512. "string",
  1513. "nan",
  1514. "number",
  1515. "integer",
  1516. "float",
  1517. "boolean",
  1518. "date",
  1519. "bigint",
  1520. "symbol",
  1521. "function",
  1522. "undefined",
  1523. "null",
  1524. "array",
  1525. "object",
  1526. "unknown",
  1527. "promise",
  1528. "void",
  1529. "never",
  1530. "map",
  1531. "set",
  1532. ]);
  1533. const getParsedType = (data) => {
  1534. const t = typeof data;
  1535. switch (t) {
  1536. case "undefined":
  1537. return ZodParsedType.undefined;
  1538. case "string":
  1539. return ZodParsedType.string;
  1540. case "number":
  1541. return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
  1542. case "boolean":
  1543. return ZodParsedType.boolean;
  1544. case "function":
  1545. return ZodParsedType.function;
  1546. case "bigint":
  1547. return ZodParsedType.bigint;
  1548. case "symbol":
  1549. return ZodParsedType.symbol;
  1550. case "object":
  1551. if (Array.isArray(data)) {
  1552. return ZodParsedType.array;
  1553. }
  1554. if (data === null) {
  1555. return ZodParsedType.null;
  1556. }
  1557. if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
  1558. return ZodParsedType.promise;
  1559. }
  1560. if (typeof Map !== "undefined" && data instanceof Map) {
  1561. return ZodParsedType.map;
  1562. }
  1563. if (typeof Set !== "undefined" && data instanceof Set) {
  1564. return ZodParsedType.set;
  1565. }
  1566. if (typeof Date !== "undefined" && data instanceof Date) {
  1567. return ZodParsedType.date;
  1568. }
  1569. return ZodParsedType.object;
  1570. default:
  1571. return ZodParsedType.unknown;
  1572. }
  1573. };
  1574. const ZodIssueCode = util.arrayToEnum([
  1575. "invalid_type",
  1576. "invalid_literal",
  1577. "custom",
  1578. "invalid_union",
  1579. "invalid_union_discriminator",
  1580. "invalid_enum_value",
  1581. "unrecognized_keys",
  1582. "invalid_arguments",
  1583. "invalid_return_type",
  1584. "invalid_date",
  1585. "invalid_string",
  1586. "too_small",
  1587. "too_big",
  1588. "invalid_intersection_types",
  1589. "not_multiple_of",
  1590. "not_finite",
  1591. ]);
  1592. class ZodError extends Error {
  1593. get errors() {
  1594. return this.issues;
  1595. }
  1596. constructor(issues) {
  1597. super();
  1598. this.issues = [];
  1599. this.addIssue = (sub) => {
  1600. this.issues = [...this.issues, sub];
  1601. };
  1602. this.addIssues = (subs = []) => {
  1603. this.issues = [...this.issues, ...subs];
  1604. };
  1605. const actualProto = new.target.prototype;
  1606. if (Object.setPrototypeOf) {
  1607. // eslint-disable-next-line ban/ban
  1608. Object.setPrototypeOf(this, actualProto);
  1609. }
  1610. else {
  1611. this.__proto__ = actualProto;
  1612. }
  1613. this.name = "ZodError";
  1614. this.issues = issues;
  1615. }
  1616. format(_mapper) {
  1617. const mapper = _mapper ||
  1618. function (issue) {
  1619. return issue.message;
  1620. };
  1621. const fieldErrors = { _errors: [] };
  1622. const processError = (error) => {
  1623. for (const issue of error.issues) {
  1624. if (issue.code === "invalid_union") {
  1625. issue.unionErrors.map(processError);
  1626. }
  1627. else if (issue.code === "invalid_return_type") {
  1628. processError(issue.returnTypeError);
  1629. }
  1630. else if (issue.code === "invalid_arguments") {
  1631. processError(issue.argumentsError);
  1632. }
  1633. else if (issue.path.length === 0) {
  1634. fieldErrors._errors.push(mapper(issue));
  1635. }
  1636. else {
  1637. let curr = fieldErrors;
  1638. let i = 0;
  1639. while (i < issue.path.length) {
  1640. const el = issue.path[i];
  1641. const terminal = i === issue.path.length - 1;
  1642. if (!terminal) {
  1643. curr[el] = curr[el] || { _errors: [] };
  1644. // if (typeof el === "string") {
  1645. // curr[el] = curr[el] || { _errors: [] };
  1646. // } else if (typeof el === "number") {
  1647. // const errorArray: any = [];
  1648. // errorArray._errors = [];
  1649. // curr[el] = curr[el] || errorArray;
  1650. // }
  1651. }
  1652. else {
  1653. curr[el] = curr[el] || { _errors: [] };
  1654. curr[el]._errors.push(mapper(issue));
  1655. }
  1656. curr = curr[el];
  1657. i++;
  1658. }
  1659. }
  1660. }
  1661. };
  1662. processError(this);
  1663. return fieldErrors;
  1664. }
  1665. static assert(value) {
  1666. if (!(value instanceof ZodError)) {
  1667. throw new Error(`Not a ZodError: ${value}`);
  1668. }
  1669. }
  1670. toString() {
  1671. return this.message;
  1672. }
  1673. get message() {
  1674. return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  1675. }
  1676. get isEmpty() {
  1677. return this.issues.length === 0;
  1678. }
  1679. flatten(mapper = (issue) => issue.message) {
  1680. const fieldErrors = {};
  1681. const formErrors = [];
  1682. for (const sub of this.issues) {
  1683. if (sub.path.length > 0) {
  1684. const firstEl = sub.path[0];
  1685. fieldErrors[firstEl] = fieldErrors[firstEl] || [];
  1686. fieldErrors[firstEl].push(mapper(sub));
  1687. }
  1688. else {
  1689. formErrors.push(mapper(sub));
  1690. }
  1691. }
  1692. return { formErrors, fieldErrors };
  1693. }
  1694. get formErrors() {
  1695. return this.flatten();
  1696. }
  1697. }
  1698. ZodError.create = (issues) => {
  1699. const error = new ZodError(issues);
  1700. return error;
  1701. };
  1702. const errorMap = (issue, _ctx) => {
  1703. let message;
  1704. switch (issue.code) {
  1705. case ZodIssueCode.invalid_type:
  1706. if (issue.received === ZodParsedType.undefined) {
  1707. message = "Required";
  1708. }
  1709. else {
  1710. message = `Expected ${issue.expected}, received ${issue.received}`;
  1711. }
  1712. break;
  1713. case ZodIssueCode.invalid_literal:
  1714. message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
  1715. break;
  1716. case ZodIssueCode.unrecognized_keys:
  1717. message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
  1718. break;
  1719. case ZodIssueCode.invalid_union:
  1720. message = `Invalid input`;
  1721. break;
  1722. case ZodIssueCode.invalid_union_discriminator:
  1723. message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
  1724. break;
  1725. case ZodIssueCode.invalid_enum_value:
  1726. message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
  1727. break;
  1728. case ZodIssueCode.invalid_arguments:
  1729. message = `Invalid function arguments`;
  1730. break;
  1731. case ZodIssueCode.invalid_return_type:
  1732. message = `Invalid function return type`;
  1733. break;
  1734. case ZodIssueCode.invalid_date:
  1735. message = `Invalid date`;
  1736. break;
  1737. case ZodIssueCode.invalid_string:
  1738. if (typeof issue.validation === "object") {
  1739. if ("includes" in issue.validation) {
  1740. message = `Invalid input: must include "${issue.validation.includes}"`;
  1741. if (typeof issue.validation.position === "number") {
  1742. message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
  1743. }
  1744. }
  1745. else if ("startsWith" in issue.validation) {
  1746. message = `Invalid input: must start with "${issue.validation.startsWith}"`;
  1747. }
  1748. else if ("endsWith" in issue.validation) {
  1749. message = `Invalid input: must end with "${issue.validation.endsWith}"`;
  1750. }
  1751. else {
  1752. util.assertNever(issue.validation);
  1753. }
  1754. }
  1755. else if (issue.validation !== "regex") {
  1756. message = `Invalid ${issue.validation}`;
  1757. }
  1758. else {
  1759. message = "Invalid";
  1760. }
  1761. break;
  1762. case ZodIssueCode.too_small:
  1763. if (issue.type === "array")
  1764. message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
  1765. else if (issue.type === "string")
  1766. message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
  1767. else if (issue.type === "number")
  1768. message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
  1769. else if (issue.type === "bigint")
  1770. message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
  1771. else if (issue.type === "date")
  1772. message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
  1773. else
  1774. message = "Invalid input";
  1775. break;
  1776. case ZodIssueCode.too_big:
  1777. if (issue.type === "array")
  1778. message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
  1779. else if (issue.type === "string")
  1780. message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
  1781. else if (issue.type === "number")
  1782. message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
  1783. else if (issue.type === "bigint")
  1784. message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
  1785. else if (issue.type === "date")
  1786. message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
  1787. else
  1788. message = "Invalid input";
  1789. break;
  1790. case ZodIssueCode.custom:
  1791. message = `Invalid input`;
  1792. break;
  1793. case ZodIssueCode.invalid_intersection_types:
  1794. message = `Intersection results could not be merged`;
  1795. break;
  1796. case ZodIssueCode.not_multiple_of:
  1797. message = `Number must be a multiple of ${issue.multipleOf}`;
  1798. break;
  1799. case ZodIssueCode.not_finite:
  1800. message = "Number must be finite";
  1801. break;
  1802. default:
  1803. message = _ctx.defaultError;
  1804. util.assertNever(issue);
  1805. }
  1806. return { message };
  1807. };
  1808. let overrideErrorMap = errorMap;
  1809. function getErrorMap() {
  1810. return overrideErrorMap;
  1811. }
  1812. const makeIssue = (params) => {
  1813. const { data, path, errorMaps, issueData } = params;
  1814. const fullPath = [...path, ...(issueData.path || [])];
  1815. const fullIssue = {
  1816. ...issueData,
  1817. path: fullPath,
  1818. };
  1819. if (issueData.message !== undefined) {
  1820. return {
  1821. ...issueData,
  1822. path: fullPath,
  1823. message: issueData.message,
  1824. };
  1825. }
  1826. let errorMessage = "";
  1827. const maps = errorMaps
  1828. .filter((m) => !!m)
  1829. .slice()
  1830. .reverse();
  1831. for (const map of maps) {
  1832. errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
  1833. }
  1834. return {
  1835. ...issueData,
  1836. path: fullPath,
  1837. message: errorMessage,
  1838. };
  1839. };
  1840. function addIssueToContext(ctx, issueData) {
  1841. const overrideMap = getErrorMap();
  1842. const issue = makeIssue({
  1843. issueData: issueData,
  1844. data: ctx.data,
  1845. path: ctx.path,
  1846. errorMaps: [
  1847. ctx.common.contextualErrorMap, // contextual error map is first priority
  1848. ctx.schemaErrorMap, // then schema-bound map if available
  1849. overrideMap, // then global override map
  1850. overrideMap === errorMap ? undefined : errorMap, // then global default map
  1851. ].filter((x) => !!x),
  1852. });
  1853. ctx.common.issues.push(issue);
  1854. }
  1855. class ParseStatus {
  1856. constructor() {
  1857. this.value = "valid";
  1858. }
  1859. dirty() {
  1860. if (this.value === "valid")
  1861. this.value = "dirty";
  1862. }
  1863. abort() {
  1864. if (this.value !== "aborted")
  1865. this.value = "aborted";
  1866. }
  1867. static mergeArray(status, results) {
  1868. const arrayValue = [];
  1869. for (const s of results) {
  1870. if (s.status === "aborted")
  1871. return INVALID;
  1872. if (s.status === "dirty")
  1873. status.dirty();
  1874. arrayValue.push(s.value);
  1875. }
  1876. return { status: status.value, value: arrayValue };
  1877. }
  1878. static async mergeObjectAsync(status, pairs) {
  1879. const syncPairs = [];
  1880. for (const pair of pairs) {
  1881. const key = await pair.key;
  1882. const value = await pair.value;
  1883. syncPairs.push({
  1884. key,
  1885. value,
  1886. });
  1887. }
  1888. return ParseStatus.mergeObjectSync(status, syncPairs);
  1889. }
  1890. static mergeObjectSync(status, pairs) {
  1891. const finalObject = {};
  1892. for (const pair of pairs) {
  1893. const { key, value } = pair;
  1894. if (key.status === "aborted")
  1895. return INVALID;
  1896. if (value.status === "aborted")
  1897. return INVALID;
  1898. if (key.status === "dirty")
  1899. status.dirty();
  1900. if (value.status === "dirty")
  1901. status.dirty();
  1902. if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
  1903. finalObject[key.value] = value.value;
  1904. }
  1905. }
  1906. return { status: status.value, value: finalObject };
  1907. }
  1908. }
  1909. const INVALID = Object.freeze({
  1910. status: "aborted",
  1911. });
  1912. const DIRTY = (value) => ({ status: "dirty", value });
  1913. const OK = (value) => ({ status: "valid", value });
  1914. const isAborted = (x) => x.status === "aborted";
  1915. const isDirty = (x) => x.status === "dirty";
  1916. const isValid = (x) => x.status === "valid";
  1917. const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
  1918. var errorUtil;
  1919. (function (errorUtil) {
  1920. errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  1921. // biome-ignore lint:
  1922. errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
  1923. })(errorUtil || (errorUtil = {}));
  1924. class ParseInputLazyPath {
  1925. constructor(parent, value, path, key) {
  1926. this._cachedPath = [];
  1927. this.parent = parent;
  1928. this.data = value;
  1929. this._path = path;
  1930. this._key = key;
  1931. }
  1932. get path() {
  1933. if (!this._cachedPath.length) {
  1934. if (Array.isArray(this._key)) {
  1935. this._cachedPath.push(...this._path, ...this._key);
  1936. }
  1937. else {
  1938. this._cachedPath.push(...this._path, this._key);
  1939. }
  1940. }
  1941. return this._cachedPath;
  1942. }
  1943. }
  1944. const handleResult = (ctx, result) => {
  1945. if (isValid(result)) {
  1946. return { success: true, data: result.value };
  1947. }
  1948. else {
  1949. if (!ctx.common.issues.length) {
  1950. throw new Error("Validation failed but no issues detected.");
  1951. }
  1952. return {
  1953. success: false,
  1954. get error() {
  1955. if (this._error)
  1956. return this._error;
  1957. const error = new ZodError(ctx.common.issues);
  1958. this._error = error;
  1959. return this._error;
  1960. },
  1961. };
  1962. }
  1963. };
  1964. function processCreateParams(params) {
  1965. if (!params)
  1966. return {};
  1967. const { errorMap, invalid_type_error, required_error, description } = params;
  1968. if (errorMap && (invalid_type_error || required_error)) {
  1969. throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  1970. }
  1971. if (errorMap)
  1972. return { errorMap: errorMap, description };
  1973. const customMap = (iss, ctx) => {
  1974. const { message } = params;
  1975. if (iss.code === "invalid_enum_value") {
  1976. return { message: message ?? ctx.defaultError };
  1977. }
  1978. if (typeof ctx.data === "undefined") {
  1979. return { message: message ?? required_error ?? ctx.defaultError };
  1980. }
  1981. if (iss.code !== "invalid_type")
  1982. return { message: ctx.defaultError };
  1983. return { message: message ?? invalid_type_error ?? ctx.defaultError };
  1984. };
  1985. return { errorMap: customMap, description };
  1986. }
  1987. class ZodType {
  1988. get description() {
  1989. return this._def.description;
  1990. }
  1991. _getType(input) {
  1992. return getParsedType(input.data);
  1993. }
  1994. _getOrReturnCtx(input, ctx) {
  1995. return (ctx || {
  1996. common: input.parent.common,
  1997. data: input.data,
  1998. parsedType: getParsedType(input.data),
  1999. schemaErrorMap: this._def.errorMap,
  2000. path: input.path,
  2001. parent: input.parent,
  2002. });
  2003. }
  2004. _processInputParams(input) {
  2005. return {
  2006. status: new ParseStatus(),
  2007. ctx: {
  2008. common: input.parent.common,
  2009. data: input.data,
  2010. parsedType: getParsedType(input.data),
  2011. schemaErrorMap: this._def.errorMap,
  2012. path: input.path,
  2013. parent: input.parent,
  2014. },
  2015. };
  2016. }
  2017. _parseSync(input) {
  2018. const result = this._parse(input);
  2019. if (isAsync(result)) {
  2020. throw new Error("Synchronous parse encountered promise.");
  2021. }
  2022. return result;
  2023. }
  2024. _parseAsync(input) {
  2025. const result = this._parse(input);
  2026. return Promise.resolve(result);
  2027. }
  2028. parse(data, params) {
  2029. const result = this.safeParse(data, params);
  2030. if (result.success)
  2031. return result.data;
  2032. throw result.error;
  2033. }
  2034. safeParse(data, params) {
  2035. const ctx = {
  2036. common: {
  2037. issues: [],
  2038. async: params?.async ?? false,
  2039. contextualErrorMap: params?.errorMap,
  2040. },
  2041. path: params?.path || [],
  2042. schemaErrorMap: this._def.errorMap,
  2043. parent: null,
  2044. data,
  2045. parsedType: getParsedType(data),
  2046. };
  2047. const result = this._parseSync({ data, path: ctx.path, parent: ctx });
  2048. return handleResult(ctx, result);
  2049. }
  2050. "~validate"(data) {
  2051. const ctx = {
  2052. common: {
  2053. issues: [],
  2054. async: !!this["~standard"].async,
  2055. },
  2056. path: [],
  2057. schemaErrorMap: this._def.errorMap,
  2058. parent: null,
  2059. data,
  2060. parsedType: getParsedType(data),
  2061. };
  2062. if (!this["~standard"].async) {
  2063. try {
  2064. const result = this._parseSync({ data, path: [], parent: ctx });
  2065. return isValid(result)
  2066. ? {
  2067. value: result.value,
  2068. }
  2069. : {
  2070. issues: ctx.common.issues,
  2071. };
  2072. }
  2073. catch (err) {
  2074. if (err?.message?.toLowerCase()?.includes("encountered")) {
  2075. this["~standard"].async = true;
  2076. }
  2077. ctx.common = {
  2078. issues: [],
  2079. async: true,
  2080. };
  2081. }
  2082. }
  2083. return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)
  2084. ? {
  2085. value: result.value,
  2086. }
  2087. : {
  2088. issues: ctx.common.issues,
  2089. });
  2090. }
  2091. async parseAsync(data, params) {
  2092. const result = await this.safeParseAsync(data, params);
  2093. if (result.success)
  2094. return result.data;
  2095. throw result.error;
  2096. }
  2097. async safeParseAsync(data, params) {
  2098. const ctx = {
  2099. common: {
  2100. issues: [],
  2101. contextualErrorMap: params?.errorMap,
  2102. async: true,
  2103. },
  2104. path: params?.path || [],
  2105. schemaErrorMap: this._def.errorMap,
  2106. parent: null,
  2107. data,
  2108. parsedType: getParsedType(data),
  2109. };
  2110. const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
  2111. const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
  2112. return handleResult(ctx, result);
  2113. }
  2114. refine(check, message) {
  2115. const getIssueProperties = (val) => {
  2116. if (typeof message === "string" || typeof message === "undefined") {
  2117. return { message };
  2118. }
  2119. else if (typeof message === "function") {
  2120. return message(val);
  2121. }
  2122. else {
  2123. return message;
  2124. }
  2125. };
  2126. return this._refinement((val, ctx) => {
  2127. const result = check(val);
  2128. const setError = () => ctx.addIssue({
  2129. code: ZodIssueCode.custom,
  2130. ...getIssueProperties(val),
  2131. });
  2132. if (typeof Promise !== "undefined" && result instanceof Promise) {
  2133. return result.then((data) => {
  2134. if (!data) {
  2135. setError();
  2136. return false;
  2137. }
  2138. else {
  2139. return true;
  2140. }
  2141. });
  2142. }
  2143. if (!result) {
  2144. setError();
  2145. return false;
  2146. }
  2147. else {
  2148. return true;
  2149. }
  2150. });
  2151. }
  2152. refinement(check, refinementData) {
  2153. return this._refinement((val, ctx) => {
  2154. if (!check(val)) {
  2155. ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
  2156. return false;
  2157. }
  2158. else {
  2159. return true;
  2160. }
  2161. });
  2162. }
  2163. _refinement(refinement) {
  2164. return new ZodEffects({
  2165. schema: this,
  2166. typeName: ZodFirstPartyTypeKind.ZodEffects,
  2167. effect: { type: "refinement", refinement },
  2168. });
  2169. }
  2170. superRefine(refinement) {
  2171. return this._refinement(refinement);
  2172. }
  2173. constructor(def) {
  2174. /** Alias of safeParseAsync */
  2175. this.spa = this.safeParseAsync;
  2176. this._def = def;
  2177. this.parse = this.parse.bind(this);
  2178. this.safeParse = this.safeParse.bind(this);
  2179. this.parseAsync = this.parseAsync.bind(this);
  2180. this.safeParseAsync = this.safeParseAsync.bind(this);
  2181. this.spa = this.spa.bind(this);
  2182. this.refine = this.refine.bind(this);
  2183. this.refinement = this.refinement.bind(this);
  2184. this.superRefine = this.superRefine.bind(this);
  2185. this.optional = this.optional.bind(this);
  2186. this.nullable = this.nullable.bind(this);
  2187. this.nullish = this.nullish.bind(this);
  2188. this.array = this.array.bind(this);
  2189. this.promise = this.promise.bind(this);
  2190. this.or = this.or.bind(this);
  2191. this.and = this.and.bind(this);
  2192. this.transform = this.transform.bind(this);
  2193. this.brand = this.brand.bind(this);
  2194. this.default = this.default.bind(this);
  2195. this.catch = this.catch.bind(this);
  2196. this.describe = this.describe.bind(this);
  2197. this.pipe = this.pipe.bind(this);
  2198. this.readonly = this.readonly.bind(this);
  2199. this.isNullable = this.isNullable.bind(this);
  2200. this.isOptional = this.isOptional.bind(this);
  2201. this["~standard"] = {
  2202. version: 1,
  2203. vendor: "zod",
  2204. validate: (data) => this["~validate"](data),
  2205. };
  2206. }
  2207. optional() {
  2208. return ZodOptional.create(this, this._def);
  2209. }
  2210. nullable() {
  2211. return ZodNullable.create(this, this._def);
  2212. }
  2213. nullish() {
  2214. return this.nullable().optional();
  2215. }
  2216. array() {
  2217. return ZodArray.create(this);
  2218. }
  2219. promise() {
  2220. return ZodPromise.create(this, this._def);
  2221. }
  2222. or(option) {
  2223. return ZodUnion.create([this, option], this._def);
  2224. }
  2225. and(incoming) {
  2226. return ZodIntersection.create(this, incoming, this._def);
  2227. }
  2228. transform(transform) {
  2229. return new ZodEffects({
  2230. ...processCreateParams(this._def),
  2231. schema: this,
  2232. typeName: ZodFirstPartyTypeKind.ZodEffects,
  2233. effect: { type: "transform", transform },
  2234. });
  2235. }
  2236. default(def) {
  2237. const defaultValueFunc = typeof def === "function" ? def : () => def;
  2238. return new ZodDefault({
  2239. ...processCreateParams(this._def),
  2240. innerType: this,
  2241. defaultValue: defaultValueFunc,
  2242. typeName: ZodFirstPartyTypeKind.ZodDefault,
  2243. });
  2244. }
  2245. brand() {
  2246. return new ZodBranded({
  2247. typeName: ZodFirstPartyTypeKind.ZodBranded,
  2248. type: this,
  2249. ...processCreateParams(this._def),
  2250. });
  2251. }
  2252. catch(def) {
  2253. const catchValueFunc = typeof def === "function" ? def : () => def;
  2254. return new ZodCatch({
  2255. ...processCreateParams(this._def),
  2256. innerType: this,
  2257. catchValue: catchValueFunc,
  2258. typeName: ZodFirstPartyTypeKind.ZodCatch,
  2259. });
  2260. }
  2261. describe(description) {
  2262. const This = this.constructor;
  2263. return new This({
  2264. ...this._def,
  2265. description,
  2266. });
  2267. }
  2268. pipe(target) {
  2269. return ZodPipeline.create(this, target);
  2270. }
  2271. readonly() {
  2272. return ZodReadonly.create(this);
  2273. }
  2274. isOptional() {
  2275. return this.safeParse(undefined).success;
  2276. }
  2277. isNullable() {
  2278. return this.safeParse(null).success;
  2279. }
  2280. }
  2281. const cuidRegex = /^c[^\s-]{8,}$/i;
  2282. const cuid2Regex = /^[0-9a-z]+$/;
  2283. const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
  2284. // const uuidRegex =
  2285. // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
  2286. const 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;
  2287. const nanoidRegex = /^[a-z0-9_-]{21}$/i;
  2288. const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
  2289. const 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)?)??$/;
  2290. // from https://stackoverflow.com/a/46181/1550155
  2291. // old version: too slow, didn't support unicode
  2292. // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
  2293. //old email regex
  2294. // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
  2295. // eslint-disable-next-line
  2296. // const emailRegex =
  2297. // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
  2298. // const emailRegex =
  2299. // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
  2300. // const emailRegex =
  2301. // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
  2302. const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
  2303. // const emailRegex =
  2304. // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
  2305. // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
  2306. const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
  2307. let emojiRegex;
  2308. // faster, simpler, safer
  2309. const 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])$/;
  2310. const 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])$/;
  2311. // const ipv6Regex =
  2312. // /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
  2313. const 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]))$/;
  2314. const 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])$/;
  2315. // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
  2316. const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
  2317. // https://base64.guru/standards/base64url
  2318. const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
  2319. // simple
  2320. // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
  2321. // no leap year validation
  2322. // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
  2323. // with leap year validation
  2324. const 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])))`;
  2325. const dateRegex = new RegExp(`^${dateRegexSource}$`);
  2326. function timeRegexSource(args) {
  2327. let secondsRegexSource = `[0-5]\\d`;
  2328. if (args.precision) {
  2329. secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  2330. }
  2331. else if (args.precision == null) {
  2332. secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  2333. }
  2334. const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero
  2335. return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
  2336. }
  2337. function timeRegex(args) {
  2338. return new RegExp(`^${timeRegexSource(args)}$`);
  2339. }
  2340. // Adapted from https://stackoverflow.com/a/3143231
  2341. function datetimeRegex(args) {
  2342. let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  2343. const opts = [];
  2344. opts.push(args.local ? `Z?` : `Z`);
  2345. if (args.offset)
  2346. opts.push(`([+-]\\d{2}:?\\d{2})`);
  2347. regex = `${regex}(${opts.join("|")})`;
  2348. return new RegExp(`^${regex}$`);
  2349. }
  2350. function isValidIP(ip, version) {
  2351. if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
  2352. return true;
  2353. }
  2354. if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
  2355. return true;
  2356. }
  2357. return false;
  2358. }
  2359. function isValidJWT(jwt, alg) {
  2360. if (!jwtRegex.test(jwt))
  2361. return false;
  2362. try {
  2363. const [header] = jwt.split(".");
  2364. if (!header)
  2365. return false;
  2366. // Convert base64url to base64
  2367. const base64 = header
  2368. .replace(/-/g, "+")
  2369. .replace(/_/g, "/")
  2370. .padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
  2371. const decoded = JSON.parse(atob(base64));
  2372. if (typeof decoded !== "object" || decoded === null)
  2373. return false;
  2374. if ("typ" in decoded && decoded?.typ !== "JWT")
  2375. return false;
  2376. if (!decoded.alg)
  2377. return false;
  2378. if (alg && decoded.alg !== alg)
  2379. return false;
  2380. return true;
  2381. }
  2382. catch {
  2383. return false;
  2384. }
  2385. }
  2386. function isValidCidr(ip, version) {
  2387. if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
  2388. return true;
  2389. }
  2390. if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
  2391. return true;
  2392. }
  2393. return false;
  2394. }
  2395. class ZodString extends ZodType {
  2396. _parse(input) {
  2397. if (this._def.coerce) {
  2398. input.data = String(input.data);
  2399. }
  2400. const parsedType = this._getType(input);
  2401. if (parsedType !== ZodParsedType.string) {
  2402. const ctx = this._getOrReturnCtx(input);
  2403. addIssueToContext(ctx, {
  2404. code: ZodIssueCode.invalid_type,
  2405. expected: ZodParsedType.string,
  2406. received: ctx.parsedType,
  2407. });
  2408. return INVALID;
  2409. }
  2410. const status = new ParseStatus();
  2411. let ctx = undefined;
  2412. for (const check of this._def.checks) {
  2413. if (check.kind === "min") {
  2414. if (input.data.length < check.value) {
  2415. ctx = this._getOrReturnCtx(input, ctx);
  2416. addIssueToContext(ctx, {
  2417. code: ZodIssueCode.too_small,
  2418. minimum: check.value,
  2419. type: "string",
  2420. inclusive: true,
  2421. exact: false,
  2422. message: check.message,
  2423. });
  2424. status.dirty();
  2425. }
  2426. }
  2427. else if (check.kind === "max") {
  2428. if (input.data.length > check.value) {
  2429. ctx = this._getOrReturnCtx(input, ctx);
  2430. addIssueToContext(ctx, {
  2431. code: ZodIssueCode.too_big,
  2432. maximum: check.value,
  2433. type: "string",
  2434. inclusive: true,
  2435. exact: false,
  2436. message: check.message,
  2437. });
  2438. status.dirty();
  2439. }
  2440. }
  2441. else if (check.kind === "length") {
  2442. const tooBig = input.data.length > check.value;
  2443. const tooSmall = input.data.length < check.value;
  2444. if (tooBig || tooSmall) {
  2445. ctx = this._getOrReturnCtx(input, ctx);
  2446. if (tooBig) {
  2447. addIssueToContext(ctx, {
  2448. code: ZodIssueCode.too_big,
  2449. maximum: check.value,
  2450. type: "string",
  2451. inclusive: true,
  2452. exact: true,
  2453. message: check.message,
  2454. });
  2455. }
  2456. else if (tooSmall) {
  2457. addIssueToContext(ctx, {
  2458. code: ZodIssueCode.too_small,
  2459. minimum: check.value,
  2460. type: "string",
  2461. inclusive: true,
  2462. exact: true,
  2463. message: check.message,
  2464. });
  2465. }
  2466. status.dirty();
  2467. }
  2468. }
  2469. else if (check.kind === "email") {
  2470. if (!emailRegex.test(input.data)) {
  2471. ctx = this._getOrReturnCtx(input, ctx);
  2472. addIssueToContext(ctx, {
  2473. validation: "email",
  2474. code: ZodIssueCode.invalid_string,
  2475. message: check.message,
  2476. });
  2477. status.dirty();
  2478. }
  2479. }
  2480. else if (check.kind === "emoji") {
  2481. if (!emojiRegex) {
  2482. emojiRegex = new RegExp(_emojiRegex, "u");
  2483. }
  2484. if (!emojiRegex.test(input.data)) {
  2485. ctx = this._getOrReturnCtx(input, ctx);
  2486. addIssueToContext(ctx, {
  2487. validation: "emoji",
  2488. code: ZodIssueCode.invalid_string,
  2489. message: check.message,
  2490. });
  2491. status.dirty();
  2492. }
  2493. }
  2494. else if (check.kind === "uuid") {
  2495. if (!uuidRegex.test(input.data)) {
  2496. ctx = this._getOrReturnCtx(input, ctx);
  2497. addIssueToContext(ctx, {
  2498. validation: "uuid",
  2499. code: ZodIssueCode.invalid_string,
  2500. message: check.message,
  2501. });
  2502. status.dirty();
  2503. }
  2504. }
  2505. else if (check.kind === "nanoid") {
  2506. if (!nanoidRegex.test(input.data)) {
  2507. ctx = this._getOrReturnCtx(input, ctx);
  2508. addIssueToContext(ctx, {
  2509. validation: "nanoid",
  2510. code: ZodIssueCode.invalid_string,
  2511. message: check.message,
  2512. });
  2513. status.dirty();
  2514. }
  2515. }
  2516. else if (check.kind === "cuid") {
  2517. if (!cuidRegex.test(input.data)) {
  2518. ctx = this._getOrReturnCtx(input, ctx);
  2519. addIssueToContext(ctx, {
  2520. validation: "cuid",
  2521. code: ZodIssueCode.invalid_string,
  2522. message: check.message,
  2523. });
  2524. status.dirty();
  2525. }
  2526. }
  2527. else if (check.kind === "cuid2") {
  2528. if (!cuid2Regex.test(input.data)) {
  2529. ctx = this._getOrReturnCtx(input, ctx);
  2530. addIssueToContext(ctx, {
  2531. validation: "cuid2",
  2532. code: ZodIssueCode.invalid_string,
  2533. message: check.message,
  2534. });
  2535. status.dirty();
  2536. }
  2537. }
  2538. else if (check.kind === "ulid") {
  2539. if (!ulidRegex.test(input.data)) {
  2540. ctx = this._getOrReturnCtx(input, ctx);
  2541. addIssueToContext(ctx, {
  2542. validation: "ulid",
  2543. code: ZodIssueCode.invalid_string,
  2544. message: check.message,
  2545. });
  2546. status.dirty();
  2547. }
  2548. }
  2549. else if (check.kind === "url") {
  2550. try {
  2551. new URL(input.data);
  2552. }
  2553. catch {
  2554. ctx = this._getOrReturnCtx(input, ctx);
  2555. addIssueToContext(ctx, {
  2556. validation: "url",
  2557. code: ZodIssueCode.invalid_string,
  2558. message: check.message,
  2559. });
  2560. status.dirty();
  2561. }
  2562. }
  2563. else if (check.kind === "regex") {
  2564. check.regex.lastIndex = 0;
  2565. const testResult = check.regex.test(input.data);
  2566. if (!testResult) {
  2567. ctx = this._getOrReturnCtx(input, ctx);
  2568. addIssueToContext(ctx, {
  2569. validation: "regex",
  2570. code: ZodIssueCode.invalid_string,
  2571. message: check.message,
  2572. });
  2573. status.dirty();
  2574. }
  2575. }
  2576. else if (check.kind === "trim") {
  2577. input.data = input.data.trim();
  2578. }
  2579. else if (check.kind === "includes") {
  2580. if (!input.data.includes(check.value, check.position)) {
  2581. ctx = this._getOrReturnCtx(input, ctx);
  2582. addIssueToContext(ctx, {
  2583. code: ZodIssueCode.invalid_string,
  2584. validation: { includes: check.value, position: check.position },
  2585. message: check.message,
  2586. });
  2587. status.dirty();
  2588. }
  2589. }
  2590. else if (check.kind === "toLowerCase") {
  2591. input.data = input.data.toLowerCase();
  2592. }
  2593. else if (check.kind === "toUpperCase") {
  2594. input.data = input.data.toUpperCase();
  2595. }
  2596. else if (check.kind === "startsWith") {
  2597. if (!input.data.startsWith(check.value)) {
  2598. ctx = this._getOrReturnCtx(input, ctx);
  2599. addIssueToContext(ctx, {
  2600. code: ZodIssueCode.invalid_string,
  2601. validation: { startsWith: check.value },
  2602. message: check.message,
  2603. });
  2604. status.dirty();
  2605. }
  2606. }
  2607. else if (check.kind === "endsWith") {
  2608. if (!input.data.endsWith(check.value)) {
  2609. ctx = this._getOrReturnCtx(input, ctx);
  2610. addIssueToContext(ctx, {
  2611. code: ZodIssueCode.invalid_string,
  2612. validation: { endsWith: check.value },
  2613. message: check.message,
  2614. });
  2615. status.dirty();
  2616. }
  2617. }
  2618. else if (check.kind === "datetime") {
  2619. const regex = datetimeRegex(check);
  2620. if (!regex.test(input.data)) {
  2621. ctx = this._getOrReturnCtx(input, ctx);
  2622. addIssueToContext(ctx, {
  2623. code: ZodIssueCode.invalid_string,
  2624. validation: "datetime",
  2625. message: check.message,
  2626. });
  2627. status.dirty();
  2628. }
  2629. }
  2630. else if (check.kind === "date") {
  2631. const regex = dateRegex;
  2632. if (!regex.test(input.data)) {
  2633. ctx = this._getOrReturnCtx(input, ctx);
  2634. addIssueToContext(ctx, {
  2635. code: ZodIssueCode.invalid_string,
  2636. validation: "date",
  2637. message: check.message,
  2638. });
  2639. status.dirty();
  2640. }
  2641. }
  2642. else if (check.kind === "time") {
  2643. const regex = timeRegex(check);
  2644. if (!regex.test(input.data)) {
  2645. ctx = this._getOrReturnCtx(input, ctx);
  2646. addIssueToContext(ctx, {
  2647. code: ZodIssueCode.invalid_string,
  2648. validation: "time",
  2649. message: check.message,
  2650. });
  2651. status.dirty();
  2652. }
  2653. }
  2654. else if (check.kind === "duration") {
  2655. if (!durationRegex.test(input.data)) {
  2656. ctx = this._getOrReturnCtx(input, ctx);
  2657. addIssueToContext(ctx, {
  2658. validation: "duration",
  2659. code: ZodIssueCode.invalid_string,
  2660. message: check.message,
  2661. });
  2662. status.dirty();
  2663. }
  2664. }
  2665. else if (check.kind === "ip") {
  2666. if (!isValidIP(input.data, check.version)) {
  2667. ctx = this._getOrReturnCtx(input, ctx);
  2668. addIssueToContext(ctx, {
  2669. validation: "ip",
  2670. code: ZodIssueCode.invalid_string,
  2671. message: check.message,
  2672. });
  2673. status.dirty();
  2674. }
  2675. }
  2676. else if (check.kind === "jwt") {
  2677. if (!isValidJWT(input.data, check.alg)) {
  2678. ctx = this._getOrReturnCtx(input, ctx);
  2679. addIssueToContext(ctx, {
  2680. validation: "jwt",
  2681. code: ZodIssueCode.invalid_string,
  2682. message: check.message,
  2683. });
  2684. status.dirty();
  2685. }
  2686. }
  2687. else if (check.kind === "cidr") {
  2688. if (!isValidCidr(input.data, check.version)) {
  2689. ctx = this._getOrReturnCtx(input, ctx);
  2690. addIssueToContext(ctx, {
  2691. validation: "cidr",
  2692. code: ZodIssueCode.invalid_string,
  2693. message: check.message,
  2694. });
  2695. status.dirty();
  2696. }
  2697. }
  2698. else if (check.kind === "base64") {
  2699. if (!base64Regex.test(input.data)) {
  2700. ctx = this._getOrReturnCtx(input, ctx);
  2701. addIssueToContext(ctx, {
  2702. validation: "base64",
  2703. code: ZodIssueCode.invalid_string,
  2704. message: check.message,
  2705. });
  2706. status.dirty();
  2707. }
  2708. }
  2709. else if (check.kind === "base64url") {
  2710. if (!base64urlRegex.test(input.data)) {
  2711. ctx = this._getOrReturnCtx(input, ctx);
  2712. addIssueToContext(ctx, {
  2713. validation: "base64url",
  2714. code: ZodIssueCode.invalid_string,
  2715. message: check.message,
  2716. });
  2717. status.dirty();
  2718. }
  2719. }
  2720. else {
  2721. util.assertNever(check);
  2722. }
  2723. }
  2724. return { status: status.value, value: input.data };
  2725. }
  2726. _regex(regex, validation, message) {
  2727. return this.refinement((data) => regex.test(data), {
  2728. validation,
  2729. code: ZodIssueCode.invalid_string,
  2730. ...errorUtil.errToObj(message),
  2731. });
  2732. }
  2733. _addCheck(check) {
  2734. return new ZodString({
  2735. ...this._def,
  2736. checks: [...this._def.checks, check],
  2737. });
  2738. }
  2739. email(message) {
  2740. return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  2741. }
  2742. url(message) {
  2743. return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  2744. }
  2745. emoji(message) {
  2746. return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  2747. }
  2748. uuid(message) {
  2749. return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  2750. }
  2751. nanoid(message) {
  2752. return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  2753. }
  2754. cuid(message) {
  2755. return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  2756. }
  2757. cuid2(message) {
  2758. return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  2759. }
  2760. ulid(message) {
  2761. return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  2762. }
  2763. base64(message) {
  2764. return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  2765. }
  2766. base64url(message) {
  2767. // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
  2768. return this._addCheck({
  2769. kind: "base64url",
  2770. ...errorUtil.errToObj(message),
  2771. });
  2772. }
  2773. jwt(options) {
  2774. return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
  2775. }
  2776. ip(options) {
  2777. return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  2778. }
  2779. cidr(options) {
  2780. return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
  2781. }
  2782. datetime(options) {
  2783. if (typeof options === "string") {
  2784. return this._addCheck({
  2785. kind: "datetime",
  2786. precision: null,
  2787. offset: false,
  2788. local: false,
  2789. message: options,
  2790. });
  2791. }
  2792. return this._addCheck({
  2793. kind: "datetime",
  2794. precision: typeof options?.precision === "undefined" ? null : options?.precision,
  2795. offset: options?.offset ?? false,
  2796. local: options?.local ?? false,
  2797. ...errorUtil.errToObj(options?.message),
  2798. });
  2799. }
  2800. date(message) {
  2801. return this._addCheck({ kind: "date", message });
  2802. }
  2803. time(options) {
  2804. if (typeof options === "string") {
  2805. return this._addCheck({
  2806. kind: "time",
  2807. precision: null,
  2808. message: options,
  2809. });
  2810. }
  2811. return this._addCheck({
  2812. kind: "time",
  2813. precision: typeof options?.precision === "undefined" ? null : options?.precision,
  2814. ...errorUtil.errToObj(options?.message),
  2815. });
  2816. }
  2817. duration(message) {
  2818. return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  2819. }
  2820. regex(regex, message) {
  2821. return this._addCheck({
  2822. kind: "regex",
  2823. regex: regex,
  2824. ...errorUtil.errToObj(message),
  2825. });
  2826. }
  2827. includes(value, options) {
  2828. return this._addCheck({
  2829. kind: "includes",
  2830. value: value,
  2831. position: options?.position,
  2832. ...errorUtil.errToObj(options?.message),
  2833. });
  2834. }
  2835. startsWith(value, message) {
  2836. return this._addCheck({
  2837. kind: "startsWith",
  2838. value: value,
  2839. ...errorUtil.errToObj(message),
  2840. });
  2841. }
  2842. endsWith(value, message) {
  2843. return this._addCheck({
  2844. kind: "endsWith",
  2845. value: value,
  2846. ...errorUtil.errToObj(message),
  2847. });
  2848. }
  2849. min(minLength, message) {
  2850. return this._addCheck({
  2851. kind: "min",
  2852. value: minLength,
  2853. ...errorUtil.errToObj(message),
  2854. });
  2855. }
  2856. max(maxLength, message) {
  2857. return this._addCheck({
  2858. kind: "max",
  2859. value: maxLength,
  2860. ...errorUtil.errToObj(message),
  2861. });
  2862. }
  2863. length(len, message) {
  2864. return this._addCheck({
  2865. kind: "length",
  2866. value: len,
  2867. ...errorUtil.errToObj(message),
  2868. });
  2869. }
  2870. /**
  2871. * Equivalent to `.min(1)`
  2872. */
  2873. nonempty(message) {
  2874. return this.min(1, errorUtil.errToObj(message));
  2875. }
  2876. trim() {
  2877. return new ZodString({
  2878. ...this._def,
  2879. checks: [...this._def.checks, { kind: "trim" }],
  2880. });
  2881. }
  2882. toLowerCase() {
  2883. return new ZodString({
  2884. ...this._def,
  2885. checks: [...this._def.checks, { kind: "toLowerCase" }],
  2886. });
  2887. }
  2888. toUpperCase() {
  2889. return new ZodString({
  2890. ...this._def,
  2891. checks: [...this._def.checks, { kind: "toUpperCase" }],
  2892. });
  2893. }
  2894. get isDatetime() {
  2895. return !!this._def.checks.find((ch) => ch.kind === "datetime");
  2896. }
  2897. get isDate() {
  2898. return !!this._def.checks.find((ch) => ch.kind === "date");
  2899. }
  2900. get isTime() {
  2901. return !!this._def.checks.find((ch) => ch.kind === "time");
  2902. }
  2903. get isDuration() {
  2904. return !!this._def.checks.find((ch) => ch.kind === "duration");
  2905. }
  2906. get isEmail() {
  2907. return !!this._def.checks.find((ch) => ch.kind === "email");
  2908. }
  2909. get isURL() {
  2910. return !!this._def.checks.find((ch) => ch.kind === "url");
  2911. }
  2912. get isEmoji() {
  2913. return !!this._def.checks.find((ch) => ch.kind === "emoji");
  2914. }
  2915. get isUUID() {
  2916. return !!this._def.checks.find((ch) => ch.kind === "uuid");
  2917. }
  2918. get isNANOID() {
  2919. return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  2920. }
  2921. get isCUID() {
  2922. return !!this._def.checks.find((ch) => ch.kind === "cuid");
  2923. }
  2924. get isCUID2() {
  2925. return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  2926. }
  2927. get isULID() {
  2928. return !!this._def.checks.find((ch) => ch.kind === "ulid");
  2929. }
  2930. get isIP() {
  2931. return !!this._def.checks.find((ch) => ch.kind === "ip");
  2932. }
  2933. get isCIDR() {
  2934. return !!this._def.checks.find((ch) => ch.kind === "cidr");
  2935. }
  2936. get isBase64() {
  2937. return !!this._def.checks.find((ch) => ch.kind === "base64");
  2938. }
  2939. get isBase64url() {
  2940. // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
  2941. return !!this._def.checks.find((ch) => ch.kind === "base64url");
  2942. }
  2943. get minLength() {
  2944. let min = null;
  2945. for (const ch of this._def.checks) {
  2946. if (ch.kind === "min") {
  2947. if (min === null || ch.value > min)
  2948. min = ch.value;
  2949. }
  2950. }
  2951. return min;
  2952. }
  2953. get maxLength() {
  2954. let max = null;
  2955. for (const ch of this._def.checks) {
  2956. if (ch.kind === "max") {
  2957. if (max === null || ch.value < max)
  2958. max = ch.value;
  2959. }
  2960. }
  2961. return max;
  2962. }
  2963. }
  2964. ZodString.create = (params) => {
  2965. return new ZodString({
  2966. checks: [],
  2967. typeName: ZodFirstPartyTypeKind.ZodString,
  2968. coerce: params?.coerce ?? false,
  2969. ...processCreateParams(params),
  2970. });
  2971. };
  2972. // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
  2973. function floatSafeRemainder(val, step) {
  2974. const valDecCount = (val.toString().split(".")[1] || "").length;
  2975. const stepDecCount = (step.toString().split(".")[1] || "").length;
  2976. const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  2977. const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  2978. const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  2979. return (valInt % stepInt) / 10 ** decCount;
  2980. }
  2981. class ZodNumber extends ZodType {
  2982. constructor() {
  2983. super(...arguments);
  2984. this.min = this.gte;
  2985. this.max = this.lte;
  2986. this.step = this.multipleOf;
  2987. }
  2988. _parse(input) {
  2989. if (this._def.coerce) {
  2990. input.data = Number(input.data);
  2991. }
  2992. const parsedType = this._getType(input);
  2993. if (parsedType !== ZodParsedType.number) {
  2994. const ctx = this._getOrReturnCtx(input);
  2995. addIssueToContext(ctx, {
  2996. code: ZodIssueCode.invalid_type,
  2997. expected: ZodParsedType.number,
  2998. received: ctx.parsedType,
  2999. });
  3000. return INVALID;
  3001. }
  3002. let ctx = undefined;
  3003. const status = new ParseStatus();
  3004. for (const check of this._def.checks) {
  3005. if (check.kind === "int") {
  3006. if (!util.isInteger(input.data)) {
  3007. ctx = this._getOrReturnCtx(input, ctx);
  3008. addIssueToContext(ctx, {
  3009. code: ZodIssueCode.invalid_type,
  3010. expected: "integer",
  3011. received: "float",
  3012. message: check.message,
  3013. });
  3014. status.dirty();
  3015. }
  3016. }
  3017. else if (check.kind === "min") {
  3018. const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
  3019. if (tooSmall) {
  3020. ctx = this._getOrReturnCtx(input, ctx);
  3021. addIssueToContext(ctx, {
  3022. code: ZodIssueCode.too_small,
  3023. minimum: check.value,
  3024. type: "number",
  3025. inclusive: check.inclusive,
  3026. exact: false,
  3027. message: check.message,
  3028. });
  3029. status.dirty();
  3030. }
  3031. }
  3032. else if (check.kind === "max") {
  3033. const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
  3034. if (tooBig) {
  3035. ctx = this._getOrReturnCtx(input, ctx);
  3036. addIssueToContext(ctx, {
  3037. code: ZodIssueCode.too_big,
  3038. maximum: check.value,
  3039. type: "number",
  3040. inclusive: check.inclusive,
  3041. exact: false,
  3042. message: check.message,
  3043. });
  3044. status.dirty();
  3045. }
  3046. }
  3047. else if (check.kind === "multipleOf") {
  3048. if (floatSafeRemainder(input.data, check.value) !== 0) {
  3049. ctx = this._getOrReturnCtx(input, ctx);
  3050. addIssueToContext(ctx, {
  3051. code: ZodIssueCode.not_multiple_of,
  3052. multipleOf: check.value,
  3053. message: check.message,
  3054. });
  3055. status.dirty();
  3056. }
  3057. }
  3058. else if (check.kind === "finite") {
  3059. if (!Number.isFinite(input.data)) {
  3060. ctx = this._getOrReturnCtx(input, ctx);
  3061. addIssueToContext(ctx, {
  3062. code: ZodIssueCode.not_finite,
  3063. message: check.message,
  3064. });
  3065. status.dirty();
  3066. }
  3067. }
  3068. else {
  3069. util.assertNever(check);
  3070. }
  3071. }
  3072. return { status: status.value, value: input.data };
  3073. }
  3074. gte(value, message) {
  3075. return this.setLimit("min", value, true, errorUtil.toString(message));
  3076. }
  3077. gt(value, message) {
  3078. return this.setLimit("min", value, false, errorUtil.toString(message));
  3079. }
  3080. lte(value, message) {
  3081. return this.setLimit("max", value, true, errorUtil.toString(message));
  3082. }
  3083. lt(value, message) {
  3084. return this.setLimit("max", value, false, errorUtil.toString(message));
  3085. }
  3086. setLimit(kind, value, inclusive, message) {
  3087. return new ZodNumber({
  3088. ...this._def,
  3089. checks: [
  3090. ...this._def.checks,
  3091. {
  3092. kind,
  3093. value,
  3094. inclusive,
  3095. message: errorUtil.toString(message),
  3096. },
  3097. ],
  3098. });
  3099. }
  3100. _addCheck(check) {
  3101. return new ZodNumber({
  3102. ...this._def,
  3103. checks: [...this._def.checks, check],
  3104. });
  3105. }
  3106. int(message) {
  3107. return this._addCheck({
  3108. kind: "int",
  3109. message: errorUtil.toString(message),
  3110. });
  3111. }
  3112. positive(message) {
  3113. return this._addCheck({
  3114. kind: "min",
  3115. value: 0,
  3116. inclusive: false,
  3117. message: errorUtil.toString(message),
  3118. });
  3119. }
  3120. negative(message) {
  3121. return this._addCheck({
  3122. kind: "max",
  3123. value: 0,
  3124. inclusive: false,
  3125. message: errorUtil.toString(message),
  3126. });
  3127. }
  3128. nonpositive(message) {
  3129. return this._addCheck({
  3130. kind: "max",
  3131. value: 0,
  3132. inclusive: true,
  3133. message: errorUtil.toString(message),
  3134. });
  3135. }
  3136. nonnegative(message) {
  3137. return this._addCheck({
  3138. kind: "min",
  3139. value: 0,
  3140. inclusive: true,
  3141. message: errorUtil.toString(message),
  3142. });
  3143. }
  3144. multipleOf(value, message) {
  3145. return this._addCheck({
  3146. kind: "multipleOf",
  3147. value: value,
  3148. message: errorUtil.toString(message),
  3149. });
  3150. }
  3151. finite(message) {
  3152. return this._addCheck({
  3153. kind: "finite",
  3154. message: errorUtil.toString(message),
  3155. });
  3156. }
  3157. safe(message) {
  3158. return this._addCheck({
  3159. kind: "min",
  3160. inclusive: true,
  3161. value: Number.MIN_SAFE_INTEGER,
  3162. message: errorUtil.toString(message),
  3163. })._addCheck({
  3164. kind: "max",
  3165. inclusive: true,
  3166. value: Number.MAX_SAFE_INTEGER,
  3167. message: errorUtil.toString(message),
  3168. });
  3169. }
  3170. get minValue() {
  3171. let min = null;
  3172. for (const ch of this._def.checks) {
  3173. if (ch.kind === "min") {
  3174. if (min === null || ch.value > min)
  3175. min = ch.value;
  3176. }
  3177. }
  3178. return min;
  3179. }
  3180. get maxValue() {
  3181. let max = null;
  3182. for (const ch of this._def.checks) {
  3183. if (ch.kind === "max") {
  3184. if (max === null || ch.value < max)
  3185. max = ch.value;
  3186. }
  3187. }
  3188. return max;
  3189. }
  3190. get isInt() {
  3191. return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value)));
  3192. }
  3193. get isFinite() {
  3194. let max = null;
  3195. let min = null;
  3196. for (const ch of this._def.checks) {
  3197. if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
  3198. return true;
  3199. }
  3200. else if (ch.kind === "min") {
  3201. if (min === null || ch.value > min)
  3202. min = ch.value;
  3203. }
  3204. else if (ch.kind === "max") {
  3205. if (max === null || ch.value < max)
  3206. max = ch.value;
  3207. }
  3208. }
  3209. return Number.isFinite(min) && Number.isFinite(max);
  3210. }
  3211. }
  3212. ZodNumber.create = (params) => {
  3213. return new ZodNumber({
  3214. checks: [],
  3215. typeName: ZodFirstPartyTypeKind.ZodNumber,
  3216. coerce: params?.coerce || false,
  3217. ...processCreateParams(params),
  3218. });
  3219. };
  3220. class ZodBigInt extends ZodType {
  3221. constructor() {
  3222. super(...arguments);
  3223. this.min = this.gte;
  3224. this.max = this.lte;
  3225. }
  3226. _parse(input) {
  3227. if (this._def.coerce) {
  3228. try {
  3229. input.data = BigInt(input.data);
  3230. }
  3231. catch {
  3232. return this._getInvalidInput(input);
  3233. }
  3234. }
  3235. const parsedType = this._getType(input);
  3236. if (parsedType !== ZodParsedType.bigint) {
  3237. return this._getInvalidInput(input);
  3238. }
  3239. let ctx = undefined;
  3240. const status = new ParseStatus();
  3241. for (const check of this._def.checks) {
  3242. if (check.kind === "min") {
  3243. const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
  3244. if (tooSmall) {
  3245. ctx = this._getOrReturnCtx(input, ctx);
  3246. addIssueToContext(ctx, {
  3247. code: ZodIssueCode.too_small,
  3248. type: "bigint",
  3249. minimum: check.value,
  3250. inclusive: check.inclusive,
  3251. message: check.message,
  3252. });
  3253. status.dirty();
  3254. }
  3255. }
  3256. else if (check.kind === "max") {
  3257. const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
  3258. if (tooBig) {
  3259. ctx = this._getOrReturnCtx(input, ctx);
  3260. addIssueToContext(ctx, {
  3261. code: ZodIssueCode.too_big,
  3262. type: "bigint",
  3263. maximum: check.value,
  3264. inclusive: check.inclusive,
  3265. message: check.message,
  3266. });
  3267. status.dirty();
  3268. }
  3269. }
  3270. else if (check.kind === "multipleOf") {
  3271. if (input.data % check.value !== BigInt(0)) {
  3272. ctx = this._getOrReturnCtx(input, ctx);
  3273. addIssueToContext(ctx, {
  3274. code: ZodIssueCode.not_multiple_of,
  3275. multipleOf: check.value,
  3276. message: check.message,
  3277. });
  3278. status.dirty();
  3279. }
  3280. }
  3281. else {
  3282. util.assertNever(check);
  3283. }
  3284. }
  3285. return { status: status.value, value: input.data };
  3286. }
  3287. _getInvalidInput(input) {
  3288. const ctx = this._getOrReturnCtx(input);
  3289. addIssueToContext(ctx, {
  3290. code: ZodIssueCode.invalid_type,
  3291. expected: ZodParsedType.bigint,
  3292. received: ctx.parsedType,
  3293. });
  3294. return INVALID;
  3295. }
  3296. gte(value, message) {
  3297. return this.setLimit("min", value, true, errorUtil.toString(message));
  3298. }
  3299. gt(value, message) {
  3300. return this.setLimit("min", value, false, errorUtil.toString(message));
  3301. }
  3302. lte(value, message) {
  3303. return this.setLimit("max", value, true, errorUtil.toString(message));
  3304. }
  3305. lt(value, message) {
  3306. return this.setLimit("max", value, false, errorUtil.toString(message));
  3307. }
  3308. setLimit(kind, value, inclusive, message) {
  3309. return new ZodBigInt({
  3310. ...this._def,
  3311. checks: [
  3312. ...this._def.checks,
  3313. {
  3314. kind,
  3315. value,
  3316. inclusive,
  3317. message: errorUtil.toString(message),
  3318. },
  3319. ],
  3320. });
  3321. }
  3322. _addCheck(check) {
  3323. return new ZodBigInt({
  3324. ...this._def,
  3325. checks: [...this._def.checks, check],
  3326. });
  3327. }
  3328. positive(message) {
  3329. return this._addCheck({
  3330. kind: "min",
  3331. value: BigInt(0),
  3332. inclusive: false,
  3333. message: errorUtil.toString(message),
  3334. });
  3335. }
  3336. negative(message) {
  3337. return this._addCheck({
  3338. kind: "max",
  3339. value: BigInt(0),
  3340. inclusive: false,
  3341. message: errorUtil.toString(message),
  3342. });
  3343. }
  3344. nonpositive(message) {
  3345. return this._addCheck({
  3346. kind: "max",
  3347. value: BigInt(0),
  3348. inclusive: true,
  3349. message: errorUtil.toString(message),
  3350. });
  3351. }
  3352. nonnegative(message) {
  3353. return this._addCheck({
  3354. kind: "min",
  3355. value: BigInt(0),
  3356. inclusive: true,
  3357. message: errorUtil.toString(message),
  3358. });
  3359. }
  3360. multipleOf(value, message) {
  3361. return this._addCheck({
  3362. kind: "multipleOf",
  3363. value,
  3364. message: errorUtil.toString(message),
  3365. });
  3366. }
  3367. get minValue() {
  3368. let min = null;
  3369. for (const ch of this._def.checks) {
  3370. if (ch.kind === "min") {
  3371. if (min === null || ch.value > min)
  3372. min = ch.value;
  3373. }
  3374. }
  3375. return min;
  3376. }
  3377. get maxValue() {
  3378. let max = null;
  3379. for (const ch of this._def.checks) {
  3380. if (ch.kind === "max") {
  3381. if (max === null || ch.value < max)
  3382. max = ch.value;
  3383. }
  3384. }
  3385. return max;
  3386. }
  3387. }
  3388. ZodBigInt.create = (params) => {
  3389. return new ZodBigInt({
  3390. checks: [],
  3391. typeName: ZodFirstPartyTypeKind.ZodBigInt,
  3392. coerce: params?.coerce ?? false,
  3393. ...processCreateParams(params),
  3394. });
  3395. };
  3396. class ZodBoolean extends ZodType {
  3397. _parse(input) {
  3398. if (this._def.coerce) {
  3399. input.data = Boolean(input.data);
  3400. }
  3401. const parsedType = this._getType(input);
  3402. if (parsedType !== ZodParsedType.boolean) {
  3403. const ctx = this._getOrReturnCtx(input);
  3404. addIssueToContext(ctx, {
  3405. code: ZodIssueCode.invalid_type,
  3406. expected: ZodParsedType.boolean,
  3407. received: ctx.parsedType,
  3408. });
  3409. return INVALID;
  3410. }
  3411. return OK(input.data);
  3412. }
  3413. }
  3414. ZodBoolean.create = (params) => {
  3415. return new ZodBoolean({
  3416. typeName: ZodFirstPartyTypeKind.ZodBoolean,
  3417. coerce: params?.coerce || false,
  3418. ...processCreateParams(params),
  3419. });
  3420. };
  3421. class ZodDate extends ZodType {
  3422. _parse(input) {
  3423. if (this._def.coerce) {
  3424. input.data = new Date(input.data);
  3425. }
  3426. const parsedType = this._getType(input);
  3427. if (parsedType !== ZodParsedType.date) {
  3428. const ctx = this._getOrReturnCtx(input);
  3429. addIssueToContext(ctx, {
  3430. code: ZodIssueCode.invalid_type,
  3431. expected: ZodParsedType.date,
  3432. received: ctx.parsedType,
  3433. });
  3434. return INVALID;
  3435. }
  3436. if (Number.isNaN(input.data.getTime())) {
  3437. const ctx = this._getOrReturnCtx(input);
  3438. addIssueToContext(ctx, {
  3439. code: ZodIssueCode.invalid_date,
  3440. });
  3441. return INVALID;
  3442. }
  3443. const status = new ParseStatus();
  3444. let ctx = undefined;
  3445. for (const check of this._def.checks) {
  3446. if (check.kind === "min") {
  3447. if (input.data.getTime() < check.value) {
  3448. ctx = this._getOrReturnCtx(input, ctx);
  3449. addIssueToContext(ctx, {
  3450. code: ZodIssueCode.too_small,
  3451. message: check.message,
  3452. inclusive: true,
  3453. exact: false,
  3454. minimum: check.value,
  3455. type: "date",
  3456. });
  3457. status.dirty();
  3458. }
  3459. }
  3460. else if (check.kind === "max") {
  3461. if (input.data.getTime() > check.value) {
  3462. ctx = this._getOrReturnCtx(input, ctx);
  3463. addIssueToContext(ctx, {
  3464. code: ZodIssueCode.too_big,
  3465. message: check.message,
  3466. inclusive: true,
  3467. exact: false,
  3468. maximum: check.value,
  3469. type: "date",
  3470. });
  3471. status.dirty();
  3472. }
  3473. }
  3474. else {
  3475. util.assertNever(check);
  3476. }
  3477. }
  3478. return {
  3479. status: status.value,
  3480. value: new Date(input.data.getTime()),
  3481. };
  3482. }
  3483. _addCheck(check) {
  3484. return new ZodDate({
  3485. ...this._def,
  3486. checks: [...this._def.checks, check],
  3487. });
  3488. }
  3489. min(minDate, message) {
  3490. return this._addCheck({
  3491. kind: "min",
  3492. value: minDate.getTime(),
  3493. message: errorUtil.toString(message),
  3494. });
  3495. }
  3496. max(maxDate, message) {
  3497. return this._addCheck({
  3498. kind: "max",
  3499. value: maxDate.getTime(),
  3500. message: errorUtil.toString(message),
  3501. });
  3502. }
  3503. get minDate() {
  3504. let min = null;
  3505. for (const ch of this._def.checks) {
  3506. if (ch.kind === "min") {
  3507. if (min === null || ch.value > min)
  3508. min = ch.value;
  3509. }
  3510. }
  3511. return min != null ? new Date(min) : null;
  3512. }
  3513. get maxDate() {
  3514. let max = null;
  3515. for (const ch of this._def.checks) {
  3516. if (ch.kind === "max") {
  3517. if (max === null || ch.value < max)
  3518. max = ch.value;
  3519. }
  3520. }
  3521. return max != null ? new Date(max) : null;
  3522. }
  3523. }
  3524. ZodDate.create = (params) => {
  3525. return new ZodDate({
  3526. checks: [],
  3527. coerce: params?.coerce || false,
  3528. typeName: ZodFirstPartyTypeKind.ZodDate,
  3529. ...processCreateParams(params),
  3530. });
  3531. };
  3532. class ZodSymbol extends ZodType {
  3533. _parse(input) {
  3534. const parsedType = this._getType(input);
  3535. if (parsedType !== ZodParsedType.symbol) {
  3536. const ctx = this._getOrReturnCtx(input);
  3537. addIssueToContext(ctx, {
  3538. code: ZodIssueCode.invalid_type,
  3539. expected: ZodParsedType.symbol,
  3540. received: ctx.parsedType,
  3541. });
  3542. return INVALID;
  3543. }
  3544. return OK(input.data);
  3545. }
  3546. }
  3547. ZodSymbol.create = (params) => {
  3548. return new ZodSymbol({
  3549. typeName: ZodFirstPartyTypeKind.ZodSymbol,
  3550. ...processCreateParams(params),
  3551. });
  3552. };
  3553. class ZodUndefined extends ZodType {
  3554. _parse(input) {
  3555. const parsedType = this._getType(input);
  3556. if (parsedType !== ZodParsedType.undefined) {
  3557. const ctx = this._getOrReturnCtx(input);
  3558. addIssueToContext(ctx, {
  3559. code: ZodIssueCode.invalid_type,
  3560. expected: ZodParsedType.undefined,
  3561. received: ctx.parsedType,
  3562. });
  3563. return INVALID;
  3564. }
  3565. return OK(input.data);
  3566. }
  3567. }
  3568. ZodUndefined.create = (params) => {
  3569. return new ZodUndefined({
  3570. typeName: ZodFirstPartyTypeKind.ZodUndefined,
  3571. ...processCreateParams(params),
  3572. });
  3573. };
  3574. class ZodNull extends ZodType {
  3575. _parse(input) {
  3576. const parsedType = this._getType(input);
  3577. if (parsedType !== ZodParsedType.null) {
  3578. const ctx = this._getOrReturnCtx(input);
  3579. addIssueToContext(ctx, {
  3580. code: ZodIssueCode.invalid_type,
  3581. expected: ZodParsedType.null,
  3582. received: ctx.parsedType,
  3583. });
  3584. return INVALID;
  3585. }
  3586. return OK(input.data);
  3587. }
  3588. }
  3589. ZodNull.create = (params) => {
  3590. return new ZodNull({
  3591. typeName: ZodFirstPartyTypeKind.ZodNull,
  3592. ...processCreateParams(params),
  3593. });
  3594. };
  3595. class ZodAny extends ZodType {
  3596. constructor() {
  3597. super(...arguments);
  3598. // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
  3599. this._any = true;
  3600. }
  3601. _parse(input) {
  3602. return OK(input.data);
  3603. }
  3604. }
  3605. ZodAny.create = (params) => {
  3606. return new ZodAny({
  3607. typeName: ZodFirstPartyTypeKind.ZodAny,
  3608. ...processCreateParams(params),
  3609. });
  3610. };
  3611. class ZodUnknown extends ZodType {
  3612. constructor() {
  3613. super(...arguments);
  3614. // required
  3615. this._unknown = true;
  3616. }
  3617. _parse(input) {
  3618. return OK(input.data);
  3619. }
  3620. }
  3621. ZodUnknown.create = (params) => {
  3622. return new ZodUnknown({
  3623. typeName: ZodFirstPartyTypeKind.ZodUnknown,
  3624. ...processCreateParams(params),
  3625. });
  3626. };
  3627. class ZodNever extends ZodType {
  3628. _parse(input) {
  3629. const ctx = this._getOrReturnCtx(input);
  3630. addIssueToContext(ctx, {
  3631. code: ZodIssueCode.invalid_type,
  3632. expected: ZodParsedType.never,
  3633. received: ctx.parsedType,
  3634. });
  3635. return INVALID;
  3636. }
  3637. }
  3638. ZodNever.create = (params) => {
  3639. return new ZodNever({
  3640. typeName: ZodFirstPartyTypeKind.ZodNever,
  3641. ...processCreateParams(params),
  3642. });
  3643. };
  3644. class ZodVoid extends ZodType {
  3645. _parse(input) {
  3646. const parsedType = this._getType(input);
  3647. if (parsedType !== ZodParsedType.undefined) {
  3648. const ctx = this._getOrReturnCtx(input);
  3649. addIssueToContext(ctx, {
  3650. code: ZodIssueCode.invalid_type,
  3651. expected: ZodParsedType.void,
  3652. received: ctx.parsedType,
  3653. });
  3654. return INVALID;
  3655. }
  3656. return OK(input.data);
  3657. }
  3658. }
  3659. ZodVoid.create = (params) => {
  3660. return new ZodVoid({
  3661. typeName: ZodFirstPartyTypeKind.ZodVoid,
  3662. ...processCreateParams(params),
  3663. });
  3664. };
  3665. class ZodArray extends ZodType {
  3666. _parse(input) {
  3667. const { ctx, status } = this._processInputParams(input);
  3668. const def = this._def;
  3669. if (ctx.parsedType !== ZodParsedType.array) {
  3670. addIssueToContext(ctx, {
  3671. code: ZodIssueCode.invalid_type,
  3672. expected: ZodParsedType.array,
  3673. received: ctx.parsedType,
  3674. });
  3675. return INVALID;
  3676. }
  3677. if (def.exactLength !== null) {
  3678. const tooBig = ctx.data.length > def.exactLength.value;
  3679. const tooSmall = ctx.data.length < def.exactLength.value;
  3680. if (tooBig || tooSmall) {
  3681. addIssueToContext(ctx, {
  3682. code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
  3683. minimum: (tooSmall ? def.exactLength.value : undefined),
  3684. maximum: (tooBig ? def.exactLength.value : undefined),
  3685. type: "array",
  3686. inclusive: true,
  3687. exact: true,
  3688. message: def.exactLength.message,
  3689. });
  3690. status.dirty();
  3691. }
  3692. }
  3693. if (def.minLength !== null) {
  3694. if (ctx.data.length < def.minLength.value) {
  3695. addIssueToContext(ctx, {
  3696. code: ZodIssueCode.too_small,
  3697. minimum: def.minLength.value,
  3698. type: "array",
  3699. inclusive: true,
  3700. exact: false,
  3701. message: def.minLength.message,
  3702. });
  3703. status.dirty();
  3704. }
  3705. }
  3706. if (def.maxLength !== null) {
  3707. if (ctx.data.length > def.maxLength.value) {
  3708. addIssueToContext(ctx, {
  3709. code: ZodIssueCode.too_big,
  3710. maximum: def.maxLength.value,
  3711. type: "array",
  3712. inclusive: true,
  3713. exact: false,
  3714. message: def.maxLength.message,
  3715. });
  3716. status.dirty();
  3717. }
  3718. }
  3719. if (ctx.common.async) {
  3720. return Promise.all([...ctx.data].map((item, i) => {
  3721. return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
  3722. })).then((result) => {
  3723. return ParseStatus.mergeArray(status, result);
  3724. });
  3725. }
  3726. const result = [...ctx.data].map((item, i) => {
  3727. return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
  3728. });
  3729. return ParseStatus.mergeArray(status, result);
  3730. }
  3731. get element() {
  3732. return this._def.type;
  3733. }
  3734. min(minLength, message) {
  3735. return new ZodArray({
  3736. ...this._def,
  3737. minLength: { value: minLength, message: errorUtil.toString(message) },
  3738. });
  3739. }
  3740. max(maxLength, message) {
  3741. return new ZodArray({
  3742. ...this._def,
  3743. maxLength: { value: maxLength, message: errorUtil.toString(message) },
  3744. });
  3745. }
  3746. length(len, message) {
  3747. return new ZodArray({
  3748. ...this._def,
  3749. exactLength: { value: len, message: errorUtil.toString(message) },
  3750. });
  3751. }
  3752. nonempty(message) {
  3753. return this.min(1, message);
  3754. }
  3755. }
  3756. ZodArray.create = (schema, params) => {
  3757. return new ZodArray({
  3758. type: schema,
  3759. minLength: null,
  3760. maxLength: null,
  3761. exactLength: null,
  3762. typeName: ZodFirstPartyTypeKind.ZodArray,
  3763. ...processCreateParams(params),
  3764. });
  3765. };
  3766. function deepPartialify(schema) {
  3767. if (schema instanceof ZodObject) {
  3768. const newShape = {};
  3769. for (const key in schema.shape) {
  3770. const fieldSchema = schema.shape[key];
  3771. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
  3772. }
  3773. return new ZodObject({
  3774. ...schema._def,
  3775. shape: () => newShape,
  3776. });
  3777. }
  3778. else if (schema instanceof ZodArray) {
  3779. return new ZodArray({
  3780. ...schema._def,
  3781. type: deepPartialify(schema.element),
  3782. });
  3783. }
  3784. else if (schema instanceof ZodOptional) {
  3785. return ZodOptional.create(deepPartialify(schema.unwrap()));
  3786. }
  3787. else if (schema instanceof ZodNullable) {
  3788. return ZodNullable.create(deepPartialify(schema.unwrap()));
  3789. }
  3790. else if (schema instanceof ZodTuple) {
  3791. return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  3792. }
  3793. else {
  3794. return schema;
  3795. }
  3796. }
  3797. class ZodObject extends ZodType {
  3798. constructor() {
  3799. super(...arguments);
  3800. this._cached = null;
  3801. /**
  3802. * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
  3803. * If you want to pass through unknown properties, use `.passthrough()` instead.
  3804. */
  3805. this.nonstrict = this.passthrough;
  3806. // extend<
  3807. // Augmentation extends ZodRawShape,
  3808. // NewOutput extends util.flatten<{
  3809. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  3810. // ? Augmentation[k]["_output"]
  3811. // : k extends keyof Output
  3812. // ? Output[k]
  3813. // : never;
  3814. // }>,
  3815. // NewInput extends util.flatten<{
  3816. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  3817. // ? Augmentation[k]["_input"]
  3818. // : k extends keyof Input
  3819. // ? Input[k]
  3820. // : never;
  3821. // }>
  3822. // >(
  3823. // augmentation: Augmentation
  3824. // ): ZodObject<
  3825. // extendShape<T, Augmentation>,
  3826. // UnknownKeys,
  3827. // Catchall,
  3828. // NewOutput,
  3829. // NewInput
  3830. // > {
  3831. // return new ZodObject({
  3832. // ...this._def,
  3833. // shape: () => ({
  3834. // ...this._def.shape(),
  3835. // ...augmentation,
  3836. // }),
  3837. // }) as any;
  3838. // }
  3839. /**
  3840. * @deprecated Use `.extend` instead
  3841. * */
  3842. this.augment = this.extend;
  3843. }
  3844. _getCached() {
  3845. if (this._cached !== null)
  3846. return this._cached;
  3847. const shape = this._def.shape();
  3848. const keys = util.objectKeys(shape);
  3849. this._cached = { shape, keys };
  3850. return this._cached;
  3851. }
  3852. _parse(input) {
  3853. const parsedType = this._getType(input);
  3854. if (parsedType !== ZodParsedType.object) {
  3855. const ctx = this._getOrReturnCtx(input);
  3856. addIssueToContext(ctx, {
  3857. code: ZodIssueCode.invalid_type,
  3858. expected: ZodParsedType.object,
  3859. received: ctx.parsedType,
  3860. });
  3861. return INVALID;
  3862. }
  3863. const { status, ctx } = this._processInputParams(input);
  3864. const { shape, keys: shapeKeys } = this._getCached();
  3865. const extraKeys = [];
  3866. if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
  3867. for (const key in ctx.data) {
  3868. if (!shapeKeys.includes(key)) {
  3869. extraKeys.push(key);
  3870. }
  3871. }
  3872. }
  3873. const pairs = [];
  3874. for (const key of shapeKeys) {
  3875. const keyValidator = shape[key];
  3876. const value = ctx.data[key];
  3877. pairs.push({
  3878. key: { status: "valid", value: key },
  3879. value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
  3880. alwaysSet: key in ctx.data,
  3881. });
  3882. }
  3883. if (this._def.catchall instanceof ZodNever) {
  3884. const unknownKeys = this._def.unknownKeys;
  3885. if (unknownKeys === "passthrough") {
  3886. for (const key of extraKeys) {
  3887. pairs.push({
  3888. key: { status: "valid", value: key },
  3889. value: { status: "valid", value: ctx.data[key] },
  3890. });
  3891. }
  3892. }
  3893. else if (unknownKeys === "strict") {
  3894. if (extraKeys.length > 0) {
  3895. addIssueToContext(ctx, {
  3896. code: ZodIssueCode.unrecognized_keys,
  3897. keys: extraKeys,
  3898. });
  3899. status.dirty();
  3900. }
  3901. }
  3902. else if (unknownKeys === "strip") ;
  3903. else {
  3904. throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
  3905. }
  3906. }
  3907. else {
  3908. // run catchall validation
  3909. const catchall = this._def.catchall;
  3910. for (const key of extraKeys) {
  3911. const value = ctx.data[key];
  3912. pairs.push({
  3913. key: { status: "valid", value: key },
  3914. value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
  3915. ),
  3916. alwaysSet: key in ctx.data,
  3917. });
  3918. }
  3919. }
  3920. if (ctx.common.async) {
  3921. return Promise.resolve()
  3922. .then(async () => {
  3923. const syncPairs = [];
  3924. for (const pair of pairs) {
  3925. const key = await pair.key;
  3926. const value = await pair.value;
  3927. syncPairs.push({
  3928. key,
  3929. value,
  3930. alwaysSet: pair.alwaysSet,
  3931. });
  3932. }
  3933. return syncPairs;
  3934. })
  3935. .then((syncPairs) => {
  3936. return ParseStatus.mergeObjectSync(status, syncPairs);
  3937. });
  3938. }
  3939. else {
  3940. return ParseStatus.mergeObjectSync(status, pairs);
  3941. }
  3942. }
  3943. get shape() {
  3944. return this._def.shape();
  3945. }
  3946. strict(message) {
  3947. errorUtil.errToObj;
  3948. return new ZodObject({
  3949. ...this._def,
  3950. unknownKeys: "strict",
  3951. ...(message !== undefined
  3952. ? {
  3953. errorMap: (issue, ctx) => {
  3954. const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
  3955. if (issue.code === "unrecognized_keys")
  3956. return {
  3957. message: errorUtil.errToObj(message).message ?? defaultError,
  3958. };
  3959. return {
  3960. message: defaultError,
  3961. };
  3962. },
  3963. }
  3964. : {}),
  3965. });
  3966. }
  3967. strip() {
  3968. return new ZodObject({
  3969. ...this._def,
  3970. unknownKeys: "strip",
  3971. });
  3972. }
  3973. passthrough() {
  3974. return new ZodObject({
  3975. ...this._def,
  3976. unknownKeys: "passthrough",
  3977. });
  3978. }
  3979. // const AugmentFactory =
  3980. // <Def extends ZodObjectDef>(def: Def) =>
  3981. // <Augmentation extends ZodRawShape>(
  3982. // augmentation: Augmentation
  3983. // ): ZodObject<
  3984. // extendShape<ReturnType<Def["shape"]>, Augmentation>,
  3985. // Def["unknownKeys"],
  3986. // Def["catchall"]
  3987. // > => {
  3988. // return new ZodObject({
  3989. // ...def,
  3990. // shape: () => ({
  3991. // ...def.shape(),
  3992. // ...augmentation,
  3993. // }),
  3994. // }) as any;
  3995. // };
  3996. extend(augmentation) {
  3997. return new ZodObject({
  3998. ...this._def,
  3999. shape: () => ({
  4000. ...this._def.shape(),
  4001. ...augmentation,
  4002. }),
  4003. });
  4004. }
  4005. /**
  4006. * Prior to zod@1.0.12 there was a bug in the
  4007. * inferred type of merged objects. Please
  4008. * upgrade if you are experiencing issues.
  4009. */
  4010. merge(merging) {
  4011. const merged = new ZodObject({
  4012. unknownKeys: merging._def.unknownKeys,
  4013. catchall: merging._def.catchall,
  4014. shape: () => ({
  4015. ...this._def.shape(),
  4016. ...merging._def.shape(),
  4017. }),
  4018. typeName: ZodFirstPartyTypeKind.ZodObject,
  4019. });
  4020. return merged;
  4021. }
  4022. // merge<
  4023. // Incoming extends AnyZodObject,
  4024. // Augmentation extends Incoming["shape"],
  4025. // NewOutput extends {
  4026. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  4027. // ? Augmentation[k]["_output"]
  4028. // : k extends keyof Output
  4029. // ? Output[k]
  4030. // : never;
  4031. // },
  4032. // NewInput extends {
  4033. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  4034. // ? Augmentation[k]["_input"]
  4035. // : k extends keyof Input
  4036. // ? Input[k]
  4037. // : never;
  4038. // }
  4039. // >(
  4040. // merging: Incoming
  4041. // ): ZodObject<
  4042. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  4043. // Incoming["_def"]["unknownKeys"],
  4044. // Incoming["_def"]["catchall"],
  4045. // NewOutput,
  4046. // NewInput
  4047. // > {
  4048. // const merged: any = new ZodObject({
  4049. // unknownKeys: merging._def.unknownKeys,
  4050. // catchall: merging._def.catchall,
  4051. // shape: () =>
  4052. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  4053. // typeName: ZodFirstPartyTypeKind.ZodObject,
  4054. // }) as any;
  4055. // return merged;
  4056. // }
  4057. setKey(key, schema) {
  4058. return this.augment({ [key]: schema });
  4059. }
  4060. // merge<Incoming extends AnyZodObject>(
  4061. // merging: Incoming
  4062. // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  4063. // ZodObject<
  4064. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  4065. // Incoming["_def"]["unknownKeys"],
  4066. // Incoming["_def"]["catchall"]
  4067. // > {
  4068. // // const mergedShape = objectUtil.mergeShapes(
  4069. // // this._def.shape(),
  4070. // // merging._def.shape()
  4071. // // );
  4072. // const merged: any = new ZodObject({
  4073. // unknownKeys: merging._def.unknownKeys,
  4074. // catchall: merging._def.catchall,
  4075. // shape: () =>
  4076. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  4077. // typeName: ZodFirstPartyTypeKind.ZodObject,
  4078. // }) as any;
  4079. // return merged;
  4080. // }
  4081. catchall(index) {
  4082. return new ZodObject({
  4083. ...this._def,
  4084. catchall: index,
  4085. });
  4086. }
  4087. pick(mask) {
  4088. const shape = {};
  4089. for (const key of util.objectKeys(mask)) {
  4090. if (mask[key] && this.shape[key]) {
  4091. shape[key] = this.shape[key];
  4092. }
  4093. }
  4094. return new ZodObject({
  4095. ...this._def,
  4096. shape: () => shape,
  4097. });
  4098. }
  4099. omit(mask) {
  4100. const shape = {};
  4101. for (const key of util.objectKeys(this.shape)) {
  4102. if (!mask[key]) {
  4103. shape[key] = this.shape[key];
  4104. }
  4105. }
  4106. return new ZodObject({
  4107. ...this._def,
  4108. shape: () => shape,
  4109. });
  4110. }
  4111. /**
  4112. * @deprecated
  4113. */
  4114. deepPartial() {
  4115. return deepPartialify(this);
  4116. }
  4117. partial(mask) {
  4118. const newShape = {};
  4119. for (const key of util.objectKeys(this.shape)) {
  4120. const fieldSchema = this.shape[key];
  4121. if (mask && !mask[key]) {
  4122. newShape[key] = fieldSchema;
  4123. }
  4124. else {
  4125. newShape[key] = fieldSchema.optional();
  4126. }
  4127. }
  4128. return new ZodObject({
  4129. ...this._def,
  4130. shape: () => newShape,
  4131. });
  4132. }
  4133. required(mask) {
  4134. const newShape = {};
  4135. for (const key of util.objectKeys(this.shape)) {
  4136. if (mask && !mask[key]) {
  4137. newShape[key] = this.shape[key];
  4138. }
  4139. else {
  4140. const fieldSchema = this.shape[key];
  4141. let newField = fieldSchema;
  4142. while (newField instanceof ZodOptional) {
  4143. newField = newField._def.innerType;
  4144. }
  4145. newShape[key] = newField;
  4146. }
  4147. }
  4148. return new ZodObject({
  4149. ...this._def,
  4150. shape: () => newShape,
  4151. });
  4152. }
  4153. keyof() {
  4154. return createZodEnum(util.objectKeys(this.shape));
  4155. }
  4156. }
  4157. ZodObject.create = (shape, params) => {
  4158. return new ZodObject({
  4159. shape: () => shape,
  4160. unknownKeys: "strip",
  4161. catchall: ZodNever.create(),
  4162. typeName: ZodFirstPartyTypeKind.ZodObject,
  4163. ...processCreateParams(params),
  4164. });
  4165. };
  4166. ZodObject.strictCreate = (shape, params) => {
  4167. return new ZodObject({
  4168. shape: () => shape,
  4169. unknownKeys: "strict",
  4170. catchall: ZodNever.create(),
  4171. typeName: ZodFirstPartyTypeKind.ZodObject,
  4172. ...processCreateParams(params),
  4173. });
  4174. };
  4175. ZodObject.lazycreate = (shape, params) => {
  4176. return new ZodObject({
  4177. shape,
  4178. unknownKeys: "strip",
  4179. catchall: ZodNever.create(),
  4180. typeName: ZodFirstPartyTypeKind.ZodObject,
  4181. ...processCreateParams(params),
  4182. });
  4183. };
  4184. class ZodUnion extends ZodType {
  4185. _parse(input) {
  4186. const { ctx } = this._processInputParams(input);
  4187. const options = this._def.options;
  4188. function handleResults(results) {
  4189. // return first issue-free validation if it exists
  4190. for (const result of results) {
  4191. if (result.result.status === "valid") {
  4192. return result.result;
  4193. }
  4194. }
  4195. for (const result of results) {
  4196. if (result.result.status === "dirty") {
  4197. // add issues from dirty option
  4198. ctx.common.issues.push(...result.ctx.common.issues);
  4199. return result.result;
  4200. }
  4201. }
  4202. // return invalid
  4203. const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
  4204. addIssueToContext(ctx, {
  4205. code: ZodIssueCode.invalid_union,
  4206. unionErrors,
  4207. });
  4208. return INVALID;
  4209. }
  4210. if (ctx.common.async) {
  4211. return Promise.all(options.map(async (option) => {
  4212. const childCtx = {
  4213. ...ctx,
  4214. common: {
  4215. ...ctx.common,
  4216. issues: [],
  4217. },
  4218. parent: null,
  4219. };
  4220. return {
  4221. result: await option._parseAsync({
  4222. data: ctx.data,
  4223. path: ctx.path,
  4224. parent: childCtx,
  4225. }),
  4226. ctx: childCtx,
  4227. };
  4228. })).then(handleResults);
  4229. }
  4230. else {
  4231. let dirty = undefined;
  4232. const issues = [];
  4233. for (const option of options) {
  4234. const childCtx = {
  4235. ...ctx,
  4236. common: {
  4237. ...ctx.common,
  4238. issues: [],
  4239. },
  4240. parent: null,
  4241. };
  4242. const result = option._parseSync({
  4243. data: ctx.data,
  4244. path: ctx.path,
  4245. parent: childCtx,
  4246. });
  4247. if (result.status === "valid") {
  4248. return result;
  4249. }
  4250. else if (result.status === "dirty" && !dirty) {
  4251. dirty = { result, ctx: childCtx };
  4252. }
  4253. if (childCtx.common.issues.length) {
  4254. issues.push(childCtx.common.issues);
  4255. }
  4256. }
  4257. if (dirty) {
  4258. ctx.common.issues.push(...dirty.ctx.common.issues);
  4259. return dirty.result;
  4260. }
  4261. const unionErrors = issues.map((issues) => new ZodError(issues));
  4262. addIssueToContext(ctx, {
  4263. code: ZodIssueCode.invalid_union,
  4264. unionErrors,
  4265. });
  4266. return INVALID;
  4267. }
  4268. }
  4269. get options() {
  4270. return this._def.options;
  4271. }
  4272. }
  4273. ZodUnion.create = (types, params) => {
  4274. return new ZodUnion({
  4275. options: types,
  4276. typeName: ZodFirstPartyTypeKind.ZodUnion,
  4277. ...processCreateParams(params),
  4278. });
  4279. };
  4280. function mergeValues(a, b) {
  4281. const aType = getParsedType(a);
  4282. const bType = getParsedType(b);
  4283. if (a === b) {
  4284. return { valid: true, data: a };
  4285. }
  4286. else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
  4287. const bKeys = util.objectKeys(b);
  4288. const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
  4289. const newObj = { ...a, ...b };
  4290. for (const key of sharedKeys) {
  4291. const sharedValue = mergeValues(a[key], b[key]);
  4292. if (!sharedValue.valid) {
  4293. return { valid: false };
  4294. }
  4295. newObj[key] = sharedValue.data;
  4296. }
  4297. return { valid: true, data: newObj };
  4298. }
  4299. else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
  4300. if (a.length !== b.length) {
  4301. return { valid: false };
  4302. }
  4303. const newArray = [];
  4304. for (let index = 0; index < a.length; index++) {
  4305. const itemA = a[index];
  4306. const itemB = b[index];
  4307. const sharedValue = mergeValues(itemA, itemB);
  4308. if (!sharedValue.valid) {
  4309. return { valid: false };
  4310. }
  4311. newArray.push(sharedValue.data);
  4312. }
  4313. return { valid: true, data: newArray };
  4314. }
  4315. else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
  4316. return { valid: true, data: a };
  4317. }
  4318. else {
  4319. return { valid: false };
  4320. }
  4321. }
  4322. class ZodIntersection extends ZodType {
  4323. _parse(input) {
  4324. const { status, ctx } = this._processInputParams(input);
  4325. const handleParsed = (parsedLeft, parsedRight) => {
  4326. if (isAborted(parsedLeft) || isAborted(parsedRight)) {
  4327. return INVALID;
  4328. }
  4329. const merged = mergeValues(parsedLeft.value, parsedRight.value);
  4330. if (!merged.valid) {
  4331. addIssueToContext(ctx, {
  4332. code: ZodIssueCode.invalid_intersection_types,
  4333. });
  4334. return INVALID;
  4335. }
  4336. if (isDirty(parsedLeft) || isDirty(parsedRight)) {
  4337. status.dirty();
  4338. }
  4339. return { status: status.value, value: merged.data };
  4340. };
  4341. if (ctx.common.async) {
  4342. return Promise.all([
  4343. this._def.left._parseAsync({
  4344. data: ctx.data,
  4345. path: ctx.path,
  4346. parent: ctx,
  4347. }),
  4348. this._def.right._parseAsync({
  4349. data: ctx.data,
  4350. path: ctx.path,
  4351. parent: ctx,
  4352. }),
  4353. ]).then(([left, right]) => handleParsed(left, right));
  4354. }
  4355. else {
  4356. return handleParsed(this._def.left._parseSync({
  4357. data: ctx.data,
  4358. path: ctx.path,
  4359. parent: ctx,
  4360. }), this._def.right._parseSync({
  4361. data: ctx.data,
  4362. path: ctx.path,
  4363. parent: ctx,
  4364. }));
  4365. }
  4366. }
  4367. }
  4368. ZodIntersection.create = (left, right, params) => {
  4369. return new ZodIntersection({
  4370. left: left,
  4371. right: right,
  4372. typeName: ZodFirstPartyTypeKind.ZodIntersection,
  4373. ...processCreateParams(params),
  4374. });
  4375. };
  4376. // type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];
  4377. class ZodTuple extends ZodType {
  4378. _parse(input) {
  4379. const { status, ctx } = this._processInputParams(input);
  4380. if (ctx.parsedType !== ZodParsedType.array) {
  4381. addIssueToContext(ctx, {
  4382. code: ZodIssueCode.invalid_type,
  4383. expected: ZodParsedType.array,
  4384. received: ctx.parsedType,
  4385. });
  4386. return INVALID;
  4387. }
  4388. if (ctx.data.length < this._def.items.length) {
  4389. addIssueToContext(ctx, {
  4390. code: ZodIssueCode.too_small,
  4391. minimum: this._def.items.length,
  4392. inclusive: true,
  4393. exact: false,
  4394. type: "array",
  4395. });
  4396. return INVALID;
  4397. }
  4398. const rest = this._def.rest;
  4399. if (!rest && ctx.data.length > this._def.items.length) {
  4400. addIssueToContext(ctx, {
  4401. code: ZodIssueCode.too_big,
  4402. maximum: this._def.items.length,
  4403. inclusive: true,
  4404. exact: false,
  4405. type: "array",
  4406. });
  4407. status.dirty();
  4408. }
  4409. const items = [...ctx.data]
  4410. .map((item, itemIndex) => {
  4411. const schema = this._def.items[itemIndex] || this._def.rest;
  4412. if (!schema)
  4413. return null;
  4414. return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
  4415. })
  4416. .filter((x) => !!x); // filter nulls
  4417. if (ctx.common.async) {
  4418. return Promise.all(items).then((results) => {
  4419. return ParseStatus.mergeArray(status, results);
  4420. });
  4421. }
  4422. else {
  4423. return ParseStatus.mergeArray(status, items);
  4424. }
  4425. }
  4426. get items() {
  4427. return this._def.items;
  4428. }
  4429. rest(rest) {
  4430. return new ZodTuple({
  4431. ...this._def,
  4432. rest,
  4433. });
  4434. }
  4435. }
  4436. ZodTuple.create = (schemas, params) => {
  4437. if (!Array.isArray(schemas)) {
  4438. throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  4439. }
  4440. return new ZodTuple({
  4441. items: schemas,
  4442. typeName: ZodFirstPartyTypeKind.ZodTuple,
  4443. rest: null,
  4444. ...processCreateParams(params),
  4445. });
  4446. };
  4447. class ZodMap extends ZodType {
  4448. get keySchema() {
  4449. return this._def.keyType;
  4450. }
  4451. get valueSchema() {
  4452. return this._def.valueType;
  4453. }
  4454. _parse(input) {
  4455. const { status, ctx } = this._processInputParams(input);
  4456. if (ctx.parsedType !== ZodParsedType.map) {
  4457. addIssueToContext(ctx, {
  4458. code: ZodIssueCode.invalid_type,
  4459. expected: ZodParsedType.map,
  4460. received: ctx.parsedType,
  4461. });
  4462. return INVALID;
  4463. }
  4464. const keyType = this._def.keyType;
  4465. const valueType = this._def.valueType;
  4466. const pairs = [...ctx.data.entries()].map(([key, value], index) => {
  4467. return {
  4468. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
  4469. value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
  4470. };
  4471. });
  4472. if (ctx.common.async) {
  4473. const finalMap = new Map();
  4474. return Promise.resolve().then(async () => {
  4475. for (const pair of pairs) {
  4476. const key = await pair.key;
  4477. const value = await pair.value;
  4478. if (key.status === "aborted" || value.status === "aborted") {
  4479. return INVALID;
  4480. }
  4481. if (key.status === "dirty" || value.status === "dirty") {
  4482. status.dirty();
  4483. }
  4484. finalMap.set(key.value, value.value);
  4485. }
  4486. return { status: status.value, value: finalMap };
  4487. });
  4488. }
  4489. else {
  4490. const finalMap = new Map();
  4491. for (const pair of pairs) {
  4492. const key = pair.key;
  4493. const value = pair.value;
  4494. if (key.status === "aborted" || value.status === "aborted") {
  4495. return INVALID;
  4496. }
  4497. if (key.status === "dirty" || value.status === "dirty") {
  4498. status.dirty();
  4499. }
  4500. finalMap.set(key.value, value.value);
  4501. }
  4502. return { status: status.value, value: finalMap };
  4503. }
  4504. }
  4505. }
  4506. ZodMap.create = (keyType, valueType, params) => {
  4507. return new ZodMap({
  4508. valueType,
  4509. keyType,
  4510. typeName: ZodFirstPartyTypeKind.ZodMap,
  4511. ...processCreateParams(params),
  4512. });
  4513. };
  4514. class ZodSet extends ZodType {
  4515. _parse(input) {
  4516. const { status, ctx } = this._processInputParams(input);
  4517. if (ctx.parsedType !== ZodParsedType.set) {
  4518. addIssueToContext(ctx, {
  4519. code: ZodIssueCode.invalid_type,
  4520. expected: ZodParsedType.set,
  4521. received: ctx.parsedType,
  4522. });
  4523. return INVALID;
  4524. }
  4525. const def = this._def;
  4526. if (def.minSize !== null) {
  4527. if (ctx.data.size < def.minSize.value) {
  4528. addIssueToContext(ctx, {
  4529. code: ZodIssueCode.too_small,
  4530. minimum: def.minSize.value,
  4531. type: "set",
  4532. inclusive: true,
  4533. exact: false,
  4534. message: def.minSize.message,
  4535. });
  4536. status.dirty();
  4537. }
  4538. }
  4539. if (def.maxSize !== null) {
  4540. if (ctx.data.size > def.maxSize.value) {
  4541. addIssueToContext(ctx, {
  4542. code: ZodIssueCode.too_big,
  4543. maximum: def.maxSize.value,
  4544. type: "set",
  4545. inclusive: true,
  4546. exact: false,
  4547. message: def.maxSize.message,
  4548. });
  4549. status.dirty();
  4550. }
  4551. }
  4552. const valueType = this._def.valueType;
  4553. function finalizeSet(elements) {
  4554. const parsedSet = new Set();
  4555. for (const element of elements) {
  4556. if (element.status === "aborted")
  4557. return INVALID;
  4558. if (element.status === "dirty")
  4559. status.dirty();
  4560. parsedSet.add(element.value);
  4561. }
  4562. return { status: status.value, value: parsedSet };
  4563. }
  4564. const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
  4565. if (ctx.common.async) {
  4566. return Promise.all(elements).then((elements) => finalizeSet(elements));
  4567. }
  4568. else {
  4569. return finalizeSet(elements);
  4570. }
  4571. }
  4572. min(minSize, message) {
  4573. return new ZodSet({
  4574. ...this._def,
  4575. minSize: { value: minSize, message: errorUtil.toString(message) },
  4576. });
  4577. }
  4578. max(maxSize, message) {
  4579. return new ZodSet({
  4580. ...this._def,
  4581. maxSize: { value: maxSize, message: errorUtil.toString(message) },
  4582. });
  4583. }
  4584. size(size, message) {
  4585. return this.min(size, message).max(size, message);
  4586. }
  4587. nonempty(message) {
  4588. return this.min(1, message);
  4589. }
  4590. }
  4591. ZodSet.create = (valueType, params) => {
  4592. return new ZodSet({
  4593. valueType,
  4594. minSize: null,
  4595. maxSize: null,
  4596. typeName: ZodFirstPartyTypeKind.ZodSet,
  4597. ...processCreateParams(params),
  4598. });
  4599. };
  4600. class ZodLazy extends ZodType {
  4601. get schema() {
  4602. return this._def.getter();
  4603. }
  4604. _parse(input) {
  4605. const { ctx } = this._processInputParams(input);
  4606. const lazySchema = this._def.getter();
  4607. return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  4608. }
  4609. }
  4610. ZodLazy.create = (getter, params) => {
  4611. return new ZodLazy({
  4612. getter: getter,
  4613. typeName: ZodFirstPartyTypeKind.ZodLazy,
  4614. ...processCreateParams(params),
  4615. });
  4616. };
  4617. class ZodLiteral extends ZodType {
  4618. _parse(input) {
  4619. if (input.data !== this._def.value) {
  4620. const ctx = this._getOrReturnCtx(input);
  4621. addIssueToContext(ctx, {
  4622. received: ctx.data,
  4623. code: ZodIssueCode.invalid_literal,
  4624. expected: this._def.value,
  4625. });
  4626. return INVALID;
  4627. }
  4628. return { status: "valid", value: input.data };
  4629. }
  4630. get value() {
  4631. return this._def.value;
  4632. }
  4633. }
  4634. ZodLiteral.create = (value, params) => {
  4635. return new ZodLiteral({
  4636. value: value,
  4637. typeName: ZodFirstPartyTypeKind.ZodLiteral,
  4638. ...processCreateParams(params),
  4639. });
  4640. };
  4641. function createZodEnum(values, params) {
  4642. return new ZodEnum({
  4643. values,
  4644. typeName: ZodFirstPartyTypeKind.ZodEnum,
  4645. ...processCreateParams(params),
  4646. });
  4647. }
  4648. class ZodEnum extends ZodType {
  4649. _parse(input) {
  4650. if (typeof input.data !== "string") {
  4651. const ctx = this._getOrReturnCtx(input);
  4652. const expectedValues = this._def.values;
  4653. addIssueToContext(ctx, {
  4654. expected: util.joinValues(expectedValues),
  4655. received: ctx.parsedType,
  4656. code: ZodIssueCode.invalid_type,
  4657. });
  4658. return INVALID;
  4659. }
  4660. if (!this._cache) {
  4661. this._cache = new Set(this._def.values);
  4662. }
  4663. if (!this._cache.has(input.data)) {
  4664. const ctx = this._getOrReturnCtx(input);
  4665. const expectedValues = this._def.values;
  4666. addIssueToContext(ctx, {
  4667. received: ctx.data,
  4668. code: ZodIssueCode.invalid_enum_value,
  4669. options: expectedValues,
  4670. });
  4671. return INVALID;
  4672. }
  4673. return OK(input.data);
  4674. }
  4675. get options() {
  4676. return this._def.values;
  4677. }
  4678. get enum() {
  4679. const enumValues = {};
  4680. for (const val of this._def.values) {
  4681. enumValues[val] = val;
  4682. }
  4683. return enumValues;
  4684. }
  4685. get Values() {
  4686. const enumValues = {};
  4687. for (const val of this._def.values) {
  4688. enumValues[val] = val;
  4689. }
  4690. return enumValues;
  4691. }
  4692. get Enum() {
  4693. const enumValues = {};
  4694. for (const val of this._def.values) {
  4695. enumValues[val] = val;
  4696. }
  4697. return enumValues;
  4698. }
  4699. extract(values, newDef = this._def) {
  4700. return ZodEnum.create(values, {
  4701. ...this._def,
  4702. ...newDef,
  4703. });
  4704. }
  4705. exclude(values, newDef = this._def) {
  4706. return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
  4707. ...this._def,
  4708. ...newDef,
  4709. });
  4710. }
  4711. }
  4712. ZodEnum.create = createZodEnum;
  4713. class ZodNativeEnum extends ZodType {
  4714. _parse(input) {
  4715. const nativeEnumValues = util.getValidEnumValues(this._def.values);
  4716. const ctx = this._getOrReturnCtx(input);
  4717. if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
  4718. const expectedValues = util.objectValues(nativeEnumValues);
  4719. addIssueToContext(ctx, {
  4720. expected: util.joinValues(expectedValues),
  4721. received: ctx.parsedType,
  4722. code: ZodIssueCode.invalid_type,
  4723. });
  4724. return INVALID;
  4725. }
  4726. if (!this._cache) {
  4727. this._cache = new Set(util.getValidEnumValues(this._def.values));
  4728. }
  4729. if (!this._cache.has(input.data)) {
  4730. const expectedValues = util.objectValues(nativeEnumValues);
  4731. addIssueToContext(ctx, {
  4732. received: ctx.data,
  4733. code: ZodIssueCode.invalid_enum_value,
  4734. options: expectedValues,
  4735. });
  4736. return INVALID;
  4737. }
  4738. return OK(input.data);
  4739. }
  4740. get enum() {
  4741. return this._def.values;
  4742. }
  4743. }
  4744. ZodNativeEnum.create = (values, params) => {
  4745. return new ZodNativeEnum({
  4746. values: values,
  4747. typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
  4748. ...processCreateParams(params),
  4749. });
  4750. };
  4751. class ZodPromise extends ZodType {
  4752. unwrap() {
  4753. return this._def.type;
  4754. }
  4755. _parse(input) {
  4756. const { ctx } = this._processInputParams(input);
  4757. if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
  4758. addIssueToContext(ctx, {
  4759. code: ZodIssueCode.invalid_type,
  4760. expected: ZodParsedType.promise,
  4761. received: ctx.parsedType,
  4762. });
  4763. return INVALID;
  4764. }
  4765. const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
  4766. return OK(promisified.then((data) => {
  4767. return this._def.type.parseAsync(data, {
  4768. path: ctx.path,
  4769. errorMap: ctx.common.contextualErrorMap,
  4770. });
  4771. }));
  4772. }
  4773. }
  4774. ZodPromise.create = (schema, params) => {
  4775. return new ZodPromise({
  4776. type: schema,
  4777. typeName: ZodFirstPartyTypeKind.ZodPromise,
  4778. ...processCreateParams(params),
  4779. });
  4780. };
  4781. class ZodEffects extends ZodType {
  4782. innerType() {
  4783. return this._def.schema;
  4784. }
  4785. sourceType() {
  4786. return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
  4787. ? this._def.schema.sourceType()
  4788. : this._def.schema;
  4789. }
  4790. _parse(input) {
  4791. const { status, ctx } = this._processInputParams(input);
  4792. const effect = this._def.effect || null;
  4793. const checkCtx = {
  4794. addIssue: (arg) => {
  4795. addIssueToContext(ctx, arg);
  4796. if (arg.fatal) {
  4797. status.abort();
  4798. }
  4799. else {
  4800. status.dirty();
  4801. }
  4802. },
  4803. get path() {
  4804. return ctx.path;
  4805. },
  4806. };
  4807. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
  4808. if (effect.type === "preprocess") {
  4809. const processed = effect.transform(ctx.data, checkCtx);
  4810. if (ctx.common.async) {
  4811. return Promise.resolve(processed).then(async (processed) => {
  4812. if (status.value === "aborted")
  4813. return INVALID;
  4814. const result = await this._def.schema._parseAsync({
  4815. data: processed,
  4816. path: ctx.path,
  4817. parent: ctx,
  4818. });
  4819. if (result.status === "aborted")
  4820. return INVALID;
  4821. if (result.status === "dirty")
  4822. return DIRTY(result.value);
  4823. if (status.value === "dirty")
  4824. return DIRTY(result.value);
  4825. return result;
  4826. });
  4827. }
  4828. else {
  4829. if (status.value === "aborted")
  4830. return INVALID;
  4831. const result = this._def.schema._parseSync({
  4832. data: processed,
  4833. path: ctx.path,
  4834. parent: ctx,
  4835. });
  4836. if (result.status === "aborted")
  4837. return INVALID;
  4838. if (result.status === "dirty")
  4839. return DIRTY(result.value);
  4840. if (status.value === "dirty")
  4841. return DIRTY(result.value);
  4842. return result;
  4843. }
  4844. }
  4845. if (effect.type === "refinement") {
  4846. const executeRefinement = (acc) => {
  4847. const result = effect.refinement(acc, checkCtx);
  4848. if (ctx.common.async) {
  4849. return Promise.resolve(result);
  4850. }
  4851. if (result instanceof Promise) {
  4852. throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
  4853. }
  4854. return acc;
  4855. };
  4856. if (ctx.common.async === false) {
  4857. const inner = this._def.schema._parseSync({
  4858. data: ctx.data,
  4859. path: ctx.path,
  4860. parent: ctx,
  4861. });
  4862. if (inner.status === "aborted")
  4863. return INVALID;
  4864. if (inner.status === "dirty")
  4865. status.dirty();
  4866. // return value is ignored
  4867. executeRefinement(inner.value);
  4868. return { status: status.value, value: inner.value };
  4869. }
  4870. else {
  4871. return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
  4872. if (inner.status === "aborted")
  4873. return INVALID;
  4874. if (inner.status === "dirty")
  4875. status.dirty();
  4876. return executeRefinement(inner.value).then(() => {
  4877. return { status: status.value, value: inner.value };
  4878. });
  4879. });
  4880. }
  4881. }
  4882. if (effect.type === "transform") {
  4883. if (ctx.common.async === false) {
  4884. const base = this._def.schema._parseSync({
  4885. data: ctx.data,
  4886. path: ctx.path,
  4887. parent: ctx,
  4888. });
  4889. if (!isValid(base))
  4890. return INVALID;
  4891. const result = effect.transform(base.value, checkCtx);
  4892. if (result instanceof Promise) {
  4893. throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
  4894. }
  4895. return { status: status.value, value: result };
  4896. }
  4897. else {
  4898. return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
  4899. if (!isValid(base))
  4900. return INVALID;
  4901. return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
  4902. status: status.value,
  4903. value: result,
  4904. }));
  4905. });
  4906. }
  4907. }
  4908. util.assertNever(effect);
  4909. }
  4910. }
  4911. ZodEffects.create = (schema, effect, params) => {
  4912. return new ZodEffects({
  4913. schema,
  4914. typeName: ZodFirstPartyTypeKind.ZodEffects,
  4915. effect,
  4916. ...processCreateParams(params),
  4917. });
  4918. };
  4919. ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
  4920. return new ZodEffects({
  4921. schema,
  4922. effect: { type: "preprocess", transform: preprocess },
  4923. typeName: ZodFirstPartyTypeKind.ZodEffects,
  4924. ...processCreateParams(params),
  4925. });
  4926. };
  4927. class ZodOptional extends ZodType {
  4928. _parse(input) {
  4929. const parsedType = this._getType(input);
  4930. if (parsedType === ZodParsedType.undefined) {
  4931. return OK(undefined);
  4932. }
  4933. return this._def.innerType._parse(input);
  4934. }
  4935. unwrap() {
  4936. return this._def.innerType;
  4937. }
  4938. }
  4939. ZodOptional.create = (type, params) => {
  4940. return new ZodOptional({
  4941. innerType: type,
  4942. typeName: ZodFirstPartyTypeKind.ZodOptional,
  4943. ...processCreateParams(params),
  4944. });
  4945. };
  4946. class ZodNullable extends ZodType {
  4947. _parse(input) {
  4948. const parsedType = this._getType(input);
  4949. if (parsedType === ZodParsedType.null) {
  4950. return OK(null);
  4951. }
  4952. return this._def.innerType._parse(input);
  4953. }
  4954. unwrap() {
  4955. return this._def.innerType;
  4956. }
  4957. }
  4958. ZodNullable.create = (type, params) => {
  4959. return new ZodNullable({
  4960. innerType: type,
  4961. typeName: ZodFirstPartyTypeKind.ZodNullable,
  4962. ...processCreateParams(params),
  4963. });
  4964. };
  4965. class ZodDefault extends ZodType {
  4966. _parse(input) {
  4967. const { ctx } = this._processInputParams(input);
  4968. let data = ctx.data;
  4969. if (ctx.parsedType === ZodParsedType.undefined) {
  4970. data = this._def.defaultValue();
  4971. }
  4972. return this._def.innerType._parse({
  4973. data,
  4974. path: ctx.path,
  4975. parent: ctx,
  4976. });
  4977. }
  4978. removeDefault() {
  4979. return this._def.innerType;
  4980. }
  4981. }
  4982. ZodDefault.create = (type, params) => {
  4983. return new ZodDefault({
  4984. innerType: type,
  4985. typeName: ZodFirstPartyTypeKind.ZodDefault,
  4986. defaultValue: typeof params.default === "function" ? params.default : () => params.default,
  4987. ...processCreateParams(params),
  4988. });
  4989. };
  4990. class ZodCatch extends ZodType {
  4991. _parse(input) {
  4992. const { ctx } = this._processInputParams(input);
  4993. // newCtx is used to not collect issues from inner types in ctx
  4994. const newCtx = {
  4995. ...ctx,
  4996. common: {
  4997. ...ctx.common,
  4998. issues: [],
  4999. },
  5000. };
  5001. const result = this._def.innerType._parse({
  5002. data: newCtx.data,
  5003. path: newCtx.path,
  5004. parent: {
  5005. ...newCtx,
  5006. },
  5007. });
  5008. if (isAsync(result)) {
  5009. return result.then((result) => {
  5010. return {
  5011. status: "valid",
  5012. value: result.status === "valid"
  5013. ? result.value
  5014. : this._def.catchValue({
  5015. get error() {
  5016. return new ZodError(newCtx.common.issues);
  5017. },
  5018. input: newCtx.data,
  5019. }),
  5020. };
  5021. });
  5022. }
  5023. else {
  5024. return {
  5025. status: "valid",
  5026. value: result.status === "valid"
  5027. ? result.value
  5028. : this._def.catchValue({
  5029. get error() {
  5030. return new ZodError(newCtx.common.issues);
  5031. },
  5032. input: newCtx.data,
  5033. }),
  5034. };
  5035. }
  5036. }
  5037. removeCatch() {
  5038. return this._def.innerType;
  5039. }
  5040. }
  5041. ZodCatch.create = (type, params) => {
  5042. return new ZodCatch({
  5043. innerType: type,
  5044. typeName: ZodFirstPartyTypeKind.ZodCatch,
  5045. catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
  5046. ...processCreateParams(params),
  5047. });
  5048. };
  5049. class ZodNaN extends ZodType {
  5050. _parse(input) {
  5051. const parsedType = this._getType(input);
  5052. if (parsedType !== ZodParsedType.nan) {
  5053. const ctx = this._getOrReturnCtx(input);
  5054. addIssueToContext(ctx, {
  5055. code: ZodIssueCode.invalid_type,
  5056. expected: ZodParsedType.nan,
  5057. received: ctx.parsedType,
  5058. });
  5059. return INVALID;
  5060. }
  5061. return { status: "valid", value: input.data };
  5062. }
  5063. }
  5064. ZodNaN.create = (params) => {
  5065. return new ZodNaN({
  5066. typeName: ZodFirstPartyTypeKind.ZodNaN,
  5067. ...processCreateParams(params),
  5068. });
  5069. };
  5070. class ZodBranded extends ZodType {
  5071. _parse(input) {
  5072. const { ctx } = this._processInputParams(input);
  5073. const data = ctx.data;
  5074. return this._def.type._parse({
  5075. data,
  5076. path: ctx.path,
  5077. parent: ctx,
  5078. });
  5079. }
  5080. unwrap() {
  5081. return this._def.type;
  5082. }
  5083. }
  5084. class ZodPipeline extends ZodType {
  5085. _parse(input) {
  5086. const { status, ctx } = this._processInputParams(input);
  5087. if (ctx.common.async) {
  5088. const handleAsync = async () => {
  5089. const inResult = await this._def.in._parseAsync({
  5090. data: ctx.data,
  5091. path: ctx.path,
  5092. parent: ctx,
  5093. });
  5094. if (inResult.status === "aborted")
  5095. return INVALID;
  5096. if (inResult.status === "dirty") {
  5097. status.dirty();
  5098. return DIRTY(inResult.value);
  5099. }
  5100. else {
  5101. return this._def.out._parseAsync({
  5102. data: inResult.value,
  5103. path: ctx.path,
  5104. parent: ctx,
  5105. });
  5106. }
  5107. };
  5108. return handleAsync();
  5109. }
  5110. else {
  5111. const inResult = this._def.in._parseSync({
  5112. data: ctx.data,
  5113. path: ctx.path,
  5114. parent: ctx,
  5115. });
  5116. if (inResult.status === "aborted")
  5117. return INVALID;
  5118. if (inResult.status === "dirty") {
  5119. status.dirty();
  5120. return {
  5121. status: "dirty",
  5122. value: inResult.value,
  5123. };
  5124. }
  5125. else {
  5126. return this._def.out._parseSync({
  5127. data: inResult.value,
  5128. path: ctx.path,
  5129. parent: ctx,
  5130. });
  5131. }
  5132. }
  5133. }
  5134. static create(a, b) {
  5135. return new ZodPipeline({
  5136. in: a,
  5137. out: b,
  5138. typeName: ZodFirstPartyTypeKind.ZodPipeline,
  5139. });
  5140. }
  5141. }
  5142. class ZodReadonly extends ZodType {
  5143. _parse(input) {
  5144. const result = this._def.innerType._parse(input);
  5145. const freeze = (data) => {
  5146. if (isValid(data)) {
  5147. data.value = Object.freeze(data.value);
  5148. }
  5149. return data;
  5150. };
  5151. return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  5152. }
  5153. unwrap() {
  5154. return this._def.innerType;
  5155. }
  5156. }
  5157. ZodReadonly.create = (type, params) => {
  5158. return new ZodReadonly({
  5159. innerType: type,
  5160. typeName: ZodFirstPartyTypeKind.ZodReadonly,
  5161. ...processCreateParams(params),
  5162. });
  5163. };
  5164. ////////////////////////////////////////
  5165. ////////////////////////////////////////
  5166. ////////// //////////
  5167. ////////// z.custom //////////
  5168. ////////// //////////
  5169. ////////////////////////////////////////
  5170. ////////////////////////////////////////
  5171. function cleanParams(params, data) {
  5172. const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  5173. const p2 = typeof p === "string" ? { message: p } : p;
  5174. return p2;
  5175. }
  5176. function custom(check, _params = {},
  5177. /**
  5178. * @deprecated
  5179. *
  5180. * Pass `fatal` into the params object instead:
  5181. *
  5182. * ```ts
  5183. * z.string().custom((val) => val.length > 5, { fatal: false })
  5184. * ```
  5185. *
  5186. */
  5187. fatal) {
  5188. if (check)
  5189. return ZodAny.create().superRefine((data, ctx) => {
  5190. const r = check(data);
  5191. if (r instanceof Promise) {
  5192. return r.then((r) => {
  5193. if (!r) {
  5194. const params = cleanParams(_params, data);
  5195. const _fatal = params.fatal ?? fatal ?? true;
  5196. ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
  5197. }
  5198. });
  5199. }
  5200. if (!r) {
  5201. const params = cleanParams(_params, data);
  5202. const _fatal = params.fatal ?? fatal ?? true;
  5203. ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
  5204. }
  5205. return;
  5206. });
  5207. return ZodAny.create();
  5208. }
  5209. var ZodFirstPartyTypeKind;
  5210. (function (ZodFirstPartyTypeKind) {
  5211. ZodFirstPartyTypeKind["ZodString"] = "ZodString";
  5212. ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
  5213. ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
  5214. ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
  5215. ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
  5216. ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
  5217. ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
  5218. ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
  5219. ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
  5220. ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
  5221. ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
  5222. ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
  5223. ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
  5224. ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
  5225. ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
  5226. ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
  5227. ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  5228. ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
  5229. ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
  5230. ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
  5231. ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
  5232. ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
  5233. ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
  5234. ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
  5235. ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
  5236. ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
  5237. ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
  5238. ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
  5239. ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
  5240. ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
  5241. ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
  5242. ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
  5243. ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
  5244. ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
  5245. ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
  5246. ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
  5247. })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
  5248. ZodAny.create;
  5249. ZodNever.create;
  5250. ZodArray.create;
  5251. ZodUnion.create;
  5252. ZodIntersection.create;
  5253. ZodTuple.create;
  5254. const enumType = ZodEnum.create;
  5255. ZodPromise.create;
  5256. ZodOptional.create;
  5257. ZodNullable.create;
  5258. const ALGORITHMS = {
  5259. "SHA-256": "sha256-",
  5260. "SHA-384": "sha384-",
  5261. "SHA-512": "sha512-"
  5262. };
  5263. const ALGORITHM_VALUES = Object.values(ALGORITHMS);
  5264. enumType(Object.keys(ALGORITHMS)).optional().default("SHA-256");
  5265. custom((value) => {
  5266. if (typeof value !== "string") {
  5267. return false;
  5268. }
  5269. return ALGORITHM_VALUES.some((allowedValue) => {
  5270. return value.startsWith(allowedValue);
  5271. });
  5272. });
  5273. const ALLOWED_DIRECTIVES = [
  5274. "base-uri",
  5275. "child-src",
  5276. "connect-src",
  5277. "default-src",
  5278. "fenced-frame-src",
  5279. "font-src",
  5280. "form-action",
  5281. "frame-ancestors",
  5282. "frame-src",
  5283. "img-src",
  5284. "manifest-src",
  5285. "media-src",
  5286. "object-src",
  5287. "referrer",
  5288. "report-to",
  5289. "report-uri",
  5290. "require-trusted-types-for",
  5291. "sandbox",
  5292. "trusted-types",
  5293. "upgrade-insecure-requests",
  5294. "worker-src"
  5295. ];
  5296. custom((value) => {
  5297. if (typeof value !== "string") {
  5298. return false;
  5299. }
  5300. return ALLOWED_DIRECTIVES.some((allowedValue) => {
  5301. return value.startsWith(allowedValue);
  5302. });
  5303. });
  5304. const ALGORITHM = "AES-GCM";
  5305. async function decodeKey(encoded) {
  5306. const bytes = decodeBase64(encoded);
  5307. return crypto.subtle.importKey("raw", bytes.buffer, ALGORITHM, true, [
  5308. "encrypt",
  5309. "decrypt"
  5310. ]);
  5311. }
  5312. const encoder$1 = new TextEncoder();
  5313. const decoder$1 = new TextDecoder();
  5314. const IV_LENGTH = 24;
  5315. async function encryptString(key, raw) {
  5316. const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH / 2));
  5317. const data = encoder$1.encode(raw);
  5318. const buffer = await crypto.subtle.encrypt(
  5319. {
  5320. name: ALGORITHM,
  5321. iv
  5322. },
  5323. key,
  5324. data
  5325. );
  5326. return encodeHexUpperCase(iv) + encodeBase64(new Uint8Array(buffer));
  5327. }
  5328. async function decryptString(key, encoded) {
  5329. const iv = decodeHex(encoded.slice(0, IV_LENGTH));
  5330. const dataArray = decodeBase64(encoded.slice(IV_LENGTH));
  5331. const decryptedBuffer = await crypto.subtle.decrypt(
  5332. {
  5333. name: ALGORITHM,
  5334. iv
  5335. },
  5336. key,
  5337. dataArray
  5338. );
  5339. const decryptedString = decoder$1.decode(decryptedBuffer);
  5340. return decryptedString;
  5341. }
  5342. async function generateCspDigest(data, algorithm) {
  5343. const hashBuffer = await crypto.subtle.digest(algorithm, encoder$1.encode(data));
  5344. const hash = encodeBase64(new Uint8Array(hashBuffer));
  5345. return `${ALGORITHMS[algorithm]}${hash}`;
  5346. }
  5347. const renderTemplateResultSym = Symbol.for("astro.renderTemplateResult");
  5348. class RenderTemplateResult {
  5349. [renderTemplateResultSym] = true;
  5350. htmlParts;
  5351. expressions;
  5352. error;
  5353. constructor(htmlParts, expressions) {
  5354. this.htmlParts = htmlParts;
  5355. this.error = void 0;
  5356. this.expressions = expressions.map((expression) => {
  5357. if (isPromise(expression)) {
  5358. return Promise.resolve(expression).catch((err) => {
  5359. if (!this.error) {
  5360. this.error = err;
  5361. throw err;
  5362. }
  5363. });
  5364. }
  5365. return expression;
  5366. });
  5367. }
  5368. render(destination) {
  5369. const flushers = this.expressions.map((exp) => {
  5370. return createBufferedRenderer(destination, (bufferDestination) => {
  5371. if (exp || exp === 0) {
  5372. return renderChild(bufferDestination, exp);
  5373. }
  5374. });
  5375. });
  5376. let i = 0;
  5377. const iterate = () => {
  5378. while (i < this.htmlParts.length) {
  5379. const html = this.htmlParts[i];
  5380. const flusher = flushers[i];
  5381. i++;
  5382. if (html) {
  5383. destination.write(markHTMLString(html));
  5384. }
  5385. if (flusher) {
  5386. const result = flusher.flush();
  5387. if (isPromise(result)) {
  5388. return result.then(iterate);
  5389. }
  5390. }
  5391. }
  5392. };
  5393. return iterate();
  5394. }
  5395. }
  5396. function isRenderTemplateResult(obj) {
  5397. return typeof obj === "object" && obj !== null && !!obj[renderTemplateResultSym];
  5398. }
  5399. function renderTemplate(htmlParts, ...expressions) {
  5400. return new RenderTemplateResult(htmlParts, expressions);
  5401. }
  5402. const slotString = Symbol.for("astro:slot-string");
  5403. class SlotString extends HTMLString {
  5404. instructions;
  5405. [slotString];
  5406. constructor(content, instructions) {
  5407. super(content);
  5408. this.instructions = instructions;
  5409. this[slotString] = true;
  5410. }
  5411. }
  5412. function isSlotString(str) {
  5413. return !!str[slotString];
  5414. }
  5415. function renderSlot(result, slotted, fallback) {
  5416. if (!slotted && fallback) {
  5417. return renderSlot(result, fallback);
  5418. }
  5419. return {
  5420. async render(destination) {
  5421. await renderChild(destination, typeof slotted === "function" ? slotted(result) : slotted);
  5422. }
  5423. };
  5424. }
  5425. async function renderSlotToString(result, slotted, fallback) {
  5426. let content = "";
  5427. let instructions = null;
  5428. const temporaryDestination = {
  5429. write(chunk) {
  5430. if (chunk instanceof SlotString) {
  5431. content += chunk;
  5432. if (chunk.instructions) {
  5433. instructions ??= [];
  5434. instructions.push(...chunk.instructions);
  5435. }
  5436. } else if (chunk instanceof Response) return;
  5437. else if (typeof chunk === "object" && "type" in chunk && typeof chunk.type === "string") {
  5438. if (instructions === null) {
  5439. instructions = [];
  5440. }
  5441. instructions.push(chunk);
  5442. } else {
  5443. content += chunkToString(result, chunk);
  5444. }
  5445. }
  5446. };
  5447. const renderInstance = renderSlot(result, slotted, fallback);
  5448. await renderInstance.render(temporaryDestination);
  5449. return markHTMLString(new SlotString(content, instructions));
  5450. }
  5451. async function renderSlots(result, slots = {}) {
  5452. let slotInstructions = null;
  5453. let children = {};
  5454. if (slots) {
  5455. await Promise.all(
  5456. Object.entries(slots).map(
  5457. ([key, value]) => renderSlotToString(result, value).then((output) => {
  5458. if (output.instructions) {
  5459. if (slotInstructions === null) {
  5460. slotInstructions = [];
  5461. }
  5462. slotInstructions.push(...output.instructions);
  5463. }
  5464. children[key] = output;
  5465. })
  5466. )
  5467. );
  5468. }
  5469. return { slotInstructions, children };
  5470. }
  5471. function createSlotValueFromString(content) {
  5472. return function() {
  5473. return renderTemplate`${unescapeHTML(content)}`;
  5474. };
  5475. }
  5476. const internalProps = /* @__PURE__ */ new Set([
  5477. "server:component-path",
  5478. "server:component-export",
  5479. "server:component-directive",
  5480. "server:defer"
  5481. ]);
  5482. function containsServerDirective(props) {
  5483. return "server:component-directive" in props;
  5484. }
  5485. const SCRIPT_RE = /<\/script/giu;
  5486. const COMMENT_RE = /<!--/gu;
  5487. const SCRIPT_REPLACER = "<\\/script";
  5488. const COMMENT_REPLACER = "\\u003C!--";
  5489. function safeJsonStringify(obj) {
  5490. return JSON.stringify(obj).replace(SCRIPT_RE, SCRIPT_REPLACER).replace(COMMENT_RE, COMMENT_REPLACER);
  5491. }
  5492. function createSearchParams(componentExport, encryptedProps, slots) {
  5493. const params = new URLSearchParams();
  5494. params.set("e", componentExport);
  5495. params.set("p", encryptedProps);
  5496. params.set("s", slots);
  5497. return params;
  5498. }
  5499. function isWithinURLLimit(pathname, params) {
  5500. const url = pathname + "?" + params.toString();
  5501. const chars = url.length;
  5502. return chars < 2048;
  5503. }
  5504. class ServerIslandComponent {
  5505. result;
  5506. props;
  5507. slots;
  5508. displayName;
  5509. hostId;
  5510. islandContent;
  5511. componentPath;
  5512. componentExport;
  5513. componentId;
  5514. constructor(result, props, slots, displayName) {
  5515. this.result = result;
  5516. this.props = props;
  5517. this.slots = slots;
  5518. this.displayName = displayName;
  5519. }
  5520. async init() {
  5521. const content = await this.getIslandContent();
  5522. if (this.result.cspDestination) {
  5523. this.result._metadata.extraScriptHashes.push(
  5524. await generateCspDigest(SERVER_ISLAND_REPLACER, this.result.cspAlgorithm)
  5525. );
  5526. const contentDigest = await generateCspDigest(content, this.result.cspAlgorithm);
  5527. this.result._metadata.extraScriptHashes.push(contentDigest);
  5528. }
  5529. return createThinHead();
  5530. }
  5531. async render(destination) {
  5532. const hostId = await this.getHostId();
  5533. const islandContent = await this.getIslandContent();
  5534. destination.write(createRenderInstruction({ type: "server-island-runtime" }));
  5535. destination.write("<!--[if astro]>server-island-start<![endif]-->");
  5536. for (const name in this.slots) {
  5537. if (name === "fallback") {
  5538. await renderChild(destination, this.slots.fallback(this.result));
  5539. }
  5540. }
  5541. destination.write(
  5542. `<script type="module" data-astro-rerun data-island-id="${hostId}">${islandContent}</script>`
  5543. );
  5544. }
  5545. getComponentPath() {
  5546. if (this.componentPath) {
  5547. return this.componentPath;
  5548. }
  5549. const componentPath = this.props["server:component-path"];
  5550. if (!componentPath) {
  5551. throw new Error(`Could not find server component path`);
  5552. }
  5553. this.componentPath = componentPath;
  5554. return componentPath;
  5555. }
  5556. getComponentExport() {
  5557. if (this.componentExport) {
  5558. return this.componentExport;
  5559. }
  5560. const componentExport = this.props["server:component-export"];
  5561. if (!componentExport) {
  5562. throw new Error(`Could not find server component export`);
  5563. }
  5564. this.componentExport = componentExport;
  5565. return componentExport;
  5566. }
  5567. async getHostId() {
  5568. if (!this.hostId) {
  5569. this.hostId = await crypto.randomUUID();
  5570. }
  5571. return this.hostId;
  5572. }
  5573. async getIslandContent() {
  5574. if (this.islandContent) {
  5575. return this.islandContent;
  5576. }
  5577. const componentPath = this.getComponentPath();
  5578. const componentExport = this.getComponentExport();
  5579. const componentId = this.result.serverIslandNameMap.get(componentPath);
  5580. if (!componentId) {
  5581. throw new Error(`Could not find server component name`);
  5582. }
  5583. for (const key2 of Object.keys(this.props)) {
  5584. if (internalProps.has(key2)) {
  5585. delete this.props[key2];
  5586. }
  5587. }
  5588. const renderedSlots = {};
  5589. for (const name in this.slots) {
  5590. if (name !== "fallback") {
  5591. const content = await renderSlotToString(this.result, this.slots[name]);
  5592. renderedSlots[name] = content.toString();
  5593. }
  5594. }
  5595. const key = await this.result.key;
  5596. const propsEncrypted = Object.keys(this.props).length === 0 ? "" : await encryptString(key, JSON.stringify(this.props));
  5597. const hostId = await this.getHostId();
  5598. const slash = this.result.base.endsWith("/") ? "" : "/";
  5599. let serverIslandUrl = `${this.result.base}${slash}_server-islands/${componentId}${this.result.trailingSlash === "always" ? "/" : ""}`;
  5600. const potentialSearchParams = createSearchParams(
  5601. componentExport,
  5602. propsEncrypted,
  5603. safeJsonStringify(renderedSlots)
  5604. );
  5605. const useGETRequest = isWithinURLLimit(serverIslandUrl, potentialSearchParams);
  5606. if (useGETRequest) {
  5607. serverIslandUrl += "?" + potentialSearchParams.toString();
  5608. this.result._metadata.extraHead.push(
  5609. markHTMLString(
  5610. `<link rel="preload" as="fetch" href="${serverIslandUrl}" crossorigin="anonymous">`
  5611. )
  5612. );
  5613. }
  5614. const method = useGETRequest ? (
  5615. // GET request
  5616. `let response = await fetch('${serverIslandUrl}');`
  5617. ) : (
  5618. // POST request
  5619. `let data = {
  5620. componentExport: ${safeJsonStringify(componentExport)},
  5621. encryptedProps: ${safeJsonStringify(propsEncrypted)},
  5622. slots: ${safeJsonStringify(renderedSlots)},
  5623. };
  5624. let response = await fetch('${serverIslandUrl}', {
  5625. method: 'POST',
  5626. body: JSON.stringify(data),
  5627. });`
  5628. );
  5629. this.islandContent = `${method}replaceServerIsland('${hostId}', response);`;
  5630. return this.islandContent;
  5631. }
  5632. }
  5633. const renderServerIslandRuntime = () => {
  5634. return `<script>${SERVER_ISLAND_REPLACER}</script>`;
  5635. };
  5636. const SERVER_ISLAND_REPLACER = markHTMLString(
  5637. `async function replaceServerIsland(id, r) {
  5638. let s = document.querySelector(\`script[data-island-id="\${id}"]\`);
  5639. // If there's no matching script, or the request fails then return
  5640. if (!s || r.status !== 200 || r.headers.get('content-type')?.split(';')[0].trim() !== 'text/html') return;
  5641. // Load the HTML before modifying the DOM in case of errors
  5642. let html = await r.text();
  5643. // Remove any placeholder content before the island script
  5644. while (s.previousSibling && s.previousSibling.nodeType !== 8 && s.previousSibling.data !== '[if astro]>server-island-start<![endif]')
  5645. s.previousSibling.remove();
  5646. s.previousSibling?.remove();
  5647. // Insert the new HTML
  5648. s.before(document.createRange().createContextualFragment(html));
  5649. // Remove the script. Prior to v5.4.2, this was the trick to force rerun of scripts. Keeping it to minimize change to the existing behavior.
  5650. s.remove();
  5651. }`.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("//")).join(" ")
  5652. );
  5653. const Fragment = Symbol.for("astro:fragment");
  5654. const Renderer = Symbol.for("astro:renderer");
  5655. const encoder = new TextEncoder();
  5656. const decoder = new TextDecoder();
  5657. function stringifyChunk(result, chunk) {
  5658. if (isRenderInstruction(chunk)) {
  5659. const instruction = chunk;
  5660. switch (instruction.type) {
  5661. case "directive": {
  5662. const { hydration } = instruction;
  5663. let needsHydrationScript = hydration && determineIfNeedsHydrationScript(result);
  5664. let needsDirectiveScript = hydration && determinesIfNeedsDirectiveScript(result, hydration.directive);
  5665. if (needsHydrationScript) {
  5666. let prescripts = getPrescripts(result, "both", hydration.directive);
  5667. return markHTMLString(prescripts);
  5668. } else if (needsDirectiveScript) {
  5669. let prescripts = getPrescripts(result, "directive", hydration.directive);
  5670. return markHTMLString(prescripts);
  5671. } else {
  5672. return "";
  5673. }
  5674. }
  5675. case "head": {
  5676. if (result._metadata.hasRenderedHead || result.partial) {
  5677. return "";
  5678. }
  5679. return renderAllHeadContent(result);
  5680. }
  5681. case "maybe-head": {
  5682. if (result._metadata.hasRenderedHead || result._metadata.headInTree || result.partial) {
  5683. return "";
  5684. }
  5685. return renderAllHeadContent(result);
  5686. }
  5687. case "renderer-hydration-script": {
  5688. const { rendererSpecificHydrationScripts } = result._metadata;
  5689. const { rendererName } = instruction;
  5690. if (!rendererSpecificHydrationScripts.has(rendererName)) {
  5691. rendererSpecificHydrationScripts.add(rendererName);
  5692. return instruction.render();
  5693. }
  5694. return "";
  5695. }
  5696. case "server-island-runtime": {
  5697. if (result._metadata.hasRenderedServerIslandRuntime) {
  5698. return "";
  5699. }
  5700. result._metadata.hasRenderedServerIslandRuntime = true;
  5701. return renderServerIslandRuntime();
  5702. }
  5703. default: {
  5704. throw new Error(`Unknown chunk type: ${chunk.type}`);
  5705. }
  5706. }
  5707. } else if (chunk instanceof Response) {
  5708. return "";
  5709. } else if (isSlotString(chunk)) {
  5710. let out = "";
  5711. const c = chunk;
  5712. if (c.instructions) {
  5713. for (const instr of c.instructions) {
  5714. out += stringifyChunk(result, instr);
  5715. }
  5716. }
  5717. out += chunk.toString();
  5718. return out;
  5719. }
  5720. return chunk.toString();
  5721. }
  5722. function chunkToString(result, chunk) {
  5723. if (ArrayBuffer.isView(chunk)) {
  5724. return decoder.decode(chunk);
  5725. } else {
  5726. return stringifyChunk(result, chunk);
  5727. }
  5728. }
  5729. function chunkToByteArray(result, chunk) {
  5730. if (ArrayBuffer.isView(chunk)) {
  5731. return chunk;
  5732. } else {
  5733. const stringified = stringifyChunk(result, chunk);
  5734. return encoder.encode(stringified.toString());
  5735. }
  5736. }
  5737. function isRenderInstance(obj) {
  5738. return !!obj && typeof obj === "object" && "render" in obj && typeof obj.render === "function";
  5739. }
  5740. function renderChild(destination, child) {
  5741. if (isPromise(child)) {
  5742. return child.then((x) => renderChild(destination, x));
  5743. }
  5744. if (child instanceof SlotString) {
  5745. destination.write(child);
  5746. return;
  5747. }
  5748. if (isHTMLString(child)) {
  5749. destination.write(child);
  5750. return;
  5751. }
  5752. if (Array.isArray(child)) {
  5753. return renderArray(destination, child);
  5754. }
  5755. if (typeof child === "function") {
  5756. return renderChild(destination, child());
  5757. }
  5758. if (!child && child !== 0) {
  5759. return;
  5760. }
  5761. if (typeof child === "string") {
  5762. destination.write(markHTMLString(escapeHTML(child)));
  5763. return;
  5764. }
  5765. if (isRenderInstance(child)) {
  5766. return child.render(destination);
  5767. }
  5768. if (isRenderTemplateResult(child)) {
  5769. return child.render(destination);
  5770. }
  5771. if (isAstroComponentInstance(child)) {
  5772. return child.render(destination);
  5773. }
  5774. if (ArrayBuffer.isView(child)) {
  5775. destination.write(child);
  5776. return;
  5777. }
  5778. if (typeof child === "object" && (Symbol.asyncIterator in child || Symbol.iterator in child)) {
  5779. if (Symbol.asyncIterator in child) {
  5780. return renderAsyncIterable(destination, child);
  5781. }
  5782. return renderIterable(destination, child);
  5783. }
  5784. destination.write(child);
  5785. }
  5786. function renderArray(destination, children) {
  5787. const flushers = children.map((c) => {
  5788. return createBufferedRenderer(destination, (bufferDestination) => {
  5789. return renderChild(bufferDestination, c);
  5790. });
  5791. });
  5792. const iterator = flushers[Symbol.iterator]();
  5793. const iterate = () => {
  5794. for (; ; ) {
  5795. const { value: flusher, done } = iterator.next();
  5796. if (done) {
  5797. break;
  5798. }
  5799. const result = flusher.flush();
  5800. if (isPromise(result)) {
  5801. return result.then(iterate);
  5802. }
  5803. }
  5804. };
  5805. return iterate();
  5806. }
  5807. function renderIterable(destination, children) {
  5808. const iterator = children[Symbol.iterator]();
  5809. const iterate = () => {
  5810. for (; ; ) {
  5811. const { value, done } = iterator.next();
  5812. if (done) {
  5813. break;
  5814. }
  5815. const result = renderChild(destination, value);
  5816. if (isPromise(result)) {
  5817. return result.then(iterate);
  5818. }
  5819. }
  5820. };
  5821. return iterate();
  5822. }
  5823. async function renderAsyncIterable(destination, children) {
  5824. for await (const value of children) {
  5825. await renderChild(destination, value);
  5826. }
  5827. }
  5828. const astroComponentInstanceSym = Symbol.for("astro.componentInstance");
  5829. class AstroComponentInstance {
  5830. [astroComponentInstanceSym] = true;
  5831. result;
  5832. props;
  5833. slotValues;
  5834. factory;
  5835. returnValue;
  5836. constructor(result, props, slots, factory) {
  5837. this.result = result;
  5838. this.props = props;
  5839. this.factory = factory;
  5840. this.slotValues = {};
  5841. for (const name in slots) {
  5842. let didRender = false;
  5843. let value = slots[name](result);
  5844. this.slotValues[name] = () => {
  5845. if (!didRender) {
  5846. didRender = true;
  5847. return value;
  5848. }
  5849. return slots[name](result);
  5850. };
  5851. }
  5852. }
  5853. init(result) {
  5854. if (this.returnValue !== void 0) {
  5855. return this.returnValue;
  5856. }
  5857. this.returnValue = this.factory(result, this.props, this.slotValues);
  5858. if (isPromise(this.returnValue)) {
  5859. this.returnValue.then((resolved) => {
  5860. this.returnValue = resolved;
  5861. }).catch(() => {
  5862. });
  5863. }
  5864. return this.returnValue;
  5865. }
  5866. render(destination) {
  5867. const returnValue = this.init(this.result);
  5868. if (isPromise(returnValue)) {
  5869. return returnValue.then((x) => this.renderImpl(destination, x));
  5870. }
  5871. return this.renderImpl(destination, returnValue);
  5872. }
  5873. renderImpl(destination, returnValue) {
  5874. if (isHeadAndContent(returnValue)) {
  5875. return returnValue.content.render(destination);
  5876. } else {
  5877. return renderChild(destination, returnValue);
  5878. }
  5879. }
  5880. }
  5881. function validateComponentProps(props, clientDirectives, displayName) {
  5882. if (props != null) {
  5883. const directives = [...clientDirectives.keys()].map((directive) => `client:${directive}`);
  5884. for (const prop of Object.keys(props)) {
  5885. if (directives.includes(prop)) {
  5886. console.warn(
  5887. `You are attempting to render <${displayName} ${prop} />, but ${displayName} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.`
  5888. );
  5889. }
  5890. }
  5891. }
  5892. }
  5893. function createAstroComponentInstance(result, displayName, factory, props, slots = {}) {
  5894. validateComponentProps(props, result.clientDirectives, displayName);
  5895. const instance = new AstroComponentInstance(result, props, slots, factory);
  5896. if (isAPropagatingComponent(result, factory)) {
  5897. result._metadata.propagators.add(instance);
  5898. }
  5899. return instance;
  5900. }
  5901. function isAstroComponentInstance(obj) {
  5902. return typeof obj === "object" && obj !== null && !!obj[astroComponentInstanceSym];
  5903. }
  5904. const DOCTYPE_EXP = /<!doctype html/i;
  5905. async function renderToString(result, componentFactory, props, children, isPage = false, route) {
  5906. const templateResult = await callComponentAsTemplateResultOrResponse(
  5907. result,
  5908. componentFactory,
  5909. props,
  5910. children,
  5911. route
  5912. );
  5913. if (templateResult instanceof Response) return templateResult;
  5914. let str = "";
  5915. let renderedFirstPageChunk = false;
  5916. if (isPage) {
  5917. await bufferHeadContent(result);
  5918. }
  5919. const destination = {
  5920. write(chunk) {
  5921. if (isPage && !renderedFirstPageChunk) {
  5922. renderedFirstPageChunk = true;
  5923. if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) {
  5924. const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
  5925. str += doctype;
  5926. }
  5927. }
  5928. if (chunk instanceof Response) return;
  5929. str += chunkToString(result, chunk);
  5930. }
  5931. };
  5932. await templateResult.render(destination);
  5933. return str;
  5934. }
  5935. async function renderToReadableStream(result, componentFactory, props, children, isPage = false, route) {
  5936. const templateResult = await callComponentAsTemplateResultOrResponse(
  5937. result,
  5938. componentFactory,
  5939. props,
  5940. children,
  5941. route
  5942. );
  5943. if (templateResult instanceof Response) return templateResult;
  5944. let renderedFirstPageChunk = false;
  5945. if (isPage) {
  5946. await bufferHeadContent(result);
  5947. }
  5948. return new ReadableStream({
  5949. start(controller) {
  5950. const destination = {
  5951. write(chunk) {
  5952. if (isPage && !renderedFirstPageChunk) {
  5953. renderedFirstPageChunk = true;
  5954. if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) {
  5955. const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
  5956. controller.enqueue(encoder.encode(doctype));
  5957. }
  5958. }
  5959. if (chunk instanceof Response) {
  5960. throw new AstroError({
  5961. ...ResponseSentError
  5962. });
  5963. }
  5964. const bytes = chunkToByteArray(result, chunk);
  5965. controller.enqueue(bytes);
  5966. }
  5967. };
  5968. (async () => {
  5969. try {
  5970. await templateResult.render(destination);
  5971. controller.close();
  5972. } catch (e) {
  5973. if (AstroError.is(e) && !e.loc) {
  5974. e.setLocation({
  5975. file: route?.component
  5976. });
  5977. }
  5978. setTimeout(() => controller.error(e), 0);
  5979. }
  5980. })();
  5981. },
  5982. cancel() {
  5983. result.cancelled = true;
  5984. }
  5985. });
  5986. }
  5987. async function callComponentAsTemplateResultOrResponse(result, componentFactory, props, children, route) {
  5988. const factoryResult = await componentFactory(result, props, children);
  5989. if (factoryResult instanceof Response) {
  5990. return factoryResult;
  5991. } else if (isHeadAndContent(factoryResult)) {
  5992. if (!isRenderTemplateResult(factoryResult.content)) {
  5993. throw new AstroError({
  5994. ...OnlyResponseCanBeReturned,
  5995. message: OnlyResponseCanBeReturned.message(
  5996. route?.route,
  5997. typeof factoryResult
  5998. ),
  5999. location: {
  6000. file: route?.component
  6001. }
  6002. });
  6003. }
  6004. return factoryResult.content;
  6005. } else if (!isRenderTemplateResult(factoryResult)) {
  6006. throw new AstroError({
  6007. ...OnlyResponseCanBeReturned,
  6008. message: OnlyResponseCanBeReturned.message(route?.route, typeof factoryResult),
  6009. location: {
  6010. file: route?.component
  6011. }
  6012. });
  6013. }
  6014. return factoryResult;
  6015. }
  6016. async function bufferHeadContent(result) {
  6017. const iterator = result._metadata.propagators.values();
  6018. while (true) {
  6019. const { value, done } = iterator.next();
  6020. if (done) {
  6021. break;
  6022. }
  6023. const returnValue = await value.init(result);
  6024. if (isHeadAndContent(returnValue) && returnValue.head) {
  6025. result._metadata.extraHead.push(returnValue.head);
  6026. }
  6027. }
  6028. }
  6029. async function renderToAsyncIterable(result, componentFactory, props, children, isPage = false, route) {
  6030. const templateResult = await callComponentAsTemplateResultOrResponse(
  6031. result,
  6032. componentFactory,
  6033. props,
  6034. children,
  6035. route
  6036. );
  6037. if (templateResult instanceof Response) return templateResult;
  6038. let renderedFirstPageChunk = false;
  6039. if (isPage) {
  6040. await bufferHeadContent(result);
  6041. }
  6042. let error = null;
  6043. let next = null;
  6044. const buffer = [];
  6045. let renderingComplete = false;
  6046. const iterator = {
  6047. async next() {
  6048. if (result.cancelled) return { done: true, value: void 0 };
  6049. if (next !== null) {
  6050. await next.promise;
  6051. } else if (!renderingComplete && !buffer.length) {
  6052. next = promiseWithResolvers();
  6053. await next.promise;
  6054. }
  6055. if (!renderingComplete) {
  6056. next = promiseWithResolvers();
  6057. }
  6058. if (error) {
  6059. throw error;
  6060. }
  6061. let length = 0;
  6062. for (let i = 0, len = buffer.length; i < len; i++) {
  6063. length += buffer[i].length;
  6064. }
  6065. let mergedArray = new Uint8Array(length);
  6066. let offset = 0;
  6067. for (let i = 0, len = buffer.length; i < len; i++) {
  6068. const item = buffer[i];
  6069. mergedArray.set(item, offset);
  6070. offset += item.length;
  6071. }
  6072. buffer.length = 0;
  6073. const returnValue = {
  6074. // The iterator is done when rendering has finished
  6075. // and there are no more chunks to return.
  6076. done: length === 0 && renderingComplete,
  6077. value: mergedArray
  6078. };
  6079. return returnValue;
  6080. },
  6081. async return() {
  6082. result.cancelled = true;
  6083. return { done: true, value: void 0 };
  6084. }
  6085. };
  6086. const destination = {
  6087. write(chunk) {
  6088. if (isPage && !renderedFirstPageChunk) {
  6089. renderedFirstPageChunk = true;
  6090. if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) {
  6091. const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
  6092. buffer.push(encoder.encode(doctype));
  6093. }
  6094. }
  6095. if (chunk instanceof Response) {
  6096. throw new AstroError(ResponseSentError);
  6097. }
  6098. const bytes = chunkToByteArray(result, chunk);
  6099. if (bytes.length > 0) {
  6100. buffer.push(bytes);
  6101. next?.resolve();
  6102. } else if (buffer.length > 0) {
  6103. next?.resolve();
  6104. }
  6105. }
  6106. };
  6107. const renderResult = toPromise(() => templateResult.render(destination));
  6108. renderResult.catch((err) => {
  6109. error = err;
  6110. }).finally(() => {
  6111. renderingComplete = true;
  6112. next?.resolve();
  6113. });
  6114. return {
  6115. [Symbol.asyncIterator]() {
  6116. return iterator;
  6117. }
  6118. };
  6119. }
  6120. function toPromise(fn) {
  6121. try {
  6122. const result = fn();
  6123. return isPromise(result) ? result : Promise.resolve(result);
  6124. } catch (err) {
  6125. return Promise.reject(err);
  6126. }
  6127. }
  6128. function componentIsHTMLElement(Component) {
  6129. return typeof HTMLElement !== "undefined" && HTMLElement.isPrototypeOf(Component);
  6130. }
  6131. async function renderHTMLElement(result, constructor, props, slots) {
  6132. const name = getHTMLElementName(constructor);
  6133. let attrHTML = "";
  6134. for (const attr in props) {
  6135. attrHTML += ` ${attr}="${toAttributeString(await props[attr])}"`;
  6136. }
  6137. return markHTMLString(
  6138. `<${name}${attrHTML}>${await renderSlotToString(result, slots?.default)}</${name}>`
  6139. );
  6140. }
  6141. function getHTMLElementName(constructor) {
  6142. const definedName = customElements.getName(constructor);
  6143. if (definedName) return definedName;
  6144. const assignedName = constructor.name.replace(/^HTML|Element$/g, "").replace(/[A-Z]/g, "-$&").toLowerCase().replace(/^-/, "html-");
  6145. return assignedName;
  6146. }
  6147. const needsHeadRenderingSymbol = Symbol.for("astro.needsHeadRendering");
  6148. const rendererAliases = /* @__PURE__ */ new Map([["solid", "solid-js"]]);
  6149. const clientOnlyValues = /* @__PURE__ */ new Set(["solid-js", "react", "preact", "vue", "svelte"]);
  6150. function guessRenderers(componentUrl) {
  6151. const extname = componentUrl?.split(".").pop();
  6152. switch (extname) {
  6153. case "svelte":
  6154. return ["@astrojs/svelte"];
  6155. case "vue":
  6156. return ["@astrojs/vue"];
  6157. case "jsx":
  6158. case "tsx":
  6159. return ["@astrojs/react", "@astrojs/preact", "@astrojs/solid-js", "@astrojs/vue (jsx)"];
  6160. case void 0:
  6161. default:
  6162. return [
  6163. "@astrojs/react",
  6164. "@astrojs/preact",
  6165. "@astrojs/solid-js",
  6166. "@astrojs/vue",
  6167. "@astrojs/svelte"
  6168. ];
  6169. }
  6170. }
  6171. function isFragmentComponent(Component) {
  6172. return Component === Fragment;
  6173. }
  6174. function isHTMLComponent(Component) {
  6175. return Component && Component["astro:html"] === true;
  6176. }
  6177. const ASTRO_SLOT_EXP = /<\/?astro-slot\b[^>]*>/g;
  6178. const ASTRO_STATIC_SLOT_EXP = /<\/?astro-static-slot\b[^>]*>/g;
  6179. function removeStaticAstroSlot(html, supportsAstroStaticSlot = true) {
  6180. const exp = supportsAstroStaticSlot ? ASTRO_STATIC_SLOT_EXP : ASTRO_SLOT_EXP;
  6181. return html.replace(exp, "");
  6182. }
  6183. async function renderFrameworkComponent(result, displayName, Component, _props, slots = {}) {
  6184. if (!Component && "client:only" in _props === false) {
  6185. throw new Error(
  6186. `Unable to render ${displayName} because it is ${Component}!
  6187. Did you forget to import the component or is it possible there is a typo?`
  6188. );
  6189. }
  6190. const { renderers, clientDirectives } = result;
  6191. const metadata = {
  6192. astroStaticSlot: true,
  6193. displayName
  6194. };
  6195. const { hydration, isPage, props, propsWithoutTransitionAttributes } = extractDirectives(
  6196. _props,
  6197. clientDirectives
  6198. );
  6199. let html = "";
  6200. let attrs = void 0;
  6201. if (hydration) {
  6202. metadata.hydrate = hydration.directive;
  6203. metadata.hydrateArgs = hydration.value;
  6204. metadata.componentExport = hydration.componentExport;
  6205. metadata.componentUrl = hydration.componentUrl;
  6206. }
  6207. const probableRendererNames = guessRenderers(metadata.componentUrl);
  6208. const validRenderers = renderers.filter((r) => r.name !== "astro:jsx");
  6209. const { children, slotInstructions } = await renderSlots(result, slots);
  6210. let renderer;
  6211. if (metadata.hydrate !== "only") {
  6212. let isTagged = false;
  6213. try {
  6214. isTagged = Component && Component[Renderer];
  6215. } catch {
  6216. }
  6217. if (isTagged) {
  6218. const rendererName = Component[Renderer];
  6219. renderer = renderers.find(({ name }) => name === rendererName);
  6220. }
  6221. if (!renderer) {
  6222. let error;
  6223. for (const r of renderers) {
  6224. try {
  6225. if (await r.ssr.check.call({ result }, Component, props, children)) {
  6226. renderer = r;
  6227. break;
  6228. }
  6229. } catch (e) {
  6230. error ??= e;
  6231. }
  6232. }
  6233. if (!renderer && error) {
  6234. throw error;
  6235. }
  6236. }
  6237. if (!renderer && typeof HTMLElement === "function" && componentIsHTMLElement(Component)) {
  6238. const output = await renderHTMLElement(
  6239. result,
  6240. Component,
  6241. _props,
  6242. slots
  6243. );
  6244. return {
  6245. render(destination) {
  6246. destination.write(output);
  6247. }
  6248. };
  6249. }
  6250. } else {
  6251. if (metadata.hydrateArgs) {
  6252. const rendererName = rendererAliases.has(metadata.hydrateArgs) ? rendererAliases.get(metadata.hydrateArgs) : metadata.hydrateArgs;
  6253. if (clientOnlyValues.has(rendererName)) {
  6254. renderer = renderers.find(
  6255. ({ name }) => name === `@astrojs/${rendererName}` || name === rendererName
  6256. );
  6257. }
  6258. }
  6259. if (!renderer && validRenderers.length === 1) {
  6260. renderer = validRenderers[0];
  6261. }
  6262. if (!renderer) {
  6263. const extname = metadata.componentUrl?.split(".").pop();
  6264. renderer = renderers.find(({ name }) => name === `@astrojs/${extname}` || name === extname);
  6265. }
  6266. }
  6267. if (!renderer) {
  6268. if (metadata.hydrate === "only") {
  6269. const rendererName = rendererAliases.has(metadata.hydrateArgs) ? rendererAliases.get(metadata.hydrateArgs) : metadata.hydrateArgs;
  6270. if (clientOnlyValues.has(rendererName)) {
  6271. const plural = validRenderers.length > 1;
  6272. throw new AstroError({
  6273. ...NoMatchingRenderer,
  6274. message: NoMatchingRenderer.message(
  6275. metadata.displayName,
  6276. metadata?.componentUrl?.split(".").pop(),
  6277. plural,
  6278. validRenderers.length
  6279. ),
  6280. hint: NoMatchingRenderer.hint(
  6281. formatList(probableRendererNames.map((r) => "`" + r + "`"))
  6282. )
  6283. });
  6284. } else {
  6285. throw new AstroError({
  6286. ...NoClientOnlyHint,
  6287. message: NoClientOnlyHint.message(metadata.displayName),
  6288. hint: NoClientOnlyHint.hint(
  6289. probableRendererNames.map((r) => r.replace("@astrojs/", "")).join("|")
  6290. )
  6291. });
  6292. }
  6293. } else if (typeof Component !== "string") {
  6294. const matchingRenderers = validRenderers.filter(
  6295. (r) => probableRendererNames.includes(r.name)
  6296. );
  6297. const plural = validRenderers.length > 1;
  6298. if (matchingRenderers.length === 0) {
  6299. throw new AstroError({
  6300. ...NoMatchingRenderer,
  6301. message: NoMatchingRenderer.message(
  6302. metadata.displayName,
  6303. metadata?.componentUrl?.split(".").pop(),
  6304. plural,
  6305. validRenderers.length
  6306. ),
  6307. hint: NoMatchingRenderer.hint(
  6308. formatList(probableRendererNames.map((r) => "`" + r + "`"))
  6309. )
  6310. });
  6311. } else if (matchingRenderers.length === 1) {
  6312. renderer = matchingRenderers[0];
  6313. ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
  6314. { result },
  6315. Component,
  6316. propsWithoutTransitionAttributes,
  6317. children,
  6318. metadata
  6319. ));
  6320. } else {
  6321. throw new Error(`Unable to render ${metadata.displayName}!
  6322. This component likely uses ${formatList(probableRendererNames)},
  6323. but Astro encountered an error during server-side rendering.
  6324. Please ensure that ${metadata.displayName}:
  6325. 1. Does not unconditionally access browser-specific globals like \`window\` or \`document\`.
  6326. If this is unavoidable, use the \`client:only\` hydration directive.
  6327. 2. Does not conditionally return \`null\` or \`undefined\` when rendered on the server.
  6328. If you're still stuck, please open an issue on GitHub or join us at https://astro.build/chat.`);
  6329. }
  6330. }
  6331. } else {
  6332. if (metadata.hydrate === "only") {
  6333. html = await renderSlotToString(result, slots?.fallback);
  6334. } else {
  6335. performance.now();
  6336. ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
  6337. { result },
  6338. Component,
  6339. propsWithoutTransitionAttributes,
  6340. children,
  6341. metadata
  6342. ));
  6343. }
  6344. }
  6345. if (!html && typeof Component === "string") {
  6346. const Tag = sanitizeElementName(Component);
  6347. const childSlots = Object.values(children).join("");
  6348. const renderTemplateResult = renderTemplate`<${Tag}${internalSpreadAttributes(
  6349. props,
  6350. true,
  6351. Tag
  6352. )}${markHTMLString(
  6353. childSlots === "" && voidElementNames.test(Tag) ? `/>` : `>${childSlots}</${Tag}>`
  6354. )}`;
  6355. html = "";
  6356. const destination = {
  6357. write(chunk) {
  6358. if (chunk instanceof Response) return;
  6359. html += chunkToString(result, chunk);
  6360. }
  6361. };
  6362. await renderTemplateResult.render(destination);
  6363. }
  6364. if (!hydration) {
  6365. return {
  6366. render(destination) {
  6367. if (slotInstructions) {
  6368. for (const instruction of slotInstructions) {
  6369. destination.write(instruction);
  6370. }
  6371. }
  6372. if (isPage || renderer?.name === "astro:jsx") {
  6373. destination.write(html);
  6374. } else if (html && html.length > 0) {
  6375. destination.write(
  6376. markHTMLString(removeStaticAstroSlot(html, renderer?.ssr?.supportsAstroStaticSlot))
  6377. );
  6378. }
  6379. }
  6380. };
  6381. }
  6382. const astroId = shorthash(
  6383. `<!--${metadata.componentExport.value}:${metadata.componentUrl}-->
  6384. ${html}
  6385. ${serializeProps(
  6386. props,
  6387. metadata
  6388. )}`
  6389. );
  6390. const island = await generateHydrateScript(
  6391. { renderer, result, astroId, props, attrs },
  6392. metadata
  6393. );
  6394. let unrenderedSlots = [];
  6395. if (html) {
  6396. if (Object.keys(children).length > 0) {
  6397. for (const key of Object.keys(children)) {
  6398. let tagName = renderer?.ssr?.supportsAstroStaticSlot ? !!metadata.hydrate ? "astro-slot" : "astro-static-slot" : "astro-slot";
  6399. let expectedHTML = key === "default" ? `<${tagName}>` : `<${tagName} name="${key}">`;
  6400. if (!html.includes(expectedHTML)) {
  6401. unrenderedSlots.push(key);
  6402. }
  6403. }
  6404. }
  6405. } else {
  6406. unrenderedSlots = Object.keys(children);
  6407. }
  6408. const template = unrenderedSlots.length > 0 ? unrenderedSlots.map(
  6409. (key) => `<template data-astro-template${key !== "default" ? `="${key}"` : ""}>${children[key]}</template>`
  6410. ).join("") : "";
  6411. island.children = `${html ?? ""}${template}`;
  6412. if (island.children) {
  6413. island.props["await-children"] = "";
  6414. island.children += `<!--astro:end-->`;
  6415. }
  6416. return {
  6417. render(destination) {
  6418. if (slotInstructions) {
  6419. for (const instruction of slotInstructions) {
  6420. destination.write(instruction);
  6421. }
  6422. }
  6423. destination.write(createRenderInstruction({ type: "directive", hydration }));
  6424. if (hydration.directive !== "only" && renderer?.ssr.renderHydrationScript) {
  6425. destination.write(
  6426. createRenderInstruction({
  6427. type: "renderer-hydration-script",
  6428. rendererName: renderer.name,
  6429. render: renderer.ssr.renderHydrationScript
  6430. })
  6431. );
  6432. }
  6433. const renderedElement = renderElement$1("astro-island", island, false);
  6434. destination.write(markHTMLString(renderedElement));
  6435. }
  6436. };
  6437. }
  6438. function sanitizeElementName(tag) {
  6439. const unsafe = /[&<>'"\s]+/;
  6440. if (!unsafe.test(tag)) return tag;
  6441. return tag.trim().split(unsafe)[0].trim();
  6442. }
  6443. async function renderFragmentComponent(result, slots = {}) {
  6444. const children = await renderSlotToString(result, slots?.default);
  6445. return {
  6446. render(destination) {
  6447. if (children == null) return;
  6448. destination.write(children);
  6449. }
  6450. };
  6451. }
  6452. async function renderHTMLComponent(result, Component, _props, slots = {}) {
  6453. const { slotInstructions, children } = await renderSlots(result, slots);
  6454. const html = Component({ slots: children });
  6455. const hydrationHtml = slotInstructions ? slotInstructions.map((instr) => chunkToString(result, instr)).join("") : "";
  6456. return {
  6457. render(destination) {
  6458. destination.write(markHTMLString(hydrationHtml + html));
  6459. }
  6460. };
  6461. }
  6462. function renderAstroComponent(result, displayName, Component, props, slots = {}) {
  6463. if (containsServerDirective(props)) {
  6464. const serverIslandComponent = new ServerIslandComponent(result, props, slots, displayName);
  6465. result._metadata.propagators.add(serverIslandComponent);
  6466. return serverIslandComponent;
  6467. }
  6468. const instance = createAstroComponentInstance(result, displayName, Component, props, slots);
  6469. return {
  6470. render(destination) {
  6471. return instance.render(destination);
  6472. }
  6473. };
  6474. }
  6475. function renderComponent(result, displayName, Component, props, slots = {}) {
  6476. if (isPromise(Component)) {
  6477. return Component.catch(handleCancellation).then((x) => {
  6478. return renderComponent(result, displayName, x, props, slots);
  6479. });
  6480. }
  6481. if (isFragmentComponent(Component)) {
  6482. return renderFragmentComponent(result, slots).catch(handleCancellation);
  6483. }
  6484. props = normalizeProps(props);
  6485. if (isHTMLComponent(Component)) {
  6486. return renderHTMLComponent(result, Component, props, slots).catch(handleCancellation);
  6487. }
  6488. if (isAstroComponentFactory(Component)) {
  6489. return renderAstroComponent(result, displayName, Component, props, slots);
  6490. }
  6491. return renderFrameworkComponent(result, displayName, Component, props, slots).catch(
  6492. handleCancellation
  6493. );
  6494. function handleCancellation(e) {
  6495. if (result.cancelled)
  6496. return {
  6497. render() {
  6498. }
  6499. };
  6500. throw e;
  6501. }
  6502. }
  6503. function normalizeProps(props) {
  6504. if (props["class:list"] !== void 0) {
  6505. const value = props["class:list"];
  6506. delete props["class:list"];
  6507. props["class"] = clsx(props["class"], value);
  6508. if (props["class"] === "") {
  6509. delete props["class"];
  6510. }
  6511. }
  6512. return props;
  6513. }
  6514. async function renderComponentToString(result, displayName, Component, props, slots = {}, isPage = false, route) {
  6515. let str = "";
  6516. let renderedFirstPageChunk = false;
  6517. let head = "";
  6518. if (isPage && !result.partial && nonAstroPageNeedsHeadInjection(Component)) {
  6519. head += chunkToString(result, maybeRenderHead());
  6520. }
  6521. try {
  6522. const destination = {
  6523. write(chunk) {
  6524. if (isPage && !result.partial && !renderedFirstPageChunk) {
  6525. renderedFirstPageChunk = true;
  6526. if (!/<!doctype html/i.test(String(chunk))) {
  6527. const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
  6528. str += doctype + head;
  6529. }
  6530. }
  6531. if (chunk instanceof Response) return;
  6532. str += chunkToString(result, chunk);
  6533. }
  6534. };
  6535. const renderInstance = await renderComponent(result, displayName, Component, props, slots);
  6536. if (containsServerDirective(props)) {
  6537. await bufferHeadContent(result);
  6538. }
  6539. await renderInstance.render(destination);
  6540. } catch (e) {
  6541. if (AstroError.is(e) && !e.loc) {
  6542. e.setLocation({
  6543. file: route?.component
  6544. });
  6545. }
  6546. throw e;
  6547. }
  6548. return str;
  6549. }
  6550. function nonAstroPageNeedsHeadInjection(pageComponent) {
  6551. return !!pageComponent?.[needsHeadRenderingSymbol];
  6552. }
  6553. const ClientOnlyPlaceholder = "astro-client-only";
  6554. const hasTriedRenderComponentSymbol = Symbol("hasTriedRenderComponent");
  6555. async function renderJSX(result, vnode) {
  6556. switch (true) {
  6557. case vnode instanceof HTMLString:
  6558. if (vnode.toString().trim() === "") {
  6559. return "";
  6560. }
  6561. return vnode;
  6562. case typeof vnode === "string":
  6563. return markHTMLString(escapeHTML(vnode));
  6564. case typeof vnode === "function":
  6565. return vnode;
  6566. case (!vnode && vnode !== 0):
  6567. return "";
  6568. case Array.isArray(vnode):
  6569. return markHTMLString(
  6570. (await Promise.all(vnode.map((v) => renderJSX(result, v)))).join("")
  6571. );
  6572. }
  6573. return renderJSXVNode(result, vnode);
  6574. }
  6575. async function renderJSXVNode(result, vnode) {
  6576. if (isVNode(vnode)) {
  6577. switch (true) {
  6578. case !vnode.type: {
  6579. throw new Error(`Unable to render ${result.pathname} because it contains an undefined Component!
  6580. Did you forget to import the component or is it possible there is a typo?`);
  6581. }
  6582. case vnode.type === Symbol.for("astro:fragment"):
  6583. return renderJSX(result, vnode.props.children);
  6584. case isAstroComponentFactory(vnode.type): {
  6585. let props = {};
  6586. let slots = {};
  6587. for (const [key, value] of Object.entries(vnode.props ?? {})) {
  6588. if (key === "children" || value && typeof value === "object" && value["$$slot"]) {
  6589. slots[key === "children" ? "default" : key] = () => renderJSX(result, value);
  6590. } else {
  6591. props[key] = value;
  6592. }
  6593. }
  6594. const str = await renderComponentToString(
  6595. result,
  6596. vnode.type.name,
  6597. vnode.type,
  6598. props,
  6599. slots
  6600. );
  6601. const html = markHTMLString(str);
  6602. return html;
  6603. }
  6604. case (!vnode.type && vnode.type !== 0):
  6605. return "";
  6606. case (typeof vnode.type === "string" && vnode.type !== ClientOnlyPlaceholder):
  6607. return markHTMLString(await renderElement(result, vnode.type, vnode.props ?? {}));
  6608. }
  6609. if (vnode.type) {
  6610. let extractSlots2 = function(child) {
  6611. if (Array.isArray(child)) {
  6612. return child.map((c) => extractSlots2(c));
  6613. }
  6614. if (!isVNode(child)) {
  6615. _slots.default.push(child);
  6616. return;
  6617. }
  6618. if ("slot" in child.props) {
  6619. _slots[child.props.slot] = [..._slots[child.props.slot] ?? [], child];
  6620. delete child.props.slot;
  6621. return;
  6622. }
  6623. _slots.default.push(child);
  6624. };
  6625. if (typeof vnode.type === "function" && vnode.props["server:root"]) {
  6626. const output2 = await vnode.type(vnode.props ?? {});
  6627. return await renderJSX(result, output2);
  6628. }
  6629. if (typeof vnode.type === "function") {
  6630. if (vnode.props[hasTriedRenderComponentSymbol]) {
  6631. delete vnode.props[hasTriedRenderComponentSymbol];
  6632. const output2 = await vnode.type(vnode.props ?? {});
  6633. if (output2?.[AstroJSX] || !output2) {
  6634. return await renderJSXVNode(result, output2);
  6635. } else {
  6636. return;
  6637. }
  6638. } else {
  6639. vnode.props[hasTriedRenderComponentSymbol] = true;
  6640. }
  6641. }
  6642. const { children = null, ...props } = vnode.props ?? {};
  6643. const _slots = {
  6644. default: []
  6645. };
  6646. extractSlots2(children);
  6647. for (const [key, value] of Object.entries(props)) {
  6648. if (value?.["$$slot"]) {
  6649. _slots[key] = value;
  6650. delete props[key];
  6651. }
  6652. }
  6653. const slotPromises = [];
  6654. const slots = {};
  6655. for (const [key, value] of Object.entries(_slots)) {
  6656. slotPromises.push(
  6657. renderJSX(result, value).then((output2) => {
  6658. if (output2.toString().trim().length === 0) return;
  6659. slots[key] = () => output2;
  6660. })
  6661. );
  6662. }
  6663. await Promise.all(slotPromises);
  6664. let output;
  6665. if (vnode.type === ClientOnlyPlaceholder && vnode.props["client:only"]) {
  6666. output = await renderComponentToString(
  6667. result,
  6668. vnode.props["client:display-name"] ?? "",
  6669. null,
  6670. props,
  6671. slots
  6672. );
  6673. } else {
  6674. output = await renderComponentToString(
  6675. result,
  6676. typeof vnode.type === "function" ? vnode.type.name : vnode.type,
  6677. vnode.type,
  6678. props,
  6679. slots
  6680. );
  6681. }
  6682. return markHTMLString(output);
  6683. }
  6684. }
  6685. return markHTMLString(`${vnode}`);
  6686. }
  6687. async function renderElement(result, tag, { children, ...props }) {
  6688. return markHTMLString(
  6689. `<${tag}${spreadAttributes(props)}${markHTMLString(
  6690. (children == null || children == "") && voidElementNames.test(tag) ? `/>` : `>${children == null ? "" : await renderJSX(result, prerenderElementChildren(tag, children))}</${tag}>`
  6691. )}`
  6692. );
  6693. }
  6694. function prerenderElementChildren(tag, children) {
  6695. if (typeof children === "string" && (tag === "style" || tag === "script")) {
  6696. return markHTMLString(children);
  6697. } else {
  6698. return children;
  6699. }
  6700. }
  6701. async function renderPage(result, componentFactory, props, children, streaming, route) {
  6702. if (!isAstroComponentFactory(componentFactory)) {
  6703. result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
  6704. const pageProps = { ...props ?? {}, "server:root": true };
  6705. const str = await renderComponentToString(
  6706. result,
  6707. componentFactory.name,
  6708. componentFactory,
  6709. pageProps,
  6710. {},
  6711. true,
  6712. route
  6713. );
  6714. const bytes = encoder.encode(str);
  6715. const headers2 = new Headers([
  6716. ["Content-Type", "text/html"],
  6717. ["Content-Length", bytes.byteLength.toString()]
  6718. ]);
  6719. if (result.shouldInjectCspMetaTags && (result.cspDestination === "header" || result.cspDestination === "adapter")) {
  6720. headers2.set("content-security-policy", renderCspContent(result));
  6721. }
  6722. return new Response(bytes, {
  6723. headers: headers2
  6724. });
  6725. }
  6726. result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
  6727. let body;
  6728. if (streaming) {
  6729. if (isNode && !isDeno) {
  6730. const nodeBody = await renderToAsyncIterable(
  6731. result,
  6732. componentFactory,
  6733. props,
  6734. children,
  6735. true,
  6736. route
  6737. );
  6738. body = nodeBody;
  6739. } else {
  6740. body = await renderToReadableStream(result, componentFactory, props, children, true, route);
  6741. }
  6742. } else {
  6743. body = await renderToString(result, componentFactory, props, children, true, route);
  6744. }
  6745. if (body instanceof Response) return body;
  6746. const init = result.response;
  6747. const headers = new Headers(init.headers);
  6748. if (result.shouldInjectCspMetaTags && result.cspDestination === "header" || result.cspDestination === "adapter") {
  6749. headers.set("content-security-policy", renderCspContent(result));
  6750. }
  6751. if (!streaming && typeof body === "string") {
  6752. body = encoder.encode(body);
  6753. headers.set("Content-Length", body.byteLength.toString());
  6754. }
  6755. let status = init.status;
  6756. let statusText = init.statusText;
  6757. if (route?.route === "/404") {
  6758. status = 404;
  6759. if (statusText === "OK") {
  6760. statusText = "Not Found";
  6761. }
  6762. } else if (route?.route === "/500") {
  6763. status = 500;
  6764. if (statusText === "OK") {
  6765. statusText = "Internal Server Error";
  6766. }
  6767. }
  6768. if (status) {
  6769. return new Response(body, { ...init, headers, status, statusText });
  6770. } else {
  6771. return new Response(body, { ...init, headers });
  6772. }
  6773. }
  6774. async function renderScript(result, id) {
  6775. if (result._metadata.renderedScripts.has(id)) return;
  6776. result._metadata.renderedScripts.add(id);
  6777. const inlined = result.inlinedScripts.get(id);
  6778. if (inlined != null) {
  6779. if (inlined) {
  6780. return markHTMLString(`<script type="module">${inlined}</script>`);
  6781. } else {
  6782. return "";
  6783. }
  6784. }
  6785. const resolved = await result.resolve(id);
  6786. return markHTMLString(
  6787. `<script type="module" src="${result.userAssetsBase ? (result.base === "/" ? "" : result.base) + result.userAssetsBase : ""}${resolved}"></script>`
  6788. );
  6789. }
  6790. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  6791. var cssesc_1;
  6792. var hasRequiredCssesc;
  6793. function requireCssesc () {
  6794. if (hasRequiredCssesc) return cssesc_1;
  6795. hasRequiredCssesc = 1;
  6796. var object = {};
  6797. var hasOwnProperty = object.hasOwnProperty;
  6798. var merge = function merge(options, defaults) {
  6799. if (!options) {
  6800. return defaults;
  6801. }
  6802. var result = {};
  6803. for (var key in defaults) {
  6804. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  6805. // only recognized option names are used.
  6806. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  6807. }
  6808. return result;
  6809. };
  6810. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  6811. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  6812. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  6813. // https://mathiasbynens.be/notes/css-escapes#css
  6814. var cssesc = function cssesc(string, options) {
  6815. options = merge(options, cssesc.options);
  6816. if (options.quotes != 'single' && options.quotes != 'double') {
  6817. options.quotes = 'single';
  6818. }
  6819. var quote = options.quotes == 'double' ? '"' : '\'';
  6820. var isIdentifier = options.isIdentifier;
  6821. var firstChar = string.charAt(0);
  6822. var output = '';
  6823. var counter = 0;
  6824. var length = string.length;
  6825. while (counter < length) {
  6826. var character = string.charAt(counter++);
  6827. var codePoint = character.charCodeAt();
  6828. var value = void 0;
  6829. // If it’s not a printable ASCII character…
  6830. if (codePoint < 0x20 || codePoint > 0x7E) {
  6831. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  6832. // It’s a high surrogate, and there is a next character.
  6833. var extra = string.charCodeAt(counter++);
  6834. if ((extra & 0xFC00) == 0xDC00) {
  6835. // next character is low surrogate
  6836. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  6837. } else {
  6838. // It’s an unmatched surrogate; only append this code unit, in case
  6839. // the next code unit is the high surrogate of a surrogate pair.
  6840. counter--;
  6841. }
  6842. }
  6843. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  6844. } else {
  6845. if (options.escapeEverything) {
  6846. if (regexAnySingleEscape.test(character)) {
  6847. value = '\\' + character;
  6848. } else {
  6849. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  6850. }
  6851. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  6852. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  6853. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  6854. value = '\\' + character;
  6855. } else {
  6856. value = character;
  6857. }
  6858. }
  6859. output += value;
  6860. }
  6861. if (isIdentifier) {
  6862. if (/^-[-\d]/.test(output)) {
  6863. output = '\\-' + output.slice(1);
  6864. } else if (/\d/.test(firstChar)) {
  6865. output = '\\3' + firstChar + ' ' + output.slice(1);
  6866. }
  6867. }
  6868. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  6869. // since they’re redundant. Note that this is only possible if the escape
  6870. // sequence isn’t preceded by an odd number of backslashes.
  6871. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  6872. if ($1 && $1.length % 2) {
  6873. // It’s not safe to remove the space, so don’t.
  6874. return $0;
  6875. }
  6876. // Strip the space.
  6877. return ($1 || '') + $2;
  6878. });
  6879. if (!isIdentifier && options.wrap) {
  6880. return quote + output + quote;
  6881. }
  6882. return output;
  6883. };
  6884. // Expose default options (so they can be overridden globally).
  6885. cssesc.options = {
  6886. 'escapeEverything': false,
  6887. 'isIdentifier': false,
  6888. 'quotes': 'single',
  6889. 'wrap': false
  6890. };
  6891. cssesc.version = '3.0.0';
  6892. cssesc_1 = cssesc;
  6893. return cssesc_1;
  6894. }
  6895. requireCssesc();
  6896. "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_".split("").reduce((v, c) => (v[c.charCodeAt(0)] = c, v), []);
  6897. "-0123456789_".split("").reduce((v, c) => (v[c.charCodeAt(0)] = c, v), []);
  6898. function spreadAttributes(values = {}, _name, { class: scopedClassName } = {}) {
  6899. let output = "";
  6900. if (scopedClassName) {
  6901. if (typeof values.class !== "undefined") {
  6902. values.class += ` ${scopedClassName}`;
  6903. } else if (typeof values["class:list"] !== "undefined") {
  6904. values["class:list"] = [values["class:list"], scopedClassName];
  6905. } else {
  6906. values.class = scopedClassName;
  6907. }
  6908. }
  6909. for (const [key, value] of Object.entries(values)) {
  6910. output += addAttribute(value, key, true, _name);
  6911. }
  6912. return markHTMLString(output);
  6913. }
  6914. export { PageNumberParamNotFound as $, AstroError as A, blue as B, clientAddressSymbol as C, DEFAULT_404_COMPONENT as D, ExpectedImage as E, FailedToFetchRemoteImageDimensions as F, LocalsNotAnObject as G, REROUTABLE_STATUS_CODES as H, IncompatibleDescriptorOptions as I, responseSentSymbol as J, decryptString as K, LocalImageUsedWrongly as L, MissingImageDimension as M, NoImageMetadata as N, createSlotValueFromString as O, isAstroComponentFactory as P, i18nNoLocaleFoundInPath as Q, ROUTE_TYPE_HEADER as R, ResponseSentError as S, originPathnameSymbol as T, UnsupportedImageFormat as U, RewriteWithBodyUsed as V, GetStaticPathsRequired as W, InvalidGetStaticPathsReturn as X, InvalidGetStaticPathsEntry as Y, GetStaticPathsExpectedParams as Z, GetStaticPathsInvalidRouteParam as _, UnsupportedImageConversion as a, NoMatchingStaticPathFound as a0, PrerenderDynamicEndpointPathCollide as a1, ReservedSlotName as a2, renderSlotToString as a3, renderJSX as a4, chunkToString as a5, isRenderInstruction as a6, MiddlewareNoDataOrNextCalled as a7, MiddlewareNotAResponse as a8, SessionStorageInitError as a9, SessionStorageSaveError as aa, ForbiddenRewrite as ab, ASTRO_VERSION as ac, CspNotEnabled as ad, green as ae, LocalsReassigned as af, generateCspDigest as ag, PrerenderClientAddressNotAvailable as ah, ClientAddressNotAvailable as ai, StaticClientAddressNotAvailable as aj, AstroResponseHeadersReassigned as ak, renderPage as al, REWRITE_DIRECTIVE_HEADER_KEY as am, REWRITE_DIRECTIVE_HEADER_VALUE as an, renderEndpoint as ao, NOOP_MIDDLEWARE_HEADER as ap, REDIRECT_STATUS_CODES as aq, ActionsReturnedInvalidDataError as ar, escape as as, MissingSharp as at, ExpectedImageOptions as b, ExpectedNotESMImage as c, InvalidImageService as d, createComponent as e, createAstro as f, ImageMissingAlt as g, addAttribute as h, ExperimentalFontsNotEnabled as i, FontFamilyNotFound as j, renderComponent as k, renderHead as l, maybeRenderHead as m, renderScript as n, renderSlot as o, decodeKey as p, REROUTE_DIRECTIVE_HEADER as q, renderTemplate as r, spreadAttributes as s, toStyleString as t, unescapeHTML as u, ActionNotFoundError as v, bold as w, red as x, yellow as y, dim as z };