chunk-RBZI3ZHD.js 310 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470
  1. "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }/**
  2. * react-router v7.10.1
  3. *
  4. * Copyright (c) Remix Software Inc.
  5. *
  6. * This source code is licensed under the MIT license found in the
  7. * LICENSE.md file in the root directory of this source tree.
  8. *
  9. * @license MIT
  10. */
  11. var __typeError = (msg) => {
  12. throw TypeError(msg);
  13. };
  14. var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
  15. var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
  16. var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  17. // lib/router/history.ts
  18. var Action = /* @__PURE__ */ ((Action2) => {
  19. Action2["Pop"] = "POP";
  20. Action2["Push"] = "PUSH";
  21. Action2["Replace"] = "REPLACE";
  22. return Action2;
  23. })(Action || {});
  24. var PopStateEventType = "popstate";
  25. function createMemoryHistory(options = {}) {
  26. let { initialEntries = ["/"], initialIndex, v5Compat = false } = options;
  27. let entries;
  28. entries = initialEntries.map(
  29. (entry, index2) => createMemoryLocation(
  30. entry,
  31. typeof entry === "string" ? null : entry.state,
  32. index2 === 0 ? "default" : void 0
  33. )
  34. );
  35. let index = clampIndex(
  36. initialIndex == null ? entries.length - 1 : initialIndex
  37. );
  38. let action = "POP" /* Pop */;
  39. let listener = null;
  40. function clampIndex(n) {
  41. return Math.min(Math.max(n, 0), entries.length - 1);
  42. }
  43. function getCurrentLocation() {
  44. return entries[index];
  45. }
  46. function createMemoryLocation(to, state = null, key) {
  47. let location = createLocation(
  48. entries ? getCurrentLocation().pathname : "/",
  49. to,
  50. state,
  51. key
  52. );
  53. warning(
  54. location.pathname.charAt(0) === "/",
  55. `relative pathnames are not supported in memory history: ${JSON.stringify(
  56. to
  57. )}`
  58. );
  59. return location;
  60. }
  61. function createHref(to) {
  62. return typeof to === "string" ? to : createPath(to);
  63. }
  64. let history = {
  65. get index() {
  66. return index;
  67. },
  68. get action() {
  69. return action;
  70. },
  71. get location() {
  72. return getCurrentLocation();
  73. },
  74. createHref,
  75. createURL(to) {
  76. return new URL(createHref(to), "http://localhost");
  77. },
  78. encodeLocation(to) {
  79. let path = typeof to === "string" ? parsePath(to) : to;
  80. return {
  81. pathname: path.pathname || "",
  82. search: path.search || "",
  83. hash: path.hash || ""
  84. };
  85. },
  86. push(to, state) {
  87. action = "PUSH" /* Push */;
  88. let nextLocation = createMemoryLocation(to, state);
  89. index += 1;
  90. entries.splice(index, entries.length, nextLocation);
  91. if (v5Compat && listener) {
  92. listener({ action, location: nextLocation, delta: 1 });
  93. }
  94. },
  95. replace(to, state) {
  96. action = "REPLACE" /* Replace */;
  97. let nextLocation = createMemoryLocation(to, state);
  98. entries[index] = nextLocation;
  99. if (v5Compat && listener) {
  100. listener({ action, location: nextLocation, delta: 0 });
  101. }
  102. },
  103. go(delta) {
  104. action = "POP" /* Pop */;
  105. let nextIndex = clampIndex(index + delta);
  106. let nextLocation = entries[nextIndex];
  107. index = nextIndex;
  108. if (listener) {
  109. listener({ action, location: nextLocation, delta });
  110. }
  111. },
  112. listen(fn) {
  113. listener = fn;
  114. return () => {
  115. listener = null;
  116. };
  117. }
  118. };
  119. return history;
  120. }
  121. function createBrowserHistory(options = {}) {
  122. function createBrowserLocation(window2, globalHistory) {
  123. let { pathname, search, hash } = window2.location;
  124. return createLocation(
  125. "",
  126. { pathname, search, hash },
  127. // state defaults to `null` because `window.history.state` does
  128. globalHistory.state && globalHistory.state.usr || null,
  129. globalHistory.state && globalHistory.state.key || "default"
  130. );
  131. }
  132. function createBrowserHref(window2, to) {
  133. return typeof to === "string" ? to : createPath(to);
  134. }
  135. return getUrlBasedHistory(
  136. createBrowserLocation,
  137. createBrowserHref,
  138. null,
  139. options
  140. );
  141. }
  142. function createHashHistory(options = {}) {
  143. function createHashLocation(window2, globalHistory) {
  144. let {
  145. pathname = "/",
  146. search = "",
  147. hash = ""
  148. } = parsePath(window2.location.hash.substring(1));
  149. if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
  150. pathname = "/" + pathname;
  151. }
  152. return createLocation(
  153. "",
  154. { pathname, search, hash },
  155. // state defaults to `null` because `window.history.state` does
  156. globalHistory.state && globalHistory.state.usr || null,
  157. globalHistory.state && globalHistory.state.key || "default"
  158. );
  159. }
  160. function createHashHref(window2, to) {
  161. let base = window2.document.querySelector("base");
  162. let href = "";
  163. if (base && base.getAttribute("href")) {
  164. let url = window2.location.href;
  165. let hashIndex = url.indexOf("#");
  166. href = hashIndex === -1 ? url : url.slice(0, hashIndex);
  167. }
  168. return href + "#" + (typeof to === "string" ? to : createPath(to));
  169. }
  170. function validateHashLocation(location, to) {
  171. warning(
  172. location.pathname.charAt(0) === "/",
  173. `relative pathnames are not supported in hash history.push(${JSON.stringify(
  174. to
  175. )})`
  176. );
  177. }
  178. return getUrlBasedHistory(
  179. createHashLocation,
  180. createHashHref,
  181. validateHashLocation,
  182. options
  183. );
  184. }
  185. function invariant(value, message) {
  186. if (value === false || value === null || typeof value === "undefined") {
  187. throw new Error(message);
  188. }
  189. }
  190. function warning(cond, message) {
  191. if (!cond) {
  192. if (typeof console !== "undefined") console.warn(message);
  193. try {
  194. throw new Error(message);
  195. } catch (e) {
  196. }
  197. }
  198. }
  199. function createKey() {
  200. return Math.random().toString(36).substring(2, 10);
  201. }
  202. function getHistoryState(location, index) {
  203. return {
  204. usr: location.state,
  205. key: location.key,
  206. idx: index
  207. };
  208. }
  209. function createLocation(current, to, state = null, key) {
  210. let location = {
  211. pathname: typeof current === "string" ? current : current.pathname,
  212. search: "",
  213. hash: "",
  214. ...typeof to === "string" ? parsePath(to) : to,
  215. state,
  216. // TODO: This could be cleaned up. push/replace should probably just take
  217. // full Locations now and avoid the need to run through this flow at all
  218. // But that's a pretty big refactor to the current test suite so going to
  219. // keep as is for the time being and just let any incoming keys take precedence
  220. key: to && to.key || key || createKey()
  221. };
  222. return location;
  223. }
  224. function createPath({
  225. pathname = "/",
  226. search = "",
  227. hash = ""
  228. }) {
  229. if (search && search !== "?")
  230. pathname += search.charAt(0) === "?" ? search : "?" + search;
  231. if (hash && hash !== "#")
  232. pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  233. return pathname;
  234. }
  235. function parsePath(path) {
  236. let parsedPath = {};
  237. if (path) {
  238. let hashIndex = path.indexOf("#");
  239. if (hashIndex >= 0) {
  240. parsedPath.hash = path.substring(hashIndex);
  241. path = path.substring(0, hashIndex);
  242. }
  243. let searchIndex = path.indexOf("?");
  244. if (searchIndex >= 0) {
  245. parsedPath.search = path.substring(searchIndex);
  246. path = path.substring(0, searchIndex);
  247. }
  248. if (path) {
  249. parsedPath.pathname = path;
  250. }
  251. }
  252. return parsedPath;
  253. }
  254. function getUrlBasedHistory(getLocation, createHref, validateLocation, options = {}) {
  255. let { window: window2 = document.defaultView, v5Compat = false } = options;
  256. let globalHistory = window2.history;
  257. let action = "POP" /* Pop */;
  258. let listener = null;
  259. let index = getIndex();
  260. if (index == null) {
  261. index = 0;
  262. globalHistory.replaceState({ ...globalHistory.state, idx: index }, "");
  263. }
  264. function getIndex() {
  265. let state = globalHistory.state || { idx: null };
  266. return state.idx;
  267. }
  268. function handlePop() {
  269. action = "POP" /* Pop */;
  270. let nextIndex = getIndex();
  271. let delta = nextIndex == null ? null : nextIndex - index;
  272. index = nextIndex;
  273. if (listener) {
  274. listener({ action, location: history.location, delta });
  275. }
  276. }
  277. function push(to, state) {
  278. action = "PUSH" /* Push */;
  279. let location = createLocation(history.location, to, state);
  280. if (validateLocation) validateLocation(location, to);
  281. index = getIndex() + 1;
  282. let historyState = getHistoryState(location, index);
  283. let url = history.createHref(location);
  284. try {
  285. globalHistory.pushState(historyState, "", url);
  286. } catch (error) {
  287. if (error instanceof DOMException && error.name === "DataCloneError") {
  288. throw error;
  289. }
  290. window2.location.assign(url);
  291. }
  292. if (v5Compat && listener) {
  293. listener({ action, location: history.location, delta: 1 });
  294. }
  295. }
  296. function replace2(to, state) {
  297. action = "REPLACE" /* Replace */;
  298. let location = createLocation(history.location, to, state);
  299. if (validateLocation) validateLocation(location, to);
  300. index = getIndex();
  301. let historyState = getHistoryState(location, index);
  302. let url = history.createHref(location);
  303. globalHistory.replaceState(historyState, "", url);
  304. if (v5Compat && listener) {
  305. listener({ action, location: history.location, delta: 0 });
  306. }
  307. }
  308. function createURL(to) {
  309. return createBrowserURLImpl(to);
  310. }
  311. let history = {
  312. get action() {
  313. return action;
  314. },
  315. get location() {
  316. return getLocation(window2, globalHistory);
  317. },
  318. listen(fn) {
  319. if (listener) {
  320. throw new Error("A history only accepts one active listener");
  321. }
  322. window2.addEventListener(PopStateEventType, handlePop);
  323. listener = fn;
  324. return () => {
  325. window2.removeEventListener(PopStateEventType, handlePop);
  326. listener = null;
  327. };
  328. },
  329. createHref(to) {
  330. return createHref(window2, to);
  331. },
  332. createURL,
  333. encodeLocation(to) {
  334. let url = createURL(to);
  335. return {
  336. pathname: url.pathname,
  337. search: url.search,
  338. hash: url.hash
  339. };
  340. },
  341. push,
  342. replace: replace2,
  343. go(n) {
  344. return globalHistory.go(n);
  345. }
  346. };
  347. return history;
  348. }
  349. function createBrowserURLImpl(to, isAbsolute = false) {
  350. let base = "http://localhost";
  351. if (typeof window !== "undefined") {
  352. base = window.location.origin !== "null" ? window.location.origin : window.location.href;
  353. }
  354. invariant(base, "No window.location.(origin|href) available to create URL");
  355. let href = typeof to === "string" ? to : createPath(to);
  356. href = href.replace(/ $/, "%20");
  357. if (!isAbsolute && href.startsWith("//")) {
  358. href = base + href;
  359. }
  360. return new URL(href, base);
  361. }
  362. // lib/router/utils.ts
  363. function createContext(defaultValue) {
  364. return { defaultValue };
  365. }
  366. var _map;
  367. var RouterContextProvider = class {
  368. /**
  369. * Create a new `RouterContextProvider` instance
  370. * @param init An optional initial context map to populate the provider with
  371. */
  372. constructor(init) {
  373. __privateAdd(this, _map, /* @__PURE__ */ new Map());
  374. if (init) {
  375. for (let [context, value] of init) {
  376. this.set(context, value);
  377. }
  378. }
  379. }
  380. /**
  381. * Access a value from the context. If no value has been set for the context,
  382. * it will return the context's `defaultValue` if provided, or throw an error
  383. * if no `defaultValue` was set.
  384. * @param context The context to get the value for
  385. * @returns The value for the context, or the context's `defaultValue` if no
  386. * value was set
  387. */
  388. get(context) {
  389. if (__privateGet(this, _map).has(context)) {
  390. return __privateGet(this, _map).get(context);
  391. }
  392. if (context.defaultValue !== void 0) {
  393. return context.defaultValue;
  394. }
  395. throw new Error("No value found for context");
  396. }
  397. /**
  398. * Set a value for the context. If the context already has a value set, this
  399. * will overwrite it.
  400. *
  401. * @param context The context to set the value for
  402. * @param value The value to set for the context
  403. * @returns {void}
  404. */
  405. set(context, value) {
  406. __privateGet(this, _map).set(context, value);
  407. }
  408. };
  409. _map = new WeakMap();
  410. var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([
  411. "lazy",
  412. "caseSensitive",
  413. "path",
  414. "id",
  415. "index",
  416. "children"
  417. ]);
  418. function isUnsupportedLazyRouteObjectKey(key) {
  419. return unsupportedLazyRouteObjectKeys.has(
  420. key
  421. );
  422. }
  423. var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([
  424. "lazy",
  425. "caseSensitive",
  426. "path",
  427. "id",
  428. "index",
  429. "middleware",
  430. "children"
  431. ]);
  432. function isUnsupportedLazyRouteFunctionKey(key) {
  433. return unsupportedLazyRouteFunctionKeys.has(
  434. key
  435. );
  436. }
  437. function isIndexRoute(route) {
  438. return route.index === true;
  439. }
  440. function convertRoutesToDataRoutes(routes, mapRouteProperties2, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
  441. return routes.map((route, index) => {
  442. let treePath = [...parentPath, String(index)];
  443. let id = typeof route.id === "string" ? route.id : treePath.join("-");
  444. invariant(
  445. route.index !== true || !route.children,
  446. `Cannot specify children on an index route`
  447. );
  448. invariant(
  449. allowInPlaceMutations || !manifest[id],
  450. `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
  451. );
  452. if (isIndexRoute(route)) {
  453. let indexRoute = {
  454. ...route,
  455. id
  456. };
  457. manifest[id] = mergeRouteUpdates(
  458. indexRoute,
  459. mapRouteProperties2(indexRoute)
  460. );
  461. return indexRoute;
  462. } else {
  463. let pathOrLayoutRoute = {
  464. ...route,
  465. id,
  466. children: void 0
  467. };
  468. manifest[id] = mergeRouteUpdates(
  469. pathOrLayoutRoute,
  470. mapRouteProperties2(pathOrLayoutRoute)
  471. );
  472. if (route.children) {
  473. pathOrLayoutRoute.children = convertRoutesToDataRoutes(
  474. route.children,
  475. mapRouteProperties2,
  476. treePath,
  477. manifest,
  478. allowInPlaceMutations
  479. );
  480. }
  481. return pathOrLayoutRoute;
  482. }
  483. });
  484. }
  485. function mergeRouteUpdates(route, updates) {
  486. return Object.assign(route, {
  487. ...updates,
  488. ...typeof updates.lazy === "object" && updates.lazy != null ? {
  489. lazy: {
  490. ...route.lazy,
  491. ...updates.lazy
  492. }
  493. } : {}
  494. });
  495. }
  496. function matchRoutes(routes, locationArg, basename = "/") {
  497. return matchRoutesImpl(routes, locationArg, basename, false);
  498. }
  499. function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
  500. let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  501. let pathname = stripBasename(location.pathname || "/", basename);
  502. if (pathname == null) {
  503. return null;
  504. }
  505. let branches = flattenRoutes(routes);
  506. rankRouteBranches(branches);
  507. let matches = null;
  508. for (let i = 0; matches == null && i < branches.length; ++i) {
  509. let decoded = decodePath(pathname);
  510. matches = matchRouteBranch(
  511. branches[i],
  512. decoded,
  513. allowPartial
  514. );
  515. }
  516. return matches;
  517. }
  518. function convertRouteMatchToUiMatch(match, loaderData) {
  519. let { route, pathname, params } = match;
  520. return {
  521. id: route.id,
  522. pathname,
  523. params,
  524. data: loaderData[route.id],
  525. loaderData: loaderData[route.id],
  526. handle: route.handle
  527. };
  528. }
  529. function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
  530. let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
  531. let meta = {
  532. relativePath: relativePath === void 0 ? route.path || "" : relativePath,
  533. caseSensitive: route.caseSensitive === true,
  534. childrenIndex: index,
  535. route
  536. };
  537. if (meta.relativePath.startsWith("/")) {
  538. if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) {
  539. return;
  540. }
  541. invariant(
  542. meta.relativePath.startsWith(parentPath),
  543. `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`
  544. );
  545. meta.relativePath = meta.relativePath.slice(parentPath.length);
  546. }
  547. let path = joinPaths([parentPath, meta.relativePath]);
  548. let routesMeta = parentsMeta.concat(meta);
  549. if (route.children && route.children.length > 0) {
  550. invariant(
  551. // Our types know better, but runtime JS may not!
  552. // @ts-expect-error
  553. route.index !== true,
  554. `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
  555. );
  556. flattenRoutes(
  557. route.children,
  558. branches,
  559. routesMeta,
  560. path,
  561. hasParentOptionalSegments
  562. );
  563. }
  564. if (route.path == null && !route.index) {
  565. return;
  566. }
  567. branches.push({
  568. path,
  569. score: computeScore(path, route.index),
  570. routesMeta
  571. });
  572. };
  573. routes.forEach((route, index) => {
  574. if (route.path === "" || !_optionalChain([route, 'access', _2 => _2.path, 'optionalAccess', _3 => _3.includes, 'call', _4 => _4("?")])) {
  575. flattenRoute(route, index);
  576. } else {
  577. for (let exploded of explodeOptionalSegments(route.path)) {
  578. flattenRoute(route, index, true, exploded);
  579. }
  580. }
  581. });
  582. return branches;
  583. }
  584. function explodeOptionalSegments(path) {
  585. let segments = path.split("/");
  586. if (segments.length === 0) return [];
  587. let [first, ...rest] = segments;
  588. let isOptional = first.endsWith("?");
  589. let required = first.replace(/\?$/, "");
  590. if (rest.length === 0) {
  591. return isOptional ? [required, ""] : [required];
  592. }
  593. let restExploded = explodeOptionalSegments(rest.join("/"));
  594. let result = [];
  595. result.push(
  596. ...restExploded.map(
  597. (subpath) => subpath === "" ? required : [required, subpath].join("/")
  598. )
  599. );
  600. if (isOptional) {
  601. result.push(...restExploded);
  602. }
  603. return result.map(
  604. (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
  605. );
  606. }
  607. function rankRouteBranches(branches) {
  608. branches.sort(
  609. (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
  610. a.routesMeta.map((meta) => meta.childrenIndex),
  611. b.routesMeta.map((meta) => meta.childrenIndex)
  612. )
  613. );
  614. }
  615. var paramRe = /^:[\w-]+$/;
  616. var dynamicSegmentValue = 3;
  617. var indexRouteValue = 2;
  618. var emptySegmentValue = 1;
  619. var staticSegmentValue = 10;
  620. var splatPenalty = -2;
  621. var isSplat = (s) => s === "*";
  622. function computeScore(path, index) {
  623. let segments = path.split("/");
  624. let initialScore = segments.length;
  625. if (segments.some(isSplat)) {
  626. initialScore += splatPenalty;
  627. }
  628. if (index) {
  629. initialScore += indexRouteValue;
  630. }
  631. return segments.filter((s) => !isSplat(s)).reduce(
  632. (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
  633. initialScore
  634. );
  635. }
  636. function compareIndexes(a, b) {
  637. let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
  638. return siblings ? (
  639. // If two routes are siblings, we should try to match the earlier sibling
  640. // first. This allows people to have fine-grained control over the matching
  641. // behavior by simply putting routes with identical paths in the order they
  642. // want them tried.
  643. a[a.length - 1] - b[b.length - 1]
  644. ) : (
  645. // Otherwise, it doesn't really make sense to rank non-siblings by index,
  646. // so they sort equally.
  647. 0
  648. );
  649. }
  650. function matchRouteBranch(branch, pathname, allowPartial = false) {
  651. let { routesMeta } = branch;
  652. let matchedParams = {};
  653. let matchedPathname = "/";
  654. let matches = [];
  655. for (let i = 0; i < routesMeta.length; ++i) {
  656. let meta = routesMeta[i];
  657. let end = i === routesMeta.length - 1;
  658. let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
  659. let match = matchPath(
  660. { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
  661. remainingPathname
  662. );
  663. let route = meta.route;
  664. if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
  665. match = matchPath(
  666. {
  667. path: meta.relativePath,
  668. caseSensitive: meta.caseSensitive,
  669. end: false
  670. },
  671. remainingPathname
  672. );
  673. }
  674. if (!match) {
  675. return null;
  676. }
  677. Object.assign(matchedParams, match.params);
  678. matches.push({
  679. // TODO: Can this as be avoided?
  680. params: matchedParams,
  681. pathname: joinPaths([matchedPathname, match.pathname]),
  682. pathnameBase: normalizePathname(
  683. joinPaths([matchedPathname, match.pathnameBase])
  684. ),
  685. route
  686. });
  687. if (match.pathnameBase !== "/") {
  688. matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
  689. }
  690. }
  691. return matches;
  692. }
  693. function generatePath(originalPath, params = {}) {
  694. let path = originalPath;
  695. if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
  696. warning(
  697. false,
  698. `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`
  699. );
  700. path = path.replace(/\*$/, "/*");
  701. }
  702. const prefix = path.startsWith("/") ? "/" : "";
  703. const stringify2 = (p) => p == null ? "" : typeof p === "string" ? p : String(p);
  704. const segments = path.split(/\/+/).map((segment, index, array) => {
  705. const isLastSegment = index === array.length - 1;
  706. if (isLastSegment && segment === "*") {
  707. const star = "*";
  708. return stringify2(params[star]);
  709. }
  710. const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
  711. if (keyMatch) {
  712. const [, key, optional] = keyMatch;
  713. let param = params[key];
  714. invariant(optional === "?" || param != null, `Missing ":${key}" param`);
  715. return encodeURIComponent(stringify2(param));
  716. }
  717. return segment.replace(/\?$/g, "");
  718. }).filter((segment) => !!segment);
  719. return prefix + segments.join("/");
  720. }
  721. function matchPath(pattern, pathname) {
  722. if (typeof pattern === "string") {
  723. pattern = { path: pattern, caseSensitive: false, end: true };
  724. }
  725. let [matcher, compiledParams] = compilePath(
  726. pattern.path,
  727. pattern.caseSensitive,
  728. pattern.end
  729. );
  730. let match = pathname.match(matcher);
  731. if (!match) return null;
  732. let matchedPathname = match[0];
  733. let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  734. let captureGroups = match.slice(1);
  735. let params = compiledParams.reduce(
  736. (memo2, { paramName, isOptional }, index) => {
  737. if (paramName === "*") {
  738. let splatValue = captureGroups[index] || "";
  739. pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
  740. }
  741. const value = captureGroups[index];
  742. if (isOptional && !value) {
  743. memo2[paramName] = void 0;
  744. } else {
  745. memo2[paramName] = (value || "").replace(/%2F/g, "/");
  746. }
  747. return memo2;
  748. },
  749. {}
  750. );
  751. return {
  752. params,
  753. pathname: matchedPathname,
  754. pathnameBase,
  755. pattern
  756. };
  757. }
  758. function compilePath(path, caseSensitive = false, end = true) {
  759. warning(
  760. path === "*" || !path.endsWith("*") || path.endsWith("/*"),
  761. `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`
  762. );
  763. let params = [];
  764. let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
  765. /\/:([\w-]+)(\?)?/g,
  766. (_, paramName, isOptional) => {
  767. params.push({ paramName, isOptional: isOptional != null });
  768. return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  769. }
  770. ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2");
  771. if (path.endsWith("*")) {
  772. params.push({ paramName: "*" });
  773. regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
  774. } else if (end) {
  775. regexpSource += "\\/*$";
  776. } else if (path !== "" && path !== "/") {
  777. regexpSource += "(?:(?=\\/|$))";
  778. } else {
  779. }
  780. let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
  781. return [matcher, params];
  782. }
  783. function decodePath(value) {
  784. try {
  785. return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
  786. } catch (error) {
  787. warning(
  788. false,
  789. `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`
  790. );
  791. return value;
  792. }
  793. }
  794. function stripBasename(pathname, basename) {
  795. if (basename === "/") return pathname;
  796. if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
  797. return null;
  798. }
  799. let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  800. let nextChar = pathname.charAt(startIndex);
  801. if (nextChar && nextChar !== "/") {
  802. return null;
  803. }
  804. return pathname.slice(startIndex) || "/";
  805. }
  806. function prependBasename({
  807. basename,
  808. pathname
  809. }) {
  810. return pathname === "/" ? basename : joinPaths([basename, pathname]);
  811. }
  812. var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  813. var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
  814. function resolvePath(to, fromPathname = "/") {
  815. let {
  816. pathname: toPathname,
  817. search = "",
  818. hash = ""
  819. } = typeof to === "string" ? parsePath(to) : to;
  820. let pathname;
  821. if (toPathname) {
  822. if (isAbsoluteUrl(toPathname)) {
  823. pathname = toPathname;
  824. } else {
  825. if (toPathname.includes("//")) {
  826. let oldPathname = toPathname;
  827. toPathname = toPathname.replace(/\/\/+/g, "/");
  828. warning(
  829. false,
  830. `Pathnames cannot have embedded double slashes - normalizing ${oldPathname} -> ${toPathname}`
  831. );
  832. }
  833. if (toPathname.startsWith("/")) {
  834. pathname = resolvePathname(toPathname.substring(1), "/");
  835. } else {
  836. pathname = resolvePathname(toPathname, fromPathname);
  837. }
  838. }
  839. } else {
  840. pathname = fromPathname;
  841. }
  842. return {
  843. pathname,
  844. search: normalizeSearch(search),
  845. hash: normalizeHash(hash)
  846. };
  847. }
  848. function resolvePathname(relativePath, fromPathname) {
  849. let segments = fromPathname.replace(/\/+$/, "").split("/");
  850. let relativeSegments = relativePath.split("/");
  851. relativeSegments.forEach((segment) => {
  852. if (segment === "..") {
  853. if (segments.length > 1) segments.pop();
  854. } else if (segment !== ".") {
  855. segments.push(segment);
  856. }
  857. });
  858. return segments.length > 1 ? segments.join("/") : "/";
  859. }
  860. function getInvalidPathError(char, field, dest, path) {
  861. return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
  862. path
  863. )}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
  864. }
  865. function getPathContributingMatches(matches) {
  866. return matches.filter(
  867. (match, index) => index === 0 || match.route.path && match.route.path.length > 0
  868. );
  869. }
  870. function getResolveToMatches(matches) {
  871. let pathMatches = getPathContributingMatches(matches);
  872. return pathMatches.map(
  873. (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
  874. );
  875. }
  876. function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
  877. let to;
  878. if (typeof toArg === "string") {
  879. to = parsePath(toArg);
  880. } else {
  881. to = { ...toArg };
  882. invariant(
  883. !to.pathname || !to.pathname.includes("?"),
  884. getInvalidPathError("?", "pathname", "search", to)
  885. );
  886. invariant(
  887. !to.pathname || !to.pathname.includes("#"),
  888. getInvalidPathError("#", "pathname", "hash", to)
  889. );
  890. invariant(
  891. !to.search || !to.search.includes("#"),
  892. getInvalidPathError("#", "search", "hash", to)
  893. );
  894. }
  895. let isEmptyPath = toArg === "" || to.pathname === "";
  896. let toPathname = isEmptyPath ? "/" : to.pathname;
  897. let from;
  898. if (toPathname == null) {
  899. from = locationPathname;
  900. } else {
  901. let routePathnameIndex = routePathnames.length - 1;
  902. if (!isPathRelative && toPathname.startsWith("..")) {
  903. let toSegments = toPathname.split("/");
  904. while (toSegments[0] === "..") {
  905. toSegments.shift();
  906. routePathnameIndex -= 1;
  907. }
  908. to.pathname = toSegments.join("/");
  909. }
  910. from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  911. }
  912. let path = resolvePath(to, from);
  913. let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  914. let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  915. if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
  916. path.pathname += "/";
  917. }
  918. return path;
  919. }
  920. var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
  921. var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
  922. var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
  923. var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
  924. var DataWithResponseInit = class {
  925. constructor(data2, init) {
  926. this.type = "DataWithResponseInit";
  927. this.data = data2;
  928. this.init = init || null;
  929. }
  930. };
  931. function data(data2, init) {
  932. return new DataWithResponseInit(
  933. data2,
  934. typeof init === "number" ? { status: init } : init
  935. );
  936. }
  937. var redirect = (url, init = 302) => {
  938. let responseInit = init;
  939. if (typeof responseInit === "number") {
  940. responseInit = { status: responseInit };
  941. } else if (typeof responseInit.status === "undefined") {
  942. responseInit.status = 302;
  943. }
  944. let headers = new Headers(responseInit.headers);
  945. headers.set("Location", url);
  946. return new Response(null, { ...responseInit, headers });
  947. };
  948. var redirectDocument = (url, init) => {
  949. let response = redirect(url, init);
  950. response.headers.set("X-Remix-Reload-Document", "true");
  951. return response;
  952. };
  953. var replace = (url, init) => {
  954. let response = redirect(url, init);
  955. response.headers.set("X-Remix-Replace", "true");
  956. return response;
  957. };
  958. var ErrorResponseImpl = class {
  959. constructor(status, statusText, data2, internal = false) {
  960. this.status = status;
  961. this.statusText = statusText || "";
  962. this.internal = internal;
  963. if (data2 instanceof Error) {
  964. this.data = data2.toString();
  965. this.error = data2;
  966. } else {
  967. this.data = data2;
  968. }
  969. }
  970. };
  971. function isRouteErrorResponse(error) {
  972. return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
  973. }
  974. function getRoutePattern(matches) {
  975. return matches.map((m) => m.route.path).filter(Boolean).join("/").replace(/\/\/*/g, "/") || "/";
  976. }
  977. // lib/router/instrumentation.ts
  978. var UninstrumentedSymbol = Symbol("Uninstrumented");
  979. function getRouteInstrumentationUpdates(fns, route) {
  980. let aggregated = {
  981. lazy: [],
  982. "lazy.loader": [],
  983. "lazy.action": [],
  984. "lazy.middleware": [],
  985. middleware: [],
  986. loader: [],
  987. action: []
  988. };
  989. fns.forEach(
  990. (fn) => fn({
  991. id: route.id,
  992. index: route.index,
  993. path: route.path,
  994. instrument(i) {
  995. let keys = Object.keys(aggregated);
  996. for (let key of keys) {
  997. if (i[key]) {
  998. aggregated[key].push(i[key]);
  999. }
  1000. }
  1001. }
  1002. })
  1003. );
  1004. let updates = {};
  1005. if (typeof route.lazy === "function" && aggregated.lazy.length > 0) {
  1006. let instrumented = wrapImpl(aggregated.lazy, route.lazy, () => void 0);
  1007. if (instrumented) {
  1008. updates.lazy = instrumented;
  1009. }
  1010. }
  1011. if (typeof route.lazy === "object") {
  1012. let lazyObject = route.lazy;
  1013. ["middleware", "loader", "action"].forEach((key) => {
  1014. let lazyFn = lazyObject[key];
  1015. let instrumentations = aggregated[`lazy.${key}`];
  1016. if (typeof lazyFn === "function" && instrumentations.length > 0) {
  1017. let instrumented = wrapImpl(instrumentations, lazyFn, () => void 0);
  1018. if (instrumented) {
  1019. updates.lazy = Object.assign(updates.lazy || {}, {
  1020. [key]: instrumented
  1021. });
  1022. }
  1023. }
  1024. });
  1025. }
  1026. ["loader", "action"].forEach((key) => {
  1027. let handler = route[key];
  1028. if (typeof handler === "function" && aggregated[key].length > 0) {
  1029. let original = _nullishCoalesce(handler[UninstrumentedSymbol], () => ( handler));
  1030. let instrumented = wrapImpl(
  1031. aggregated[key],
  1032. original,
  1033. (...args) => getHandlerInfo(args[0])
  1034. );
  1035. if (instrumented) {
  1036. instrumented[UninstrumentedSymbol] = original;
  1037. updates[key] = instrumented;
  1038. }
  1039. }
  1040. });
  1041. if (route.middleware && route.middleware.length > 0 && aggregated.middleware.length > 0) {
  1042. updates.middleware = route.middleware.map((middleware) => {
  1043. let original = _nullishCoalesce(middleware[UninstrumentedSymbol], () => ( middleware));
  1044. let instrumented = wrapImpl(
  1045. aggregated.middleware,
  1046. original,
  1047. (...args) => getHandlerInfo(args[0])
  1048. );
  1049. if (instrumented) {
  1050. instrumented[UninstrumentedSymbol] = original;
  1051. return instrumented;
  1052. }
  1053. return middleware;
  1054. });
  1055. }
  1056. return updates;
  1057. }
  1058. function instrumentClientSideRouter(router, fns) {
  1059. let aggregated = {
  1060. navigate: [],
  1061. fetch: []
  1062. };
  1063. fns.forEach(
  1064. (fn) => fn({
  1065. instrument(i) {
  1066. let keys = Object.keys(i);
  1067. for (let key of keys) {
  1068. if (i[key]) {
  1069. aggregated[key].push(i[key]);
  1070. }
  1071. }
  1072. }
  1073. })
  1074. );
  1075. if (aggregated.navigate.length > 0) {
  1076. let navigate = _nullishCoalesce(router.navigate[UninstrumentedSymbol], () => ( router.navigate));
  1077. let instrumentedNavigate = wrapImpl(
  1078. aggregated.navigate,
  1079. navigate,
  1080. (...args) => {
  1081. let [to, opts] = args;
  1082. return {
  1083. to: typeof to === "number" || typeof to === "string" ? to : to ? createPath(to) : ".",
  1084. ...getRouterInfo(router, _nullishCoalesce(opts, () => ( {})))
  1085. };
  1086. }
  1087. );
  1088. if (instrumentedNavigate) {
  1089. instrumentedNavigate[UninstrumentedSymbol] = navigate;
  1090. router.navigate = instrumentedNavigate;
  1091. }
  1092. }
  1093. if (aggregated.fetch.length > 0) {
  1094. let fetch2 = _nullishCoalesce(router.fetch[UninstrumentedSymbol], () => ( router.fetch));
  1095. let instrumentedFetch = wrapImpl(aggregated.fetch, fetch2, (...args) => {
  1096. let [key, , href, opts] = args;
  1097. return {
  1098. href: _nullishCoalesce(href, () => ( ".")),
  1099. fetcherKey: key,
  1100. ...getRouterInfo(router, _nullishCoalesce(opts, () => ( {})))
  1101. };
  1102. });
  1103. if (instrumentedFetch) {
  1104. instrumentedFetch[UninstrumentedSymbol] = fetch2;
  1105. router.fetch = instrumentedFetch;
  1106. }
  1107. }
  1108. return router;
  1109. }
  1110. function instrumentHandler(handler, fns) {
  1111. let aggregated = {
  1112. request: []
  1113. };
  1114. fns.forEach(
  1115. (fn) => fn({
  1116. instrument(i) {
  1117. let keys = Object.keys(i);
  1118. for (let key of keys) {
  1119. if (i[key]) {
  1120. aggregated[key].push(i[key]);
  1121. }
  1122. }
  1123. }
  1124. })
  1125. );
  1126. let instrumentedHandler = handler;
  1127. if (aggregated.request.length > 0) {
  1128. instrumentedHandler = wrapImpl(aggregated.request, handler, (...args) => {
  1129. let [request, context] = args;
  1130. return {
  1131. request: getReadonlyRequest(request),
  1132. context: context != null ? getReadonlyContext(context) : context
  1133. };
  1134. });
  1135. }
  1136. return instrumentedHandler;
  1137. }
  1138. function wrapImpl(impls, handler, getInfo) {
  1139. if (impls.length === 0) {
  1140. return null;
  1141. }
  1142. return async (...args) => {
  1143. let result = await recurseRight(
  1144. impls,
  1145. getInfo(...args),
  1146. () => handler(...args),
  1147. impls.length - 1
  1148. );
  1149. if (result.type === "error") {
  1150. throw result.value;
  1151. }
  1152. return result.value;
  1153. };
  1154. }
  1155. async function recurseRight(impls, info, handler, index) {
  1156. let impl = impls[index];
  1157. let result;
  1158. if (!impl) {
  1159. try {
  1160. let value = await handler();
  1161. result = { type: "success", value };
  1162. } catch (e) {
  1163. result = { type: "error", value: e };
  1164. }
  1165. } else {
  1166. let handlerPromise = void 0;
  1167. let callHandler = async () => {
  1168. if (handlerPromise) {
  1169. console.error("You cannot call instrumented handlers more than once");
  1170. } else {
  1171. handlerPromise = recurseRight(impls, info, handler, index - 1);
  1172. }
  1173. result = await handlerPromise;
  1174. invariant(result, "Expected a result");
  1175. if (result.type === "error" && result.value instanceof Error) {
  1176. return { status: "error", error: result.value };
  1177. }
  1178. return { status: "success", error: void 0 };
  1179. };
  1180. try {
  1181. await impl(callHandler, info);
  1182. } catch (e) {
  1183. console.error("An instrumentation function threw an error:", e);
  1184. }
  1185. if (!handlerPromise) {
  1186. await callHandler();
  1187. }
  1188. await handlerPromise;
  1189. }
  1190. if (result) {
  1191. return result;
  1192. }
  1193. return {
  1194. type: "error",
  1195. value: new Error("No result assigned in instrumentation chain.")
  1196. };
  1197. }
  1198. function getHandlerInfo(args) {
  1199. let { request, context, params, unstable_pattern } = args;
  1200. return {
  1201. request: getReadonlyRequest(request),
  1202. params: { ...params },
  1203. unstable_pattern,
  1204. context: getReadonlyContext(context)
  1205. };
  1206. }
  1207. function getRouterInfo(router, opts) {
  1208. return {
  1209. currentUrl: createPath(router.state.location),
  1210. ..."formMethod" in opts ? { formMethod: opts.formMethod } : {},
  1211. ..."formEncType" in opts ? { formEncType: opts.formEncType } : {},
  1212. ..."formData" in opts ? { formData: opts.formData } : {},
  1213. ..."body" in opts ? { body: opts.body } : {}
  1214. };
  1215. }
  1216. function getReadonlyRequest(request) {
  1217. return {
  1218. method: request.method,
  1219. url: request.url,
  1220. headers: {
  1221. get: (...args) => request.headers.get(...args)
  1222. }
  1223. };
  1224. }
  1225. function getReadonlyContext(context) {
  1226. if (isPlainObject(context)) {
  1227. let frozen = { ...context };
  1228. Object.freeze(frozen);
  1229. return frozen;
  1230. } else {
  1231. return {
  1232. get: (ctx) => context.get(ctx)
  1233. };
  1234. }
  1235. }
  1236. var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
  1237. function isPlainObject(thing) {
  1238. if (thing === null || typeof thing !== "object") {
  1239. return false;
  1240. }
  1241. const proto = Object.getPrototypeOf(thing);
  1242. return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames;
  1243. }
  1244. // lib/router/router.ts
  1245. var validMutationMethodsArr = [
  1246. "POST",
  1247. "PUT",
  1248. "PATCH",
  1249. "DELETE"
  1250. ];
  1251. var validMutationMethods = new Set(
  1252. validMutationMethodsArr
  1253. );
  1254. var validRequestMethodsArr = [
  1255. "GET",
  1256. ...validMutationMethodsArr
  1257. ];
  1258. var validRequestMethods = new Set(validRequestMethodsArr);
  1259. var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
  1260. var redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]);
  1261. var IDLE_NAVIGATION = {
  1262. state: "idle",
  1263. location: void 0,
  1264. formMethod: void 0,
  1265. formAction: void 0,
  1266. formEncType: void 0,
  1267. formData: void 0,
  1268. json: void 0,
  1269. text: void 0
  1270. };
  1271. var IDLE_FETCHER = {
  1272. state: "idle",
  1273. data: void 0,
  1274. formMethod: void 0,
  1275. formAction: void 0,
  1276. formEncType: void 0,
  1277. formData: void 0,
  1278. json: void 0,
  1279. text: void 0
  1280. };
  1281. var IDLE_BLOCKER = {
  1282. state: "unblocked",
  1283. proceed: void 0,
  1284. reset: void 0,
  1285. location: void 0
  1286. };
  1287. var defaultMapRouteProperties = (route) => ({
  1288. hasErrorBoundary: Boolean(route.hasErrorBoundary)
  1289. });
  1290. var TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
  1291. var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
  1292. function createRouter(init) {
  1293. const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0;
  1294. const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
  1295. invariant(
  1296. init.routes.length > 0,
  1297. "You must provide a non-empty routes array to createRouter"
  1298. );
  1299. let hydrationRouteProperties2 = init.hydrationRouteProperties || [];
  1300. let _mapRouteProperties = init.mapRouteProperties || defaultMapRouteProperties;
  1301. let mapRouteProperties2 = _mapRouteProperties;
  1302. if (init.unstable_instrumentations) {
  1303. let instrumentations = init.unstable_instrumentations;
  1304. mapRouteProperties2 = (route) => {
  1305. return {
  1306. ..._mapRouteProperties(route),
  1307. ...getRouteInstrumentationUpdates(
  1308. instrumentations.map((i) => i.route).filter(Boolean),
  1309. route
  1310. )
  1311. };
  1312. };
  1313. }
  1314. let manifest = {};
  1315. let dataRoutes = convertRoutesToDataRoutes(
  1316. init.routes,
  1317. mapRouteProperties2,
  1318. void 0,
  1319. manifest
  1320. );
  1321. let inFlightDataRoutes;
  1322. let basename = init.basename || "/";
  1323. if (!basename.startsWith("/")) {
  1324. basename = `/${basename}`;
  1325. }
  1326. let dataStrategyImpl = init.dataStrategy || defaultDataStrategyWithMiddleware;
  1327. let future = {
  1328. ...init.future
  1329. };
  1330. let unlistenHistory = null;
  1331. let subscribers = /* @__PURE__ */ new Set();
  1332. let savedScrollPositions = null;
  1333. let getScrollRestorationKey = null;
  1334. let getScrollPosition = null;
  1335. let initialScrollRestored = init.hydrationData != null;
  1336. let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
  1337. let initialMatchesIsFOW = false;
  1338. let initialErrors = null;
  1339. let initialized;
  1340. if (initialMatches == null && !init.patchRoutesOnNavigation) {
  1341. let error = getInternalRouterError(404, {
  1342. pathname: init.history.location.pathname
  1343. });
  1344. let { matches, route } = getShortCircuitMatches(dataRoutes);
  1345. initialized = true;
  1346. initialMatches = matches;
  1347. initialErrors = { [route.id]: error };
  1348. } else {
  1349. if (initialMatches && !init.hydrationData) {
  1350. let fogOfWar = checkFogOfWar(
  1351. initialMatches,
  1352. dataRoutes,
  1353. init.history.location.pathname
  1354. );
  1355. if (fogOfWar.active) {
  1356. initialMatches = null;
  1357. }
  1358. }
  1359. if (!initialMatches) {
  1360. initialized = false;
  1361. initialMatches = [];
  1362. let fogOfWar = checkFogOfWar(
  1363. null,
  1364. dataRoutes,
  1365. init.history.location.pathname
  1366. );
  1367. if (fogOfWar.active && fogOfWar.matches) {
  1368. initialMatchesIsFOW = true;
  1369. initialMatches = fogOfWar.matches;
  1370. }
  1371. } else if (initialMatches.some((m) => m.route.lazy)) {
  1372. initialized = false;
  1373. } else if (!initialMatches.some((m) => routeHasLoaderOrMiddleware(m.route))) {
  1374. initialized = true;
  1375. } else {
  1376. let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
  1377. let errors = init.hydrationData ? init.hydrationData.errors : null;
  1378. if (errors) {
  1379. let idx = initialMatches.findIndex(
  1380. (m) => errors[m.route.id] !== void 0
  1381. );
  1382. initialized = initialMatches.slice(0, idx + 1).every(
  1383. (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)
  1384. );
  1385. } else {
  1386. initialized = initialMatches.every(
  1387. (m) => !shouldLoadRouteOnHydration(m.route, loaderData, errors)
  1388. );
  1389. }
  1390. }
  1391. }
  1392. let router;
  1393. let state = {
  1394. historyAction: init.history.action,
  1395. location: init.history.location,
  1396. matches: initialMatches,
  1397. initialized,
  1398. navigation: IDLE_NAVIGATION,
  1399. // Don't restore on initial updateState() if we were SSR'd
  1400. restoreScrollPosition: init.hydrationData != null ? false : null,
  1401. preventScrollReset: false,
  1402. revalidation: "idle",
  1403. loaderData: init.hydrationData && init.hydrationData.loaderData || {},
  1404. actionData: init.hydrationData && init.hydrationData.actionData || null,
  1405. errors: init.hydrationData && init.hydrationData.errors || initialErrors,
  1406. fetchers: /* @__PURE__ */ new Map(),
  1407. blockers: /* @__PURE__ */ new Map()
  1408. };
  1409. let pendingAction = "POP" /* Pop */;
  1410. let pendingPopstateNavigationDfd = null;
  1411. let pendingPreventScrollReset = false;
  1412. let pendingNavigationController;
  1413. let pendingViewTransitionEnabled = false;
  1414. let appliedViewTransitions = /* @__PURE__ */ new Map();
  1415. let removePageHideEventListener = null;
  1416. let isUninterruptedRevalidation = false;
  1417. let isRevalidationRequired = false;
  1418. let cancelledFetcherLoads = /* @__PURE__ */ new Set();
  1419. let fetchControllers = /* @__PURE__ */ new Map();
  1420. let incrementingLoadId = 0;
  1421. let pendingNavigationLoadId = -1;
  1422. let fetchReloadIds = /* @__PURE__ */ new Map();
  1423. let fetchRedirectIds = /* @__PURE__ */ new Set();
  1424. let fetchLoadMatches = /* @__PURE__ */ new Map();
  1425. let activeFetchers = /* @__PURE__ */ new Map();
  1426. let fetchersQueuedForDeletion = /* @__PURE__ */ new Set();
  1427. let blockerFunctions = /* @__PURE__ */ new Map();
  1428. let unblockBlockerHistoryUpdate = void 0;
  1429. let pendingRevalidationDfd = null;
  1430. function initialize() {
  1431. unlistenHistory = init.history.listen(
  1432. ({ action: historyAction, location, delta }) => {
  1433. if (unblockBlockerHistoryUpdate) {
  1434. unblockBlockerHistoryUpdate();
  1435. unblockBlockerHistoryUpdate = void 0;
  1436. return;
  1437. }
  1438. warning(
  1439. blockerFunctions.size === 0 || delta != null,
  1440. "You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL."
  1441. );
  1442. let blockerKey = shouldBlockNavigation({
  1443. currentLocation: state.location,
  1444. nextLocation: location,
  1445. historyAction
  1446. });
  1447. if (blockerKey && delta != null) {
  1448. let nextHistoryUpdatePromise = new Promise((resolve) => {
  1449. unblockBlockerHistoryUpdate = resolve;
  1450. });
  1451. init.history.go(delta * -1);
  1452. updateBlocker(blockerKey, {
  1453. state: "blocked",
  1454. location,
  1455. proceed() {
  1456. updateBlocker(blockerKey, {
  1457. state: "proceeding",
  1458. proceed: void 0,
  1459. reset: void 0,
  1460. location
  1461. });
  1462. nextHistoryUpdatePromise.then(() => init.history.go(delta));
  1463. },
  1464. reset() {
  1465. let blockers = new Map(state.blockers);
  1466. blockers.set(blockerKey, IDLE_BLOCKER);
  1467. updateState({ blockers });
  1468. }
  1469. });
  1470. _optionalChain([pendingPopstateNavigationDfd, 'optionalAccess', _5 => _5.resolve, 'call', _6 => _6()]);
  1471. pendingPopstateNavigationDfd = null;
  1472. return;
  1473. }
  1474. return startNavigation(historyAction, location);
  1475. }
  1476. );
  1477. if (isBrowser) {
  1478. restoreAppliedTransitions(routerWindow, appliedViewTransitions);
  1479. let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
  1480. routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
  1481. removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
  1482. }
  1483. if (!state.initialized) {
  1484. startNavigation("POP" /* Pop */, state.location, {
  1485. initialHydration: true
  1486. });
  1487. }
  1488. return router;
  1489. }
  1490. function dispose() {
  1491. if (unlistenHistory) {
  1492. unlistenHistory();
  1493. }
  1494. if (removePageHideEventListener) {
  1495. removePageHideEventListener();
  1496. }
  1497. subscribers.clear();
  1498. pendingNavigationController && pendingNavigationController.abort();
  1499. state.fetchers.forEach((_, key) => deleteFetcher(key));
  1500. state.blockers.forEach((_, key) => deleteBlocker(key));
  1501. }
  1502. function subscribe(fn) {
  1503. subscribers.add(fn);
  1504. return () => subscribers.delete(fn);
  1505. }
  1506. function updateState(newState, opts = {}) {
  1507. if (newState.matches) {
  1508. newState.matches = newState.matches.map((m) => {
  1509. let route = manifest[m.route.id];
  1510. let matchRoute = m.route;
  1511. if (matchRoute.element !== route.element || matchRoute.errorElement !== route.errorElement || matchRoute.hydrateFallbackElement !== route.hydrateFallbackElement) {
  1512. return {
  1513. ...m,
  1514. route
  1515. };
  1516. }
  1517. return m;
  1518. });
  1519. }
  1520. state = {
  1521. ...state,
  1522. ...newState
  1523. };
  1524. let unmountedFetchers = [];
  1525. let mountedFetchers = [];
  1526. state.fetchers.forEach((fetcher, key) => {
  1527. if (fetcher.state === "idle") {
  1528. if (fetchersQueuedForDeletion.has(key)) {
  1529. unmountedFetchers.push(key);
  1530. } else {
  1531. mountedFetchers.push(key);
  1532. }
  1533. }
  1534. });
  1535. fetchersQueuedForDeletion.forEach((key) => {
  1536. if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
  1537. unmountedFetchers.push(key);
  1538. }
  1539. });
  1540. [...subscribers].forEach(
  1541. (subscriber) => subscriber(state, {
  1542. deletedFetchers: unmountedFetchers,
  1543. newErrors: _nullishCoalesce(newState.errors, () => ( null)),
  1544. viewTransitionOpts: opts.viewTransitionOpts,
  1545. flushSync: opts.flushSync === true
  1546. })
  1547. );
  1548. unmountedFetchers.forEach((key) => deleteFetcher(key));
  1549. mountedFetchers.forEach((key) => state.fetchers.delete(key));
  1550. }
  1551. function completeNavigation(location, newState, { flushSync } = {}) {
  1552. let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && _optionalChain([location, 'access', _7 => _7.state, 'optionalAccess', _8 => _8._isRedirect]) !== true;
  1553. let actionData;
  1554. if (newState.actionData) {
  1555. if (Object.keys(newState.actionData).length > 0) {
  1556. actionData = newState.actionData;
  1557. } else {
  1558. actionData = null;
  1559. }
  1560. } else if (isActionReload) {
  1561. actionData = state.actionData;
  1562. } else {
  1563. actionData = null;
  1564. }
  1565. let loaderData = newState.loaderData ? mergeLoaderData(
  1566. state.loaderData,
  1567. newState.loaderData,
  1568. newState.matches || [],
  1569. newState.errors
  1570. ) : state.loaderData;
  1571. let blockers = state.blockers;
  1572. if (blockers.size > 0) {
  1573. blockers = new Map(blockers);
  1574. blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
  1575. }
  1576. let restoreScrollPosition = isUninterruptedRevalidation ? false : getSavedScrollPosition(location, newState.matches || state.matches);
  1577. let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && _optionalChain([location, 'access', _9 => _9.state, 'optionalAccess', _10 => _10._isRedirect]) !== true;
  1578. if (inFlightDataRoutes) {
  1579. dataRoutes = inFlightDataRoutes;
  1580. inFlightDataRoutes = void 0;
  1581. }
  1582. if (isUninterruptedRevalidation) {
  1583. } else if (pendingAction === "POP" /* Pop */) {
  1584. } else if (pendingAction === "PUSH" /* Push */) {
  1585. init.history.push(location, location.state);
  1586. } else if (pendingAction === "REPLACE" /* Replace */) {
  1587. init.history.replace(location, location.state);
  1588. }
  1589. let viewTransitionOpts;
  1590. if (pendingAction === "POP" /* Pop */) {
  1591. let priorPaths = appliedViewTransitions.get(state.location.pathname);
  1592. if (priorPaths && priorPaths.has(location.pathname)) {
  1593. viewTransitionOpts = {
  1594. currentLocation: state.location,
  1595. nextLocation: location
  1596. };
  1597. } else if (appliedViewTransitions.has(location.pathname)) {
  1598. viewTransitionOpts = {
  1599. currentLocation: location,
  1600. nextLocation: state.location
  1601. };
  1602. }
  1603. } else if (pendingViewTransitionEnabled) {
  1604. let toPaths = appliedViewTransitions.get(state.location.pathname);
  1605. if (toPaths) {
  1606. toPaths.add(location.pathname);
  1607. } else {
  1608. toPaths = /* @__PURE__ */ new Set([location.pathname]);
  1609. appliedViewTransitions.set(state.location.pathname, toPaths);
  1610. }
  1611. viewTransitionOpts = {
  1612. currentLocation: state.location,
  1613. nextLocation: location
  1614. };
  1615. }
  1616. updateState(
  1617. {
  1618. ...newState,
  1619. // matches, errors, fetchers go through as-is
  1620. actionData,
  1621. loaderData,
  1622. historyAction: pendingAction,
  1623. location,
  1624. initialized: true,
  1625. navigation: IDLE_NAVIGATION,
  1626. revalidation: "idle",
  1627. restoreScrollPosition,
  1628. preventScrollReset,
  1629. blockers
  1630. },
  1631. {
  1632. viewTransitionOpts,
  1633. flushSync: flushSync === true
  1634. }
  1635. );
  1636. pendingAction = "POP" /* Pop */;
  1637. pendingPreventScrollReset = false;
  1638. pendingViewTransitionEnabled = false;
  1639. isUninterruptedRevalidation = false;
  1640. isRevalidationRequired = false;
  1641. _optionalChain([pendingPopstateNavigationDfd, 'optionalAccess', _11 => _11.resolve, 'call', _12 => _12()]);
  1642. pendingPopstateNavigationDfd = null;
  1643. _optionalChain([pendingRevalidationDfd, 'optionalAccess', _13 => _13.resolve, 'call', _14 => _14()]);
  1644. pendingRevalidationDfd = null;
  1645. }
  1646. async function navigate(to, opts) {
  1647. _optionalChain([pendingPopstateNavigationDfd, 'optionalAccess', _15 => _15.resolve, 'call', _16 => _16()]);
  1648. pendingPopstateNavigationDfd = null;
  1649. if (typeof to === "number") {
  1650. if (!pendingPopstateNavigationDfd) {
  1651. pendingPopstateNavigationDfd = createDeferred();
  1652. }
  1653. let promise = pendingPopstateNavigationDfd.promise;
  1654. init.history.go(to);
  1655. return promise;
  1656. }
  1657. let normalizedPath = normalizeTo(
  1658. state.location,
  1659. state.matches,
  1660. basename,
  1661. to,
  1662. _optionalChain([opts, 'optionalAccess', _17 => _17.fromRouteId]),
  1663. _optionalChain([opts, 'optionalAccess', _18 => _18.relative])
  1664. );
  1665. let { path, submission, error } = normalizeNavigateOptions(
  1666. false,
  1667. normalizedPath,
  1668. opts
  1669. );
  1670. let currentLocation = state.location;
  1671. let nextLocation = createLocation(state.location, path, opts && opts.state);
  1672. nextLocation = {
  1673. ...nextLocation,
  1674. ...init.history.encodeLocation(nextLocation)
  1675. };
  1676. let userReplace = opts && opts.replace != null ? opts.replace : void 0;
  1677. let historyAction = "PUSH" /* Push */;
  1678. if (userReplace === true) {
  1679. historyAction = "REPLACE" /* Replace */;
  1680. } else if (userReplace === false) {
  1681. } else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
  1682. historyAction = "REPLACE" /* Replace */;
  1683. }
  1684. let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0;
  1685. let flushSync = (opts && opts.flushSync) === true;
  1686. let blockerKey = shouldBlockNavigation({
  1687. currentLocation,
  1688. nextLocation,
  1689. historyAction
  1690. });
  1691. if (blockerKey) {
  1692. updateBlocker(blockerKey, {
  1693. state: "blocked",
  1694. location: nextLocation,
  1695. proceed() {
  1696. updateBlocker(blockerKey, {
  1697. state: "proceeding",
  1698. proceed: void 0,
  1699. reset: void 0,
  1700. location: nextLocation
  1701. });
  1702. navigate(to, opts);
  1703. },
  1704. reset() {
  1705. let blockers = new Map(state.blockers);
  1706. blockers.set(blockerKey, IDLE_BLOCKER);
  1707. updateState({ blockers });
  1708. }
  1709. });
  1710. return;
  1711. }
  1712. await startNavigation(historyAction, nextLocation, {
  1713. submission,
  1714. // Send through the formData serialization error if we have one so we can
  1715. // render at the right error boundary after we match routes
  1716. pendingError: error,
  1717. preventScrollReset,
  1718. replace: opts && opts.replace,
  1719. enableViewTransition: opts && opts.viewTransition,
  1720. flushSync
  1721. });
  1722. }
  1723. function revalidate() {
  1724. if (!pendingRevalidationDfd) {
  1725. pendingRevalidationDfd = createDeferred();
  1726. }
  1727. interruptActiveLoads();
  1728. updateState({ revalidation: "loading" });
  1729. let promise = pendingRevalidationDfd.promise;
  1730. if (state.navigation.state === "submitting") {
  1731. return promise;
  1732. }
  1733. if (state.navigation.state === "idle") {
  1734. startNavigation(state.historyAction, state.location, {
  1735. startUninterruptedRevalidation: true
  1736. });
  1737. return promise;
  1738. }
  1739. startNavigation(
  1740. pendingAction || state.historyAction,
  1741. state.navigation.location,
  1742. {
  1743. overrideNavigation: state.navigation,
  1744. // Proxy through any rending view transition
  1745. enableViewTransition: pendingViewTransitionEnabled === true
  1746. }
  1747. );
  1748. return promise;
  1749. }
  1750. async function startNavigation(historyAction, location, opts) {
  1751. pendingNavigationController && pendingNavigationController.abort();
  1752. pendingNavigationController = null;
  1753. pendingAction = historyAction;
  1754. isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
  1755. saveScrollPosition(state.location, state.matches);
  1756. pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
  1757. pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
  1758. let routesToUse = inFlightDataRoutes || dataRoutes;
  1759. let loadingNavigation = opts && opts.overrideNavigation;
  1760. let matches = _optionalChain([opts, 'optionalAccess', _19 => _19.initialHydration]) && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ? (
  1761. // `matchRoutes()` has already been called if we're in here via `router.initialize()`
  1762. state.matches
  1763. ) : matchRoutes(routesToUse, location, basename);
  1764. let flushSync = (opts && opts.flushSync) === true;
  1765. if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
  1766. completeNavigation(location, { matches }, { flushSync });
  1767. return;
  1768. }
  1769. let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
  1770. if (fogOfWar.active && fogOfWar.matches) {
  1771. matches = fogOfWar.matches;
  1772. }
  1773. if (!matches) {
  1774. let { error, notFoundMatches, route } = handleNavigational404(
  1775. location.pathname
  1776. );
  1777. completeNavigation(
  1778. location,
  1779. {
  1780. matches: notFoundMatches,
  1781. loaderData: {},
  1782. errors: {
  1783. [route.id]: error
  1784. }
  1785. },
  1786. { flushSync }
  1787. );
  1788. return;
  1789. }
  1790. pendingNavigationController = new AbortController();
  1791. let request = createClientSideRequest(
  1792. init.history,
  1793. location,
  1794. pendingNavigationController.signal,
  1795. opts && opts.submission
  1796. );
  1797. let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
  1798. let pendingActionResult;
  1799. if (opts && opts.pendingError) {
  1800. pendingActionResult = [
  1801. findNearestBoundary(matches).route.id,
  1802. { type: "error" /* error */, error: opts.pendingError }
  1803. ];
  1804. } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
  1805. let actionResult = await handleAction(
  1806. request,
  1807. location,
  1808. opts.submission,
  1809. matches,
  1810. scopedContext,
  1811. fogOfWar.active,
  1812. opts && opts.initialHydration === true,
  1813. { replace: opts.replace, flushSync }
  1814. );
  1815. if (actionResult.shortCircuited) {
  1816. return;
  1817. }
  1818. if (actionResult.pendingActionResult) {
  1819. let [routeId, result] = actionResult.pendingActionResult;
  1820. if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
  1821. pendingNavigationController = null;
  1822. completeNavigation(location, {
  1823. matches: actionResult.matches,
  1824. loaderData: {},
  1825. errors: {
  1826. [routeId]: result.error
  1827. }
  1828. });
  1829. return;
  1830. }
  1831. }
  1832. matches = actionResult.matches || matches;
  1833. pendingActionResult = actionResult.pendingActionResult;
  1834. loadingNavigation = getLoadingNavigation(location, opts.submission);
  1835. flushSync = false;
  1836. fogOfWar.active = false;
  1837. request = createClientSideRequest(
  1838. init.history,
  1839. request.url,
  1840. request.signal
  1841. );
  1842. }
  1843. let {
  1844. shortCircuited,
  1845. matches: updatedMatches,
  1846. loaderData,
  1847. errors
  1848. } = await handleLoaders(
  1849. request,
  1850. location,
  1851. matches,
  1852. scopedContext,
  1853. fogOfWar.active,
  1854. loadingNavigation,
  1855. opts && opts.submission,
  1856. opts && opts.fetcherSubmission,
  1857. opts && opts.replace,
  1858. opts && opts.initialHydration === true,
  1859. flushSync,
  1860. pendingActionResult
  1861. );
  1862. if (shortCircuited) {
  1863. return;
  1864. }
  1865. pendingNavigationController = null;
  1866. completeNavigation(location, {
  1867. matches: updatedMatches || matches,
  1868. ...getActionDataForCommit(pendingActionResult),
  1869. loaderData,
  1870. errors
  1871. });
  1872. }
  1873. async function handleAction(request, location, submission, matches, scopedContext, isFogOfWar, initialHydration, opts = {}) {
  1874. interruptActiveLoads();
  1875. let navigation = getSubmittingNavigation(location, submission);
  1876. updateState({ navigation }, { flushSync: opts.flushSync === true });
  1877. if (isFogOfWar) {
  1878. let discoverResult = await discoverRoutes(
  1879. matches,
  1880. location.pathname,
  1881. request.signal
  1882. );
  1883. if (discoverResult.type === "aborted") {
  1884. return { shortCircuited: true };
  1885. } else if (discoverResult.type === "error") {
  1886. if (discoverResult.partialMatches.length === 0) {
  1887. let { matches: matches2, route } = getShortCircuitMatches(dataRoutes);
  1888. return {
  1889. matches: matches2,
  1890. pendingActionResult: [
  1891. route.id,
  1892. {
  1893. type: "error" /* error */,
  1894. error: discoverResult.error
  1895. }
  1896. ]
  1897. };
  1898. }
  1899. let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
  1900. return {
  1901. matches: discoverResult.partialMatches,
  1902. pendingActionResult: [
  1903. boundaryId,
  1904. {
  1905. type: "error" /* error */,
  1906. error: discoverResult.error
  1907. }
  1908. ]
  1909. };
  1910. } else if (!discoverResult.matches) {
  1911. let { notFoundMatches, error, route } = handleNavigational404(
  1912. location.pathname
  1913. );
  1914. return {
  1915. matches: notFoundMatches,
  1916. pendingActionResult: [
  1917. route.id,
  1918. {
  1919. type: "error" /* error */,
  1920. error
  1921. }
  1922. ]
  1923. };
  1924. } else {
  1925. matches = discoverResult.matches;
  1926. }
  1927. }
  1928. let result;
  1929. let actionMatch = getTargetMatch(matches, location);
  1930. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  1931. result = {
  1932. type: "error" /* error */,
  1933. error: getInternalRouterError(405, {
  1934. method: request.method,
  1935. pathname: location.pathname,
  1936. routeId: actionMatch.route.id
  1937. })
  1938. };
  1939. } else {
  1940. let dsMatches = getTargetedDataStrategyMatches(
  1941. mapRouteProperties2,
  1942. manifest,
  1943. request,
  1944. matches,
  1945. actionMatch,
  1946. initialHydration ? [] : hydrationRouteProperties2,
  1947. scopedContext
  1948. );
  1949. let results = await callDataStrategy(
  1950. request,
  1951. dsMatches,
  1952. scopedContext,
  1953. null
  1954. );
  1955. result = results[actionMatch.route.id];
  1956. if (!result) {
  1957. for (let match of matches) {
  1958. if (results[match.route.id]) {
  1959. result = results[match.route.id];
  1960. break;
  1961. }
  1962. }
  1963. }
  1964. if (request.signal.aborted) {
  1965. return { shortCircuited: true };
  1966. }
  1967. }
  1968. if (isRedirectResult(result)) {
  1969. let replace2;
  1970. if (opts && opts.replace != null) {
  1971. replace2 = opts.replace;
  1972. } else {
  1973. let location2 = normalizeRedirectLocation(
  1974. result.response.headers.get("Location"),
  1975. new URL(request.url),
  1976. basename
  1977. );
  1978. replace2 = location2 === state.location.pathname + state.location.search;
  1979. }
  1980. await startRedirectNavigation(request, result, true, {
  1981. submission,
  1982. replace: replace2
  1983. });
  1984. return { shortCircuited: true };
  1985. }
  1986. if (isErrorResult(result)) {
  1987. let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
  1988. if ((opts && opts.replace) !== true) {
  1989. pendingAction = "PUSH" /* Push */;
  1990. }
  1991. return {
  1992. matches,
  1993. pendingActionResult: [
  1994. boundaryMatch.route.id,
  1995. result,
  1996. actionMatch.route.id
  1997. ]
  1998. };
  1999. }
  2000. return {
  2001. matches,
  2002. pendingActionResult: [actionMatch.route.id, result]
  2003. };
  2004. }
  2005. async function handleLoaders(request, location, matches, scopedContext, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace2, initialHydration, flushSync, pendingActionResult) {
  2006. let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
  2007. let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
  2008. let shouldUpdateNavigationState = !isUninterruptedRevalidation && !initialHydration;
  2009. if (isFogOfWar) {
  2010. if (shouldUpdateNavigationState) {
  2011. let actionData = getUpdatedActionData(pendingActionResult);
  2012. updateState(
  2013. {
  2014. navigation: loadingNavigation,
  2015. ...actionData !== void 0 ? { actionData } : {}
  2016. },
  2017. {
  2018. flushSync
  2019. }
  2020. );
  2021. }
  2022. let discoverResult = await discoverRoutes(
  2023. matches,
  2024. location.pathname,
  2025. request.signal
  2026. );
  2027. if (discoverResult.type === "aborted") {
  2028. return { shortCircuited: true };
  2029. } else if (discoverResult.type === "error") {
  2030. if (discoverResult.partialMatches.length === 0) {
  2031. let { matches: matches2, route } = getShortCircuitMatches(dataRoutes);
  2032. return {
  2033. matches: matches2,
  2034. loaderData: {},
  2035. errors: {
  2036. [route.id]: discoverResult.error
  2037. }
  2038. };
  2039. }
  2040. let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
  2041. return {
  2042. matches: discoverResult.partialMatches,
  2043. loaderData: {},
  2044. errors: {
  2045. [boundaryId]: discoverResult.error
  2046. }
  2047. };
  2048. } else if (!discoverResult.matches) {
  2049. let { error, notFoundMatches, route } = handleNavigational404(
  2050. location.pathname
  2051. );
  2052. return {
  2053. matches: notFoundMatches,
  2054. loaderData: {},
  2055. errors: {
  2056. [route.id]: error
  2057. }
  2058. };
  2059. } else {
  2060. matches = discoverResult.matches;
  2061. }
  2062. }
  2063. let routesToUse = inFlightDataRoutes || dataRoutes;
  2064. let { dsMatches, revalidatingFetchers } = getMatchesToLoad(
  2065. request,
  2066. scopedContext,
  2067. mapRouteProperties2,
  2068. manifest,
  2069. init.history,
  2070. state,
  2071. matches,
  2072. activeSubmission,
  2073. location,
  2074. initialHydration ? [] : hydrationRouteProperties2,
  2075. initialHydration === true,
  2076. isRevalidationRequired,
  2077. cancelledFetcherLoads,
  2078. fetchersQueuedForDeletion,
  2079. fetchLoadMatches,
  2080. fetchRedirectIds,
  2081. routesToUse,
  2082. basename,
  2083. init.patchRoutesOnNavigation != null,
  2084. pendingActionResult
  2085. );
  2086. pendingNavigationLoadId = ++incrementingLoadId;
  2087. if (!init.dataStrategy && !dsMatches.some((m) => m.shouldLoad) && !dsMatches.some(
  2088. (m) => m.route.middleware && m.route.middleware.length > 0
  2089. ) && revalidatingFetchers.length === 0) {
  2090. let updatedFetchers2 = markFetchRedirectsDone();
  2091. completeNavigation(
  2092. location,
  2093. {
  2094. matches,
  2095. loaderData: {},
  2096. // Commit pending error if we're short circuiting
  2097. errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null,
  2098. ...getActionDataForCommit(pendingActionResult),
  2099. ...updatedFetchers2 ? { fetchers: new Map(state.fetchers) } : {}
  2100. },
  2101. { flushSync }
  2102. );
  2103. return { shortCircuited: true };
  2104. }
  2105. if (shouldUpdateNavigationState) {
  2106. let updates = {};
  2107. if (!isFogOfWar) {
  2108. updates.navigation = loadingNavigation;
  2109. let actionData = getUpdatedActionData(pendingActionResult);
  2110. if (actionData !== void 0) {
  2111. updates.actionData = actionData;
  2112. }
  2113. }
  2114. if (revalidatingFetchers.length > 0) {
  2115. updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
  2116. }
  2117. updateState(updates, { flushSync });
  2118. }
  2119. revalidatingFetchers.forEach((rf) => {
  2120. abortFetcher(rf.key);
  2121. if (rf.controller) {
  2122. fetchControllers.set(rf.key, rf.controller);
  2123. }
  2124. });
  2125. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((f) => abortFetcher(f.key));
  2126. if (pendingNavigationController) {
  2127. pendingNavigationController.signal.addEventListener(
  2128. "abort",
  2129. abortPendingFetchRevalidations
  2130. );
  2131. }
  2132. let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
  2133. dsMatches,
  2134. revalidatingFetchers,
  2135. request,
  2136. scopedContext
  2137. );
  2138. if (request.signal.aborted) {
  2139. return { shortCircuited: true };
  2140. }
  2141. if (pendingNavigationController) {
  2142. pendingNavigationController.signal.removeEventListener(
  2143. "abort",
  2144. abortPendingFetchRevalidations
  2145. );
  2146. }
  2147. revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));
  2148. let redirect2 = findRedirect(loaderResults);
  2149. if (redirect2) {
  2150. await startRedirectNavigation(request, redirect2.result, true, {
  2151. replace: replace2
  2152. });
  2153. return { shortCircuited: true };
  2154. }
  2155. redirect2 = findRedirect(fetcherResults);
  2156. if (redirect2) {
  2157. fetchRedirectIds.add(redirect2.key);
  2158. await startRedirectNavigation(request, redirect2.result, true, {
  2159. replace: replace2
  2160. });
  2161. return { shortCircuited: true };
  2162. }
  2163. let { loaderData, errors } = processLoaderData(
  2164. state,
  2165. matches,
  2166. loaderResults,
  2167. pendingActionResult,
  2168. revalidatingFetchers,
  2169. fetcherResults
  2170. );
  2171. if (initialHydration && state.errors) {
  2172. errors = { ...state.errors, ...errors };
  2173. }
  2174. let updatedFetchers = markFetchRedirectsDone();
  2175. let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
  2176. let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
  2177. return {
  2178. matches,
  2179. loaderData,
  2180. errors,
  2181. ...shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}
  2182. };
  2183. }
  2184. function getUpdatedActionData(pendingActionResult) {
  2185. if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
  2186. return {
  2187. [pendingActionResult[0]]: pendingActionResult[1].data
  2188. };
  2189. } else if (state.actionData) {
  2190. if (Object.keys(state.actionData).length === 0) {
  2191. return null;
  2192. } else {
  2193. return state.actionData;
  2194. }
  2195. }
  2196. }
  2197. function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
  2198. revalidatingFetchers.forEach((rf) => {
  2199. let fetcher = state.fetchers.get(rf.key);
  2200. let revalidatingFetcher = getLoadingFetcher(
  2201. void 0,
  2202. fetcher ? fetcher.data : void 0
  2203. );
  2204. state.fetchers.set(rf.key, revalidatingFetcher);
  2205. });
  2206. return new Map(state.fetchers);
  2207. }
  2208. async function fetch2(key, routeId, href, opts) {
  2209. abortFetcher(key);
  2210. let flushSync = (opts && opts.flushSync) === true;
  2211. let routesToUse = inFlightDataRoutes || dataRoutes;
  2212. let normalizedPath = normalizeTo(
  2213. state.location,
  2214. state.matches,
  2215. basename,
  2216. href,
  2217. routeId,
  2218. _optionalChain([opts, 'optionalAccess', _20 => _20.relative])
  2219. );
  2220. let matches = matchRoutes(routesToUse, normalizedPath, basename);
  2221. let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
  2222. if (fogOfWar.active && fogOfWar.matches) {
  2223. matches = fogOfWar.matches;
  2224. }
  2225. if (!matches) {
  2226. setFetcherError(
  2227. key,
  2228. routeId,
  2229. getInternalRouterError(404, { pathname: normalizedPath }),
  2230. { flushSync }
  2231. );
  2232. return;
  2233. }
  2234. let { path, submission, error } = normalizeNavigateOptions(
  2235. true,
  2236. normalizedPath,
  2237. opts
  2238. );
  2239. if (error) {
  2240. setFetcherError(key, routeId, error, { flushSync });
  2241. return;
  2242. }
  2243. let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
  2244. let preventScrollReset = (opts && opts.preventScrollReset) === true;
  2245. if (submission && isMutationMethod(submission.formMethod)) {
  2246. await handleFetcherAction(
  2247. key,
  2248. routeId,
  2249. path,
  2250. matches,
  2251. scopedContext,
  2252. fogOfWar.active,
  2253. flushSync,
  2254. preventScrollReset,
  2255. submission
  2256. );
  2257. return;
  2258. }
  2259. fetchLoadMatches.set(key, { routeId, path });
  2260. await handleFetcherLoader(
  2261. key,
  2262. routeId,
  2263. path,
  2264. matches,
  2265. scopedContext,
  2266. fogOfWar.active,
  2267. flushSync,
  2268. preventScrollReset,
  2269. submission
  2270. );
  2271. }
  2272. async function handleFetcherAction(key, routeId, path, requestMatches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission) {
  2273. interruptActiveLoads();
  2274. fetchLoadMatches.delete(key);
  2275. let existingFetcher = state.fetchers.get(key);
  2276. updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
  2277. flushSync
  2278. });
  2279. let abortController = new AbortController();
  2280. let fetchRequest = createClientSideRequest(
  2281. init.history,
  2282. path,
  2283. abortController.signal,
  2284. submission
  2285. );
  2286. if (isFogOfWar) {
  2287. let discoverResult = await discoverRoutes(
  2288. requestMatches,
  2289. new URL(fetchRequest.url).pathname,
  2290. fetchRequest.signal,
  2291. key
  2292. );
  2293. if (discoverResult.type === "aborted") {
  2294. return;
  2295. } else if (discoverResult.type === "error") {
  2296. setFetcherError(key, routeId, discoverResult.error, { flushSync });
  2297. return;
  2298. } else if (!discoverResult.matches) {
  2299. setFetcherError(
  2300. key,
  2301. routeId,
  2302. getInternalRouterError(404, { pathname: path }),
  2303. { flushSync }
  2304. );
  2305. return;
  2306. } else {
  2307. requestMatches = discoverResult.matches;
  2308. }
  2309. }
  2310. let match = getTargetMatch(requestMatches, path);
  2311. if (!match.route.action && !match.route.lazy) {
  2312. let error = getInternalRouterError(405, {
  2313. method: submission.formMethod,
  2314. pathname: path,
  2315. routeId
  2316. });
  2317. setFetcherError(key, routeId, error, { flushSync });
  2318. return;
  2319. }
  2320. fetchControllers.set(key, abortController);
  2321. let originatingLoadId = incrementingLoadId;
  2322. let fetchMatches = getTargetedDataStrategyMatches(
  2323. mapRouteProperties2,
  2324. manifest,
  2325. fetchRequest,
  2326. requestMatches,
  2327. match,
  2328. hydrationRouteProperties2,
  2329. scopedContext
  2330. );
  2331. let actionResults = await callDataStrategy(
  2332. fetchRequest,
  2333. fetchMatches,
  2334. scopedContext,
  2335. key
  2336. );
  2337. let actionResult = actionResults[match.route.id];
  2338. if (!actionResult) {
  2339. for (let match2 of fetchMatches) {
  2340. if (actionResults[match2.route.id]) {
  2341. actionResult = actionResults[match2.route.id];
  2342. break;
  2343. }
  2344. }
  2345. }
  2346. if (fetchRequest.signal.aborted) {
  2347. if (fetchControllers.get(key) === abortController) {
  2348. fetchControllers.delete(key);
  2349. }
  2350. return;
  2351. }
  2352. if (fetchersQueuedForDeletion.has(key)) {
  2353. if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
  2354. updateFetcherState(key, getDoneFetcher(void 0));
  2355. return;
  2356. }
  2357. } else {
  2358. if (isRedirectResult(actionResult)) {
  2359. fetchControllers.delete(key);
  2360. if (pendingNavigationLoadId > originatingLoadId) {
  2361. updateFetcherState(key, getDoneFetcher(void 0));
  2362. return;
  2363. } else {
  2364. fetchRedirectIds.add(key);
  2365. updateFetcherState(key, getLoadingFetcher(submission));
  2366. return startRedirectNavigation(fetchRequest, actionResult, false, {
  2367. fetcherSubmission: submission,
  2368. preventScrollReset
  2369. });
  2370. }
  2371. }
  2372. if (isErrorResult(actionResult)) {
  2373. setFetcherError(key, routeId, actionResult.error);
  2374. return;
  2375. }
  2376. }
  2377. let nextLocation = state.navigation.location || state.location;
  2378. let revalidationRequest = createClientSideRequest(
  2379. init.history,
  2380. nextLocation,
  2381. abortController.signal
  2382. );
  2383. let routesToUse = inFlightDataRoutes || dataRoutes;
  2384. let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
  2385. invariant(matches, "Didn't find any matches after fetcher action");
  2386. let loadId = ++incrementingLoadId;
  2387. fetchReloadIds.set(key, loadId);
  2388. let loadFetcher = getLoadingFetcher(submission, actionResult.data);
  2389. state.fetchers.set(key, loadFetcher);
  2390. let { dsMatches, revalidatingFetchers } = getMatchesToLoad(
  2391. revalidationRequest,
  2392. scopedContext,
  2393. mapRouteProperties2,
  2394. manifest,
  2395. init.history,
  2396. state,
  2397. matches,
  2398. submission,
  2399. nextLocation,
  2400. hydrationRouteProperties2,
  2401. false,
  2402. isRevalidationRequired,
  2403. cancelledFetcherLoads,
  2404. fetchersQueuedForDeletion,
  2405. fetchLoadMatches,
  2406. fetchRedirectIds,
  2407. routesToUse,
  2408. basename,
  2409. init.patchRoutesOnNavigation != null,
  2410. [match.route.id, actionResult]
  2411. );
  2412. revalidatingFetchers.filter((rf) => rf.key !== key).forEach((rf) => {
  2413. let staleKey = rf.key;
  2414. let existingFetcher2 = state.fetchers.get(staleKey);
  2415. let revalidatingFetcher = getLoadingFetcher(
  2416. void 0,
  2417. existingFetcher2 ? existingFetcher2.data : void 0
  2418. );
  2419. state.fetchers.set(staleKey, revalidatingFetcher);
  2420. abortFetcher(staleKey);
  2421. if (rf.controller) {
  2422. fetchControllers.set(staleKey, rf.controller);
  2423. }
  2424. });
  2425. updateState({ fetchers: new Map(state.fetchers) });
  2426. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));
  2427. abortController.signal.addEventListener(
  2428. "abort",
  2429. abortPendingFetchRevalidations
  2430. );
  2431. let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(
  2432. dsMatches,
  2433. revalidatingFetchers,
  2434. revalidationRequest,
  2435. scopedContext
  2436. );
  2437. if (abortController.signal.aborted) {
  2438. return;
  2439. }
  2440. abortController.signal.removeEventListener(
  2441. "abort",
  2442. abortPendingFetchRevalidations
  2443. );
  2444. fetchReloadIds.delete(key);
  2445. fetchControllers.delete(key);
  2446. revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));
  2447. if (state.fetchers.has(key)) {
  2448. let doneFetcher = getDoneFetcher(actionResult.data);
  2449. state.fetchers.set(key, doneFetcher);
  2450. }
  2451. let redirect2 = findRedirect(loaderResults);
  2452. if (redirect2) {
  2453. return startRedirectNavigation(
  2454. revalidationRequest,
  2455. redirect2.result,
  2456. false,
  2457. { preventScrollReset }
  2458. );
  2459. }
  2460. redirect2 = findRedirect(fetcherResults);
  2461. if (redirect2) {
  2462. fetchRedirectIds.add(redirect2.key);
  2463. return startRedirectNavigation(
  2464. revalidationRequest,
  2465. redirect2.result,
  2466. false,
  2467. { preventScrollReset }
  2468. );
  2469. }
  2470. let { loaderData, errors } = processLoaderData(
  2471. state,
  2472. matches,
  2473. loaderResults,
  2474. void 0,
  2475. revalidatingFetchers,
  2476. fetcherResults
  2477. );
  2478. abortStaleFetchLoads(loadId);
  2479. if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
  2480. invariant(pendingAction, "Expected pending action");
  2481. pendingNavigationController && pendingNavigationController.abort();
  2482. completeNavigation(state.navigation.location, {
  2483. matches,
  2484. loaderData,
  2485. errors,
  2486. fetchers: new Map(state.fetchers)
  2487. });
  2488. } else {
  2489. updateState({
  2490. errors,
  2491. loaderData: mergeLoaderData(
  2492. state.loaderData,
  2493. loaderData,
  2494. matches,
  2495. errors
  2496. ),
  2497. fetchers: new Map(state.fetchers)
  2498. });
  2499. isRevalidationRequired = false;
  2500. }
  2501. }
  2502. async function handleFetcherLoader(key, routeId, path, matches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission) {
  2503. let existingFetcher = state.fetchers.get(key);
  2504. updateFetcherState(
  2505. key,
  2506. getLoadingFetcher(
  2507. submission,
  2508. existingFetcher ? existingFetcher.data : void 0
  2509. ),
  2510. { flushSync }
  2511. );
  2512. let abortController = new AbortController();
  2513. let fetchRequest = createClientSideRequest(
  2514. init.history,
  2515. path,
  2516. abortController.signal
  2517. );
  2518. if (isFogOfWar) {
  2519. let discoverResult = await discoverRoutes(
  2520. matches,
  2521. new URL(fetchRequest.url).pathname,
  2522. fetchRequest.signal,
  2523. key
  2524. );
  2525. if (discoverResult.type === "aborted") {
  2526. return;
  2527. } else if (discoverResult.type === "error") {
  2528. setFetcherError(key, routeId, discoverResult.error, { flushSync });
  2529. return;
  2530. } else if (!discoverResult.matches) {
  2531. setFetcherError(
  2532. key,
  2533. routeId,
  2534. getInternalRouterError(404, { pathname: path }),
  2535. { flushSync }
  2536. );
  2537. return;
  2538. } else {
  2539. matches = discoverResult.matches;
  2540. }
  2541. }
  2542. let match = getTargetMatch(matches, path);
  2543. fetchControllers.set(key, abortController);
  2544. let originatingLoadId = incrementingLoadId;
  2545. let dsMatches = getTargetedDataStrategyMatches(
  2546. mapRouteProperties2,
  2547. manifest,
  2548. fetchRequest,
  2549. matches,
  2550. match,
  2551. hydrationRouteProperties2,
  2552. scopedContext
  2553. );
  2554. let results = await callDataStrategy(
  2555. fetchRequest,
  2556. dsMatches,
  2557. scopedContext,
  2558. key
  2559. );
  2560. let result = results[match.route.id];
  2561. if (fetchControllers.get(key) === abortController) {
  2562. fetchControllers.delete(key);
  2563. }
  2564. if (fetchRequest.signal.aborted) {
  2565. return;
  2566. }
  2567. if (fetchersQueuedForDeletion.has(key)) {
  2568. updateFetcherState(key, getDoneFetcher(void 0));
  2569. return;
  2570. }
  2571. if (isRedirectResult(result)) {
  2572. if (pendingNavigationLoadId > originatingLoadId) {
  2573. updateFetcherState(key, getDoneFetcher(void 0));
  2574. return;
  2575. } else {
  2576. fetchRedirectIds.add(key);
  2577. await startRedirectNavigation(fetchRequest, result, false, {
  2578. preventScrollReset
  2579. });
  2580. return;
  2581. }
  2582. }
  2583. if (isErrorResult(result)) {
  2584. setFetcherError(key, routeId, result.error);
  2585. return;
  2586. }
  2587. updateFetcherState(key, getDoneFetcher(result.data));
  2588. }
  2589. async function startRedirectNavigation(request, redirect2, isNavigation, {
  2590. submission,
  2591. fetcherSubmission,
  2592. preventScrollReset,
  2593. replace: replace2
  2594. } = {}) {
  2595. if (!isNavigation) {
  2596. _optionalChain([pendingPopstateNavigationDfd, 'optionalAccess', _21 => _21.resolve, 'call', _22 => _22()]);
  2597. pendingPopstateNavigationDfd = null;
  2598. }
  2599. if (redirect2.response.headers.has("X-Remix-Revalidate")) {
  2600. isRevalidationRequired = true;
  2601. }
  2602. let location = redirect2.response.headers.get("Location");
  2603. invariant(location, "Expected a Location header on the redirect Response");
  2604. location = normalizeRedirectLocation(
  2605. location,
  2606. new URL(request.url),
  2607. basename
  2608. );
  2609. let redirectLocation = createLocation(state.location, location, {
  2610. _isRedirect: true
  2611. });
  2612. if (isBrowser) {
  2613. let isDocumentReload = false;
  2614. if (redirect2.response.headers.has("X-Remix-Reload-Document")) {
  2615. isDocumentReload = true;
  2616. } else if (isAbsoluteUrl(location)) {
  2617. const url = createBrowserURLImpl(location, true);
  2618. isDocumentReload = // Hard reload if it's an absolute URL to a new origin
  2619. url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename
  2620. stripBasename(url.pathname, basename) == null;
  2621. }
  2622. if (isDocumentReload) {
  2623. if (replace2) {
  2624. routerWindow.location.replace(location);
  2625. } else {
  2626. routerWindow.location.assign(location);
  2627. }
  2628. return;
  2629. }
  2630. }
  2631. pendingNavigationController = null;
  2632. let redirectNavigationType = replace2 === true || redirect2.response.headers.has("X-Remix-Replace") ? "REPLACE" /* Replace */ : "PUSH" /* Push */;
  2633. let { formMethod, formAction, formEncType } = state.navigation;
  2634. if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
  2635. submission = getSubmissionFromNavigation(state.navigation);
  2636. }
  2637. let activeSubmission = submission || fetcherSubmission;
  2638. if (redirectPreserveMethodStatusCodes.has(redirect2.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
  2639. await startNavigation(redirectNavigationType, redirectLocation, {
  2640. submission: {
  2641. ...activeSubmission,
  2642. formAction: location
  2643. },
  2644. // Preserve these flags across redirects
  2645. preventScrollReset: preventScrollReset || pendingPreventScrollReset,
  2646. enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
  2647. });
  2648. } else {
  2649. let overrideNavigation = getLoadingNavigation(
  2650. redirectLocation,
  2651. submission
  2652. );
  2653. await startNavigation(redirectNavigationType, redirectLocation, {
  2654. overrideNavigation,
  2655. // Send fetcher submissions through for shouldRevalidate
  2656. fetcherSubmission,
  2657. // Preserve these flags across redirects
  2658. preventScrollReset: preventScrollReset || pendingPreventScrollReset,
  2659. enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0
  2660. });
  2661. }
  2662. }
  2663. async function callDataStrategy(request, matches, scopedContext, fetcherKey) {
  2664. let results;
  2665. let dataResults = {};
  2666. try {
  2667. results = await callDataStrategyImpl(
  2668. dataStrategyImpl,
  2669. request,
  2670. matches,
  2671. fetcherKey,
  2672. scopedContext,
  2673. false
  2674. );
  2675. } catch (e) {
  2676. matches.filter((m) => m.shouldLoad).forEach((m) => {
  2677. dataResults[m.route.id] = {
  2678. type: "error" /* error */,
  2679. error: e
  2680. };
  2681. });
  2682. return dataResults;
  2683. }
  2684. if (request.signal.aborted) {
  2685. return dataResults;
  2686. }
  2687. for (let [routeId, result] of Object.entries(results)) {
  2688. if (isRedirectDataStrategyResult(result)) {
  2689. let response = result.result;
  2690. dataResults[routeId] = {
  2691. type: "redirect" /* redirect */,
  2692. response: normalizeRelativeRoutingRedirectResponse(
  2693. response,
  2694. request,
  2695. routeId,
  2696. matches,
  2697. basename
  2698. )
  2699. };
  2700. } else {
  2701. dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
  2702. }
  2703. }
  2704. return dataResults;
  2705. }
  2706. async function callLoadersAndMaybeResolveData(matches, fetchersToLoad, request, scopedContext) {
  2707. let loaderResultsPromise = callDataStrategy(
  2708. request,
  2709. matches,
  2710. scopedContext,
  2711. null
  2712. );
  2713. let fetcherResultsPromise = Promise.all(
  2714. fetchersToLoad.map(async (f) => {
  2715. if (f.matches && f.match && f.request && f.controller) {
  2716. let results = await callDataStrategy(
  2717. f.request,
  2718. f.matches,
  2719. scopedContext,
  2720. f.key
  2721. );
  2722. let result = results[f.match.route.id];
  2723. return { [f.key]: result };
  2724. } else {
  2725. return Promise.resolve({
  2726. [f.key]: {
  2727. type: "error" /* error */,
  2728. error: getInternalRouterError(404, {
  2729. pathname: f.path
  2730. })
  2731. }
  2732. });
  2733. }
  2734. })
  2735. );
  2736. let loaderResults = await loaderResultsPromise;
  2737. let fetcherResults = (await fetcherResultsPromise).reduce(
  2738. (acc, r) => Object.assign(acc, r),
  2739. {}
  2740. );
  2741. return {
  2742. loaderResults,
  2743. fetcherResults
  2744. };
  2745. }
  2746. function interruptActiveLoads() {
  2747. isRevalidationRequired = true;
  2748. fetchLoadMatches.forEach((_, key) => {
  2749. if (fetchControllers.has(key)) {
  2750. cancelledFetcherLoads.add(key);
  2751. }
  2752. abortFetcher(key);
  2753. });
  2754. }
  2755. function updateFetcherState(key, fetcher, opts = {}) {
  2756. state.fetchers.set(key, fetcher);
  2757. updateState(
  2758. { fetchers: new Map(state.fetchers) },
  2759. { flushSync: (opts && opts.flushSync) === true }
  2760. );
  2761. }
  2762. function setFetcherError(key, routeId, error, opts = {}) {
  2763. let boundaryMatch = findNearestBoundary(state.matches, routeId);
  2764. deleteFetcher(key);
  2765. updateState(
  2766. {
  2767. errors: {
  2768. [boundaryMatch.route.id]: error
  2769. },
  2770. fetchers: new Map(state.fetchers)
  2771. },
  2772. { flushSync: (opts && opts.flushSync) === true }
  2773. );
  2774. }
  2775. function getFetcher(key) {
  2776. activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
  2777. if (fetchersQueuedForDeletion.has(key)) {
  2778. fetchersQueuedForDeletion.delete(key);
  2779. }
  2780. return state.fetchers.get(key) || IDLE_FETCHER;
  2781. }
  2782. function resetFetcher(key, opts) {
  2783. abortFetcher(key, _optionalChain([opts, 'optionalAccess', _23 => _23.reason]));
  2784. updateFetcherState(key, getDoneFetcher(null));
  2785. }
  2786. function deleteFetcher(key) {
  2787. let fetcher = state.fetchers.get(key);
  2788. if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
  2789. abortFetcher(key);
  2790. }
  2791. fetchLoadMatches.delete(key);
  2792. fetchReloadIds.delete(key);
  2793. fetchRedirectIds.delete(key);
  2794. fetchersQueuedForDeletion.delete(key);
  2795. cancelledFetcherLoads.delete(key);
  2796. state.fetchers.delete(key);
  2797. }
  2798. function queueFetcherForDeletion(key) {
  2799. let count = (activeFetchers.get(key) || 0) - 1;
  2800. if (count <= 0) {
  2801. activeFetchers.delete(key);
  2802. fetchersQueuedForDeletion.add(key);
  2803. } else {
  2804. activeFetchers.set(key, count);
  2805. }
  2806. updateState({ fetchers: new Map(state.fetchers) });
  2807. }
  2808. function abortFetcher(key, reason) {
  2809. let controller = fetchControllers.get(key);
  2810. if (controller) {
  2811. controller.abort(reason);
  2812. fetchControllers.delete(key);
  2813. }
  2814. }
  2815. function markFetchersDone(keys) {
  2816. for (let key of keys) {
  2817. let fetcher = getFetcher(key);
  2818. let doneFetcher = getDoneFetcher(fetcher.data);
  2819. state.fetchers.set(key, doneFetcher);
  2820. }
  2821. }
  2822. function markFetchRedirectsDone() {
  2823. let doneKeys = [];
  2824. let updatedFetchers = false;
  2825. for (let key of fetchRedirectIds) {
  2826. let fetcher = state.fetchers.get(key);
  2827. invariant(fetcher, `Expected fetcher: ${key}`);
  2828. if (fetcher.state === "loading") {
  2829. fetchRedirectIds.delete(key);
  2830. doneKeys.push(key);
  2831. updatedFetchers = true;
  2832. }
  2833. }
  2834. markFetchersDone(doneKeys);
  2835. return updatedFetchers;
  2836. }
  2837. function abortStaleFetchLoads(landedId) {
  2838. let yeetedKeys = [];
  2839. for (let [key, id] of fetchReloadIds) {
  2840. if (id < landedId) {
  2841. let fetcher = state.fetchers.get(key);
  2842. invariant(fetcher, `Expected fetcher: ${key}`);
  2843. if (fetcher.state === "loading") {
  2844. abortFetcher(key);
  2845. fetchReloadIds.delete(key);
  2846. yeetedKeys.push(key);
  2847. }
  2848. }
  2849. }
  2850. markFetchersDone(yeetedKeys);
  2851. return yeetedKeys.length > 0;
  2852. }
  2853. function getBlocker(key, fn) {
  2854. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  2855. if (blockerFunctions.get(key) !== fn) {
  2856. blockerFunctions.set(key, fn);
  2857. }
  2858. return blocker;
  2859. }
  2860. function deleteBlocker(key) {
  2861. state.blockers.delete(key);
  2862. blockerFunctions.delete(key);
  2863. }
  2864. function updateBlocker(key, newBlocker) {
  2865. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  2866. invariant(
  2867. blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked",
  2868. `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`
  2869. );
  2870. let blockers = new Map(state.blockers);
  2871. blockers.set(key, newBlocker);
  2872. updateState({ blockers });
  2873. }
  2874. function shouldBlockNavigation({
  2875. currentLocation,
  2876. nextLocation,
  2877. historyAction
  2878. }) {
  2879. if (blockerFunctions.size === 0) {
  2880. return;
  2881. }
  2882. if (blockerFunctions.size > 1) {
  2883. warning(false, "A router only supports one blocker at a time");
  2884. }
  2885. let entries = Array.from(blockerFunctions.entries());
  2886. let [blockerKey, blockerFunction] = entries[entries.length - 1];
  2887. let blocker = state.blockers.get(blockerKey);
  2888. if (blocker && blocker.state === "proceeding") {
  2889. return;
  2890. }
  2891. if (blockerFunction({ currentLocation, nextLocation, historyAction })) {
  2892. return blockerKey;
  2893. }
  2894. }
  2895. function handleNavigational404(pathname) {
  2896. let error = getInternalRouterError(404, { pathname });
  2897. let routesToUse = inFlightDataRoutes || dataRoutes;
  2898. let { matches, route } = getShortCircuitMatches(routesToUse);
  2899. return { notFoundMatches: matches, route, error };
  2900. }
  2901. function enableScrollRestoration(positions, getPosition, getKey) {
  2902. savedScrollPositions = positions;
  2903. getScrollPosition = getPosition;
  2904. getScrollRestorationKey = getKey || null;
  2905. if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
  2906. initialScrollRestored = true;
  2907. let y = getSavedScrollPosition(state.location, state.matches);
  2908. if (y != null) {
  2909. updateState({ restoreScrollPosition: y });
  2910. }
  2911. }
  2912. return () => {
  2913. savedScrollPositions = null;
  2914. getScrollPosition = null;
  2915. getScrollRestorationKey = null;
  2916. };
  2917. }
  2918. function getScrollKey(location, matches) {
  2919. if (getScrollRestorationKey) {
  2920. let key = getScrollRestorationKey(
  2921. location,
  2922. matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))
  2923. );
  2924. return key || location.key;
  2925. }
  2926. return location.key;
  2927. }
  2928. function saveScrollPosition(location, matches) {
  2929. if (savedScrollPositions && getScrollPosition) {
  2930. let key = getScrollKey(location, matches);
  2931. savedScrollPositions[key] = getScrollPosition();
  2932. }
  2933. }
  2934. function getSavedScrollPosition(location, matches) {
  2935. if (savedScrollPositions) {
  2936. let key = getScrollKey(location, matches);
  2937. let y = savedScrollPositions[key];
  2938. if (typeof y === "number") {
  2939. return y;
  2940. }
  2941. }
  2942. return null;
  2943. }
  2944. function checkFogOfWar(matches, routesToUse, pathname) {
  2945. if (init.patchRoutesOnNavigation) {
  2946. if (!matches) {
  2947. let fogMatches = matchRoutesImpl(
  2948. routesToUse,
  2949. pathname,
  2950. basename,
  2951. true
  2952. );
  2953. return { active: true, matches: fogMatches || [] };
  2954. } else {
  2955. if (Object.keys(matches[0].params).length > 0) {
  2956. let partialMatches = matchRoutesImpl(
  2957. routesToUse,
  2958. pathname,
  2959. basename,
  2960. true
  2961. );
  2962. return { active: true, matches: partialMatches };
  2963. }
  2964. }
  2965. }
  2966. return { active: false, matches: null };
  2967. }
  2968. async function discoverRoutes(matches, pathname, signal, fetcherKey) {
  2969. if (!init.patchRoutesOnNavigation) {
  2970. return { type: "success", matches };
  2971. }
  2972. let partialMatches = matches;
  2973. while (true) {
  2974. let isNonHMR = inFlightDataRoutes == null;
  2975. let routesToUse = inFlightDataRoutes || dataRoutes;
  2976. let localManifest = manifest;
  2977. try {
  2978. await init.patchRoutesOnNavigation({
  2979. signal,
  2980. path: pathname,
  2981. matches: partialMatches,
  2982. fetcherKey,
  2983. patch: (routeId, children) => {
  2984. if (signal.aborted) return;
  2985. patchRoutesImpl(
  2986. routeId,
  2987. children,
  2988. routesToUse,
  2989. localManifest,
  2990. mapRouteProperties2,
  2991. false
  2992. );
  2993. }
  2994. });
  2995. } catch (e) {
  2996. return { type: "error", error: e, partialMatches };
  2997. } finally {
  2998. if (isNonHMR && !signal.aborted) {
  2999. dataRoutes = [...dataRoutes];
  3000. }
  3001. }
  3002. if (signal.aborted) {
  3003. return { type: "aborted" };
  3004. }
  3005. let newMatches = matchRoutes(routesToUse, pathname, basename);
  3006. let newPartialMatches = null;
  3007. if (newMatches) {
  3008. if (Object.keys(newMatches[0].params).length === 0) {
  3009. return { type: "success", matches: newMatches };
  3010. } else {
  3011. newPartialMatches = matchRoutesImpl(
  3012. routesToUse,
  3013. pathname,
  3014. basename,
  3015. true
  3016. );
  3017. let matchedDeeper = newPartialMatches && partialMatches.length < newPartialMatches.length && compareMatches(
  3018. partialMatches,
  3019. newPartialMatches.slice(0, partialMatches.length)
  3020. );
  3021. if (!matchedDeeper) {
  3022. return { type: "success", matches: newMatches };
  3023. }
  3024. }
  3025. }
  3026. if (!newPartialMatches) {
  3027. newPartialMatches = matchRoutesImpl(
  3028. routesToUse,
  3029. pathname,
  3030. basename,
  3031. true
  3032. );
  3033. }
  3034. if (!newPartialMatches || compareMatches(partialMatches, newPartialMatches)) {
  3035. return { type: "success", matches: null };
  3036. }
  3037. partialMatches = newPartialMatches;
  3038. }
  3039. }
  3040. function compareMatches(a, b) {
  3041. return a.length === b.length && a.every((m, i) => m.route.id === b[i].route.id);
  3042. }
  3043. function _internalSetRoutes(newRoutes) {
  3044. manifest = {};
  3045. inFlightDataRoutes = convertRoutesToDataRoutes(
  3046. newRoutes,
  3047. mapRouteProperties2,
  3048. void 0,
  3049. manifest
  3050. );
  3051. }
  3052. function patchRoutes(routeId, children, unstable_allowElementMutations = false) {
  3053. let isNonHMR = inFlightDataRoutes == null;
  3054. let routesToUse = inFlightDataRoutes || dataRoutes;
  3055. patchRoutesImpl(
  3056. routeId,
  3057. children,
  3058. routesToUse,
  3059. manifest,
  3060. mapRouteProperties2,
  3061. unstable_allowElementMutations
  3062. );
  3063. if (isNonHMR) {
  3064. dataRoutes = [...dataRoutes];
  3065. updateState({});
  3066. }
  3067. }
  3068. router = {
  3069. get basename() {
  3070. return basename;
  3071. },
  3072. get future() {
  3073. return future;
  3074. },
  3075. get state() {
  3076. return state;
  3077. },
  3078. get routes() {
  3079. return dataRoutes;
  3080. },
  3081. get window() {
  3082. return routerWindow;
  3083. },
  3084. initialize,
  3085. subscribe,
  3086. enableScrollRestoration,
  3087. navigate,
  3088. fetch: fetch2,
  3089. revalidate,
  3090. // Passthrough to history-aware createHref used by useHref so we get proper
  3091. // hash-aware URLs in DOM paths
  3092. createHref: (to) => init.history.createHref(to),
  3093. encodeLocation: (to) => init.history.encodeLocation(to),
  3094. getFetcher,
  3095. resetFetcher,
  3096. deleteFetcher: queueFetcherForDeletion,
  3097. dispose,
  3098. getBlocker,
  3099. deleteBlocker,
  3100. patchRoutes,
  3101. _internalFetchControllers: fetchControllers,
  3102. // TODO: Remove setRoutes, it's temporary to avoid dealing with
  3103. // updating the tree while validating the update algorithm.
  3104. _internalSetRoutes,
  3105. _internalSetStateDoNotUseOrYouWillBreakYourApp(newState) {
  3106. updateState(newState);
  3107. }
  3108. };
  3109. if (init.unstable_instrumentations) {
  3110. router = instrumentClientSideRouter(
  3111. router,
  3112. init.unstable_instrumentations.map((i) => i.router).filter(Boolean)
  3113. );
  3114. }
  3115. return router;
  3116. }
  3117. function createStaticHandler(routes, opts) {
  3118. invariant(
  3119. routes.length > 0,
  3120. "You must provide a non-empty routes array to createStaticHandler"
  3121. );
  3122. let manifest = {};
  3123. let basename = (opts ? opts.basename : null) || "/";
  3124. let _mapRouteProperties = _optionalChain([opts, 'optionalAccess', _24 => _24.mapRouteProperties]) || defaultMapRouteProperties;
  3125. let mapRouteProperties2 = _mapRouteProperties;
  3126. if (_optionalChain([opts, 'optionalAccess', _25 => _25.unstable_instrumentations])) {
  3127. let instrumentations = opts.unstable_instrumentations;
  3128. mapRouteProperties2 = (route) => {
  3129. return {
  3130. ..._mapRouteProperties(route),
  3131. ...getRouteInstrumentationUpdates(
  3132. instrumentations.map((i) => i.route).filter(Boolean),
  3133. route
  3134. )
  3135. };
  3136. };
  3137. }
  3138. let dataRoutes = convertRoutesToDataRoutes(
  3139. routes,
  3140. mapRouteProperties2,
  3141. void 0,
  3142. manifest
  3143. );
  3144. async function query(request, {
  3145. requestContext,
  3146. filterMatchesToLoad,
  3147. skipLoaderErrorBubbling,
  3148. skipRevalidation,
  3149. dataStrategy,
  3150. generateMiddlewareResponse
  3151. } = {}) {
  3152. let url = new URL(request.url);
  3153. let method = request.method;
  3154. let location = createLocation("", createPath(url), null, "default");
  3155. let matches = matchRoutes(dataRoutes, location, basename);
  3156. requestContext = requestContext != null ? requestContext : new RouterContextProvider();
  3157. if (!isValidMethod(method) && method !== "HEAD") {
  3158. let error = getInternalRouterError(405, { method });
  3159. let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
  3160. let staticContext = {
  3161. basename,
  3162. location,
  3163. matches: methodNotAllowedMatches,
  3164. loaderData: {},
  3165. actionData: null,
  3166. errors: {
  3167. [route.id]: error
  3168. },
  3169. statusCode: error.status,
  3170. loaderHeaders: {},
  3171. actionHeaders: {}
  3172. };
  3173. return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
  3174. } else if (!matches) {
  3175. let error = getInternalRouterError(404, { pathname: location.pathname });
  3176. let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
  3177. let staticContext = {
  3178. basename,
  3179. location,
  3180. matches: notFoundMatches,
  3181. loaderData: {},
  3182. actionData: null,
  3183. errors: {
  3184. [route.id]: error
  3185. },
  3186. statusCode: error.status,
  3187. loaderHeaders: {},
  3188. actionHeaders: {}
  3189. };
  3190. return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
  3191. }
  3192. if (generateMiddlewareResponse) {
  3193. invariant(
  3194. requestContext instanceof RouterContextProvider,
  3195. "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`"
  3196. );
  3197. try {
  3198. await loadLazyMiddlewareForMatches(
  3199. matches,
  3200. manifest,
  3201. mapRouteProperties2
  3202. );
  3203. let renderedStaticContext;
  3204. let response = await runServerMiddlewarePipeline(
  3205. {
  3206. request,
  3207. unstable_pattern: getRoutePattern(matches),
  3208. matches,
  3209. params: matches[0].params,
  3210. // If we're calling middleware then it must be enabled so we can cast
  3211. // this to the proper type knowing it's not an `AppLoadContext`
  3212. context: requestContext
  3213. },
  3214. async () => {
  3215. let res = await generateMiddlewareResponse(
  3216. async (revalidationRequest, opts2 = {}) => {
  3217. let result2 = await queryImpl(
  3218. revalidationRequest,
  3219. location,
  3220. matches,
  3221. requestContext,
  3222. dataStrategy || null,
  3223. skipLoaderErrorBubbling === true,
  3224. null,
  3225. "filterMatchesToLoad" in opts2 ? _nullishCoalesce(opts2.filterMatchesToLoad, () => ( null)) : _nullishCoalesce(filterMatchesToLoad, () => ( null)),
  3226. skipRevalidation === true
  3227. );
  3228. if (isResponse(result2)) {
  3229. return result2;
  3230. }
  3231. renderedStaticContext = { location, basename, ...result2 };
  3232. return renderedStaticContext;
  3233. }
  3234. );
  3235. return res;
  3236. },
  3237. async (error, routeId) => {
  3238. if (isRedirectResponse(error)) {
  3239. return error;
  3240. }
  3241. if (isResponse(error)) {
  3242. try {
  3243. error = new ErrorResponseImpl(
  3244. error.status,
  3245. error.statusText,
  3246. await parseResponseBody(error)
  3247. );
  3248. } catch (e) {
  3249. error = e;
  3250. }
  3251. }
  3252. if (isDataWithResponseInit(error)) {
  3253. error = dataWithResponseInitToErrorResponse(error);
  3254. }
  3255. if (renderedStaticContext) {
  3256. if (routeId in renderedStaticContext.loaderData) {
  3257. renderedStaticContext.loaderData[routeId] = void 0;
  3258. }
  3259. let staticContext = getStaticContextFromError(
  3260. dataRoutes,
  3261. renderedStaticContext,
  3262. error,
  3263. skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id
  3264. );
  3265. return generateMiddlewareResponse(
  3266. () => Promise.resolve(staticContext)
  3267. );
  3268. } else {
  3269. let boundaryRouteId = skipLoaderErrorBubbling ? routeId : findNearestBoundary(
  3270. matches,
  3271. _optionalChain([matches, 'access', _26 => _26.find, 'call', _27 => _27(
  3272. (m) => m.route.id === routeId || m.route.loader
  3273. ), 'optionalAccess', _28 => _28.route, 'access', _29 => _29.id]) || routeId
  3274. ).route.id;
  3275. let staticContext = {
  3276. matches,
  3277. location,
  3278. basename,
  3279. loaderData: {},
  3280. actionData: null,
  3281. errors: {
  3282. [boundaryRouteId]: error
  3283. },
  3284. statusCode: isRouteErrorResponse(error) ? error.status : 500,
  3285. actionHeaders: {},
  3286. loaderHeaders: {}
  3287. };
  3288. return generateMiddlewareResponse(
  3289. () => Promise.resolve(staticContext)
  3290. );
  3291. }
  3292. }
  3293. );
  3294. invariant(isResponse(response), "Expected a response in query()");
  3295. return response;
  3296. } catch (e) {
  3297. if (isResponse(e)) {
  3298. return e;
  3299. }
  3300. throw e;
  3301. }
  3302. }
  3303. let result = await queryImpl(
  3304. request,
  3305. location,
  3306. matches,
  3307. requestContext,
  3308. dataStrategy || null,
  3309. skipLoaderErrorBubbling === true,
  3310. null,
  3311. filterMatchesToLoad || null,
  3312. skipRevalidation === true
  3313. );
  3314. if (isResponse(result)) {
  3315. return result;
  3316. }
  3317. return { location, basename, ...result };
  3318. }
  3319. async function queryRoute(request, {
  3320. routeId,
  3321. requestContext,
  3322. dataStrategy,
  3323. generateMiddlewareResponse
  3324. } = {}) {
  3325. let url = new URL(request.url);
  3326. let method = request.method;
  3327. let location = createLocation("", createPath(url), null, "default");
  3328. let matches = matchRoutes(dataRoutes, location, basename);
  3329. requestContext = requestContext != null ? requestContext : new RouterContextProvider();
  3330. if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
  3331. throw getInternalRouterError(405, { method });
  3332. } else if (!matches) {
  3333. throw getInternalRouterError(404, { pathname: location.pathname });
  3334. }
  3335. let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
  3336. if (routeId && !match) {
  3337. throw getInternalRouterError(403, {
  3338. pathname: location.pathname,
  3339. routeId
  3340. });
  3341. } else if (!match) {
  3342. throw getInternalRouterError(404, { pathname: location.pathname });
  3343. }
  3344. if (generateMiddlewareResponse) {
  3345. invariant(
  3346. requestContext instanceof RouterContextProvider,
  3347. "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`"
  3348. );
  3349. await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties2);
  3350. let response = await runServerMiddlewarePipeline(
  3351. {
  3352. request,
  3353. unstable_pattern: getRoutePattern(matches),
  3354. matches,
  3355. params: matches[0].params,
  3356. // If we're calling middleware then it must be enabled so we can cast
  3357. // this to the proper type knowing it's not an `AppLoadContext`
  3358. context: requestContext
  3359. },
  3360. async () => {
  3361. let res = await generateMiddlewareResponse(
  3362. async (innerRequest) => {
  3363. let result2 = await queryImpl(
  3364. innerRequest,
  3365. location,
  3366. matches,
  3367. requestContext,
  3368. dataStrategy || null,
  3369. false,
  3370. match,
  3371. null,
  3372. false
  3373. );
  3374. let processed = handleQueryResult(result2);
  3375. return isResponse(processed) ? processed : typeof processed === "string" ? new Response(processed) : Response.json(processed);
  3376. }
  3377. );
  3378. return res;
  3379. },
  3380. (error) => {
  3381. if (isDataWithResponseInit(error)) {
  3382. return Promise.resolve(dataWithResponseInitToResponse(error));
  3383. }
  3384. if (isResponse(error)) {
  3385. return Promise.resolve(error);
  3386. }
  3387. throw error;
  3388. }
  3389. );
  3390. return response;
  3391. }
  3392. let result = await queryImpl(
  3393. request,
  3394. location,
  3395. matches,
  3396. requestContext,
  3397. dataStrategy || null,
  3398. false,
  3399. match,
  3400. null,
  3401. false
  3402. );
  3403. return handleQueryResult(result);
  3404. function handleQueryResult(result2) {
  3405. if (isResponse(result2)) {
  3406. return result2;
  3407. }
  3408. let error = result2.errors ? Object.values(result2.errors)[0] : void 0;
  3409. if (error !== void 0) {
  3410. throw error;
  3411. }
  3412. if (result2.actionData) {
  3413. return Object.values(result2.actionData)[0];
  3414. }
  3415. if (result2.loaderData) {
  3416. return Object.values(result2.loaderData)[0];
  3417. }
  3418. return void 0;
  3419. }
  3420. }
  3421. async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
  3422. invariant(
  3423. request.signal,
  3424. "query()/queryRoute() requests must contain an AbortController signal"
  3425. );
  3426. try {
  3427. if (isMutationMethod(request.method)) {
  3428. let result2 = await submit(
  3429. request,
  3430. matches,
  3431. routeMatch || getTargetMatch(matches, location),
  3432. requestContext,
  3433. dataStrategy,
  3434. skipLoaderErrorBubbling,
  3435. routeMatch != null,
  3436. filterMatchesToLoad,
  3437. skipRevalidation
  3438. );
  3439. return result2;
  3440. }
  3441. let result = await loadRouteData(
  3442. request,
  3443. matches,
  3444. requestContext,
  3445. dataStrategy,
  3446. skipLoaderErrorBubbling,
  3447. routeMatch,
  3448. filterMatchesToLoad
  3449. );
  3450. return isResponse(result) ? result : {
  3451. ...result,
  3452. actionData: null,
  3453. actionHeaders: {}
  3454. };
  3455. } catch (e) {
  3456. if (isDataStrategyResult(e) && isResponse(e.result)) {
  3457. if (e.type === "error" /* error */) {
  3458. throw e.result;
  3459. }
  3460. return e.result;
  3461. }
  3462. if (isRedirectResponse(e)) {
  3463. return e;
  3464. }
  3465. throw e;
  3466. }
  3467. }
  3468. async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
  3469. let result;
  3470. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  3471. let error = getInternalRouterError(405, {
  3472. method: request.method,
  3473. pathname: new URL(request.url).pathname,
  3474. routeId: actionMatch.route.id
  3475. });
  3476. if (isRouteRequest) {
  3477. throw error;
  3478. }
  3479. result = {
  3480. type: "error" /* error */,
  3481. error
  3482. };
  3483. } else {
  3484. let dsMatches = getTargetedDataStrategyMatches(
  3485. mapRouteProperties2,
  3486. manifest,
  3487. request,
  3488. matches,
  3489. actionMatch,
  3490. [],
  3491. requestContext
  3492. );
  3493. let results = await callDataStrategy(
  3494. request,
  3495. dsMatches,
  3496. isRouteRequest,
  3497. requestContext,
  3498. dataStrategy
  3499. );
  3500. result = results[actionMatch.route.id];
  3501. if (request.signal.aborted) {
  3502. throwStaticHandlerAbortedError(request, isRouteRequest);
  3503. }
  3504. }
  3505. if (isRedirectResult(result)) {
  3506. throw new Response(null, {
  3507. status: result.response.status,
  3508. headers: {
  3509. Location: result.response.headers.get("Location")
  3510. }
  3511. });
  3512. }
  3513. if (isRouteRequest) {
  3514. if (isErrorResult(result)) {
  3515. throw result.error;
  3516. }
  3517. return {
  3518. matches: [actionMatch],
  3519. loaderData: {},
  3520. actionData: { [actionMatch.route.id]: result.data },
  3521. errors: null,
  3522. // Note: statusCode + headers are unused here since queryRoute will
  3523. // return the raw Response or value
  3524. statusCode: 200,
  3525. loaderHeaders: {},
  3526. actionHeaders: {}
  3527. };
  3528. }
  3529. if (skipRevalidation) {
  3530. if (isErrorResult(result)) {
  3531. let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
  3532. return {
  3533. statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
  3534. actionData: null,
  3535. actionHeaders: {
  3536. ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
  3537. },
  3538. matches,
  3539. loaderData: {},
  3540. errors: {
  3541. [boundaryMatch.route.id]: result.error
  3542. },
  3543. loaderHeaders: {}
  3544. };
  3545. } else {
  3546. return {
  3547. actionData: {
  3548. [actionMatch.route.id]: result.data
  3549. },
  3550. actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
  3551. matches,
  3552. loaderData: {},
  3553. errors: null,
  3554. statusCode: result.statusCode || 200,
  3555. loaderHeaders: {}
  3556. };
  3557. }
  3558. }
  3559. let loaderRequest = new Request(request.url, {
  3560. headers: request.headers,
  3561. redirect: request.redirect,
  3562. signal: request.signal
  3563. });
  3564. if (isErrorResult(result)) {
  3565. let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
  3566. let handlerContext2 = await loadRouteData(
  3567. loaderRequest,
  3568. matches,
  3569. requestContext,
  3570. dataStrategy,
  3571. skipLoaderErrorBubbling,
  3572. null,
  3573. filterMatchesToLoad,
  3574. [boundaryMatch.route.id, result]
  3575. );
  3576. return {
  3577. ...handlerContext2,
  3578. statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
  3579. actionData: null,
  3580. actionHeaders: {
  3581. ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
  3582. }
  3583. };
  3584. }
  3585. let handlerContext = await loadRouteData(
  3586. loaderRequest,
  3587. matches,
  3588. requestContext,
  3589. dataStrategy,
  3590. skipLoaderErrorBubbling,
  3591. null,
  3592. filterMatchesToLoad
  3593. );
  3594. return {
  3595. ...handlerContext,
  3596. actionData: {
  3597. [actionMatch.route.id]: result.data
  3598. },
  3599. // action status codes take precedence over loader status codes
  3600. ...result.statusCode ? { statusCode: result.statusCode } : {},
  3601. actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
  3602. };
  3603. }
  3604. async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
  3605. let isRouteRequest = routeMatch != null;
  3606. if (isRouteRequest && !_optionalChain([routeMatch, 'optionalAccess', _30 => _30.route, 'access', _31 => _31.loader]) && !_optionalChain([routeMatch, 'optionalAccess', _32 => _32.route, 'access', _33 => _33.lazy])) {
  3607. throw getInternalRouterError(400, {
  3608. method: request.method,
  3609. pathname: new URL(request.url).pathname,
  3610. routeId: _optionalChain([routeMatch, 'optionalAccess', _34 => _34.route, 'access', _35 => _35.id])
  3611. });
  3612. }
  3613. let dsMatches;
  3614. if (routeMatch) {
  3615. dsMatches = getTargetedDataStrategyMatches(
  3616. mapRouteProperties2,
  3617. manifest,
  3618. request,
  3619. matches,
  3620. routeMatch,
  3621. [],
  3622. requestContext
  3623. );
  3624. } else {
  3625. let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? (
  3626. // Up to but not including the boundary
  3627. matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1
  3628. ) : void 0;
  3629. let pattern = getRoutePattern(matches);
  3630. dsMatches = matches.map((match, index) => {
  3631. if (maxIdx != null && index > maxIdx) {
  3632. return getDataStrategyMatch(
  3633. mapRouteProperties2,
  3634. manifest,
  3635. request,
  3636. pattern,
  3637. match,
  3638. [],
  3639. requestContext,
  3640. false
  3641. );
  3642. }
  3643. return getDataStrategyMatch(
  3644. mapRouteProperties2,
  3645. manifest,
  3646. request,
  3647. pattern,
  3648. match,
  3649. [],
  3650. requestContext,
  3651. (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match))
  3652. );
  3653. });
  3654. }
  3655. if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) {
  3656. return {
  3657. matches,
  3658. loaderData: {},
  3659. errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
  3660. [pendingActionResult[0]]: pendingActionResult[1].error
  3661. } : null,
  3662. statusCode: 200,
  3663. loaderHeaders: {}
  3664. };
  3665. }
  3666. let results = await callDataStrategy(
  3667. request,
  3668. dsMatches,
  3669. isRouteRequest,
  3670. requestContext,
  3671. dataStrategy
  3672. );
  3673. if (request.signal.aborted) {
  3674. throwStaticHandlerAbortedError(request, isRouteRequest);
  3675. }
  3676. let handlerContext = processRouteLoaderData(
  3677. matches,
  3678. results,
  3679. pendingActionResult,
  3680. true,
  3681. skipLoaderErrorBubbling
  3682. );
  3683. return {
  3684. ...handlerContext,
  3685. matches
  3686. };
  3687. }
  3688. async function callDataStrategy(request, matches, isRouteRequest, requestContext, dataStrategy) {
  3689. let results = await callDataStrategyImpl(
  3690. dataStrategy || defaultDataStrategy,
  3691. request,
  3692. matches,
  3693. null,
  3694. requestContext,
  3695. true
  3696. );
  3697. let dataResults = {};
  3698. await Promise.all(
  3699. matches.map(async (match) => {
  3700. if (!(match.route.id in results)) {
  3701. return;
  3702. }
  3703. let result = results[match.route.id];
  3704. if (isRedirectDataStrategyResult(result)) {
  3705. let response = result.result;
  3706. throw normalizeRelativeRoutingRedirectResponse(
  3707. response,
  3708. request,
  3709. match.route.id,
  3710. matches,
  3711. basename
  3712. );
  3713. }
  3714. if (isRouteRequest) {
  3715. if (isResponse(result.result)) {
  3716. throw result;
  3717. } else if (isDataWithResponseInit(result.result)) {
  3718. throw dataWithResponseInitToResponse(result.result);
  3719. }
  3720. }
  3721. dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
  3722. })
  3723. );
  3724. return dataResults;
  3725. }
  3726. return {
  3727. dataRoutes,
  3728. query,
  3729. queryRoute
  3730. };
  3731. }
  3732. function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
  3733. let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
  3734. return {
  3735. ...handlerContext,
  3736. statusCode: isRouteErrorResponse(error) ? error.status : 500,
  3737. errors: {
  3738. [errorBoundaryId]: error
  3739. }
  3740. };
  3741. }
  3742. function throwStaticHandlerAbortedError(request, isRouteRequest) {
  3743. if (request.signal.reason !== void 0) {
  3744. throw request.signal.reason;
  3745. }
  3746. let method = isRouteRequest ? "queryRoute" : "query";
  3747. throw new Error(
  3748. `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
  3749. );
  3750. }
  3751. function isSubmissionNavigation(opts) {
  3752. return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0);
  3753. }
  3754. function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
  3755. let contextualMatches;
  3756. let activeRouteMatch;
  3757. if (fromRouteId) {
  3758. contextualMatches = [];
  3759. for (let match of matches) {
  3760. contextualMatches.push(match);
  3761. if (match.route.id === fromRouteId) {
  3762. activeRouteMatch = match;
  3763. break;
  3764. }
  3765. }
  3766. } else {
  3767. contextualMatches = matches;
  3768. activeRouteMatch = matches[matches.length - 1];
  3769. }
  3770. let path = resolveTo(
  3771. to ? to : ".",
  3772. getResolveToMatches(contextualMatches),
  3773. stripBasename(location.pathname, basename) || location.pathname,
  3774. relative === "path"
  3775. );
  3776. if (to == null) {
  3777. path.search = location.search;
  3778. path.hash = location.hash;
  3779. }
  3780. if ((to == null || to === "" || to === ".") && activeRouteMatch) {
  3781. let nakedIndex = hasNakedIndexQuery(path.search);
  3782. if (activeRouteMatch.route.index && !nakedIndex) {
  3783. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  3784. } else if (!activeRouteMatch.route.index && nakedIndex) {
  3785. let params = new URLSearchParams(path.search);
  3786. let indexValues = params.getAll("index");
  3787. params.delete("index");
  3788. indexValues.filter((v) => v).forEach((v) => params.append("index", v));
  3789. let qs = params.toString();
  3790. path.search = qs ? `?${qs}` : "";
  3791. }
  3792. }
  3793. if (basename !== "/") {
  3794. path.pathname = prependBasename({ basename, pathname: path.pathname });
  3795. }
  3796. return createPath(path);
  3797. }
  3798. function normalizeNavigateOptions(isFetcher, path, opts) {
  3799. if (!opts || !isSubmissionNavigation(opts)) {
  3800. return { path };
  3801. }
  3802. if (opts.formMethod && !isValidMethod(opts.formMethod)) {
  3803. return {
  3804. path,
  3805. error: getInternalRouterError(405, { method: opts.formMethod })
  3806. };
  3807. }
  3808. let getInvalidBodyError = () => ({
  3809. path,
  3810. error: getInternalRouterError(400, { type: "invalid-body" })
  3811. });
  3812. let rawFormMethod = opts.formMethod || "get";
  3813. let formMethod = rawFormMethod.toUpperCase();
  3814. let formAction = stripHashFromPath(path);
  3815. if (opts.body !== void 0) {
  3816. if (opts.formEncType === "text/plain") {
  3817. if (!isMutationMethod(formMethod)) {
  3818. return getInvalidBodyError();
  3819. }
  3820. let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? (
  3821. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
  3822. Array.from(opts.body.entries()).reduce(
  3823. (acc, [name, value]) => `${acc}${name}=${value}
  3824. `,
  3825. ""
  3826. )
  3827. ) : String(opts.body);
  3828. return {
  3829. path,
  3830. submission: {
  3831. formMethod,
  3832. formAction,
  3833. formEncType: opts.formEncType,
  3834. formData: void 0,
  3835. json: void 0,
  3836. text
  3837. }
  3838. };
  3839. } else if (opts.formEncType === "application/json") {
  3840. if (!isMutationMethod(formMethod)) {
  3841. return getInvalidBodyError();
  3842. }
  3843. try {
  3844. let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
  3845. return {
  3846. path,
  3847. submission: {
  3848. formMethod,
  3849. formAction,
  3850. formEncType: opts.formEncType,
  3851. formData: void 0,
  3852. json,
  3853. text: void 0
  3854. }
  3855. };
  3856. } catch (e) {
  3857. return getInvalidBodyError();
  3858. }
  3859. }
  3860. }
  3861. invariant(
  3862. typeof FormData === "function",
  3863. "FormData is not available in this environment"
  3864. );
  3865. let searchParams;
  3866. let formData;
  3867. if (opts.formData) {
  3868. searchParams = convertFormDataToSearchParams(opts.formData);
  3869. formData = opts.formData;
  3870. } else if (opts.body instanceof FormData) {
  3871. searchParams = convertFormDataToSearchParams(opts.body);
  3872. formData = opts.body;
  3873. } else if (opts.body instanceof URLSearchParams) {
  3874. searchParams = opts.body;
  3875. formData = convertSearchParamsToFormData(searchParams);
  3876. } else if (opts.body == null) {
  3877. searchParams = new URLSearchParams();
  3878. formData = new FormData();
  3879. } else {
  3880. try {
  3881. searchParams = new URLSearchParams(opts.body);
  3882. formData = convertSearchParamsToFormData(searchParams);
  3883. } catch (e) {
  3884. return getInvalidBodyError();
  3885. }
  3886. }
  3887. let submission = {
  3888. formMethod,
  3889. formAction,
  3890. formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
  3891. formData,
  3892. json: void 0,
  3893. text: void 0
  3894. };
  3895. if (isMutationMethod(submission.formMethod)) {
  3896. return { path, submission };
  3897. }
  3898. let parsedPath = parsePath(path);
  3899. if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
  3900. searchParams.append("index", "");
  3901. }
  3902. parsedPath.search = `?${searchParams}`;
  3903. return { path: createPath(parsedPath), submission };
  3904. }
  3905. function getMatchesToLoad(request, scopedContext, mapRouteProperties2, manifest, history, state, matches, submission, location, lazyRoutePropertiesToSkip, initialHydration, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, hasPatchRoutesOnNavigation, pendingActionResult) {
  3906. let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : void 0;
  3907. let currentUrl = history.createURL(state.location);
  3908. let nextUrl = history.createURL(location);
  3909. let maxIdx;
  3910. if (initialHydration && state.errors) {
  3911. let boundaryId = Object.keys(state.errors)[0];
  3912. maxIdx = matches.findIndex((m) => m.route.id === boundaryId);
  3913. } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
  3914. let boundaryId = pendingActionResult[0];
  3915. maxIdx = matches.findIndex((m) => m.route.id === boundaryId) - 1;
  3916. }
  3917. let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : void 0;
  3918. let shouldSkipRevalidation = actionStatus && actionStatus >= 400;
  3919. let baseShouldRevalidateArgs = {
  3920. currentUrl,
  3921. currentParams: _optionalChain([state, 'access', _36 => _36.matches, 'access', _37 => _37[0], 'optionalAccess', _38 => _38.params]) || {},
  3922. nextUrl,
  3923. nextParams: matches[0].params,
  3924. ...submission,
  3925. actionResult,
  3926. actionStatus
  3927. };
  3928. let pattern = getRoutePattern(matches);
  3929. let dsMatches = matches.map((match, index) => {
  3930. let { route } = match;
  3931. let forceShouldLoad = null;
  3932. if (maxIdx != null && index > maxIdx) {
  3933. forceShouldLoad = false;
  3934. } else if (route.lazy) {
  3935. forceShouldLoad = true;
  3936. } else if (!routeHasLoaderOrMiddleware(route)) {
  3937. forceShouldLoad = false;
  3938. } else if (initialHydration) {
  3939. forceShouldLoad = shouldLoadRouteOnHydration(
  3940. route,
  3941. state.loaderData,
  3942. state.errors
  3943. );
  3944. } else if (isNewLoader(state.loaderData, state.matches[index], match)) {
  3945. forceShouldLoad = true;
  3946. }
  3947. if (forceShouldLoad !== null) {
  3948. return getDataStrategyMatch(
  3949. mapRouteProperties2,
  3950. manifest,
  3951. request,
  3952. pattern,
  3953. match,
  3954. lazyRoutePropertiesToSkip,
  3955. scopedContext,
  3956. forceShouldLoad
  3957. );
  3958. }
  3959. let defaultShouldRevalidate = shouldSkipRevalidation ? false : (
  3960. // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
  3961. isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || // Search params affect all loaders
  3962. currentUrl.search !== nextUrl.search || isNewRouteInstance(state.matches[index], match)
  3963. );
  3964. let shouldRevalidateArgs = {
  3965. ...baseShouldRevalidateArgs,
  3966. defaultShouldRevalidate
  3967. };
  3968. let shouldLoad = shouldRevalidateLoader(match, shouldRevalidateArgs);
  3969. return getDataStrategyMatch(
  3970. mapRouteProperties2,
  3971. manifest,
  3972. request,
  3973. pattern,
  3974. match,
  3975. lazyRoutePropertiesToSkip,
  3976. scopedContext,
  3977. shouldLoad,
  3978. shouldRevalidateArgs
  3979. );
  3980. });
  3981. let revalidatingFetchers = [];
  3982. fetchLoadMatches.forEach((f, key) => {
  3983. if (initialHydration || !matches.some((m) => m.route.id === f.routeId) || fetchersQueuedForDeletion.has(key)) {
  3984. return;
  3985. }
  3986. let fetcher = state.fetchers.get(key);
  3987. let isMidInitialLoad = fetcher && fetcher.state !== "idle" && fetcher.data === void 0;
  3988. let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
  3989. if (!fetcherMatches) {
  3990. if (hasPatchRoutesOnNavigation && isMidInitialLoad) {
  3991. return;
  3992. }
  3993. revalidatingFetchers.push({
  3994. key,
  3995. routeId: f.routeId,
  3996. path: f.path,
  3997. matches: null,
  3998. match: null,
  3999. request: null,
  4000. controller: null
  4001. });
  4002. return;
  4003. }
  4004. if (fetchRedirectIds.has(key)) {
  4005. return;
  4006. }
  4007. let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
  4008. let fetchController = new AbortController();
  4009. let fetchRequest = createClientSideRequest(
  4010. history,
  4011. f.path,
  4012. fetchController.signal
  4013. );
  4014. let fetcherDsMatches = null;
  4015. if (cancelledFetcherLoads.has(key)) {
  4016. cancelledFetcherLoads.delete(key);
  4017. fetcherDsMatches = getTargetedDataStrategyMatches(
  4018. mapRouteProperties2,
  4019. manifest,
  4020. fetchRequest,
  4021. fetcherMatches,
  4022. fetcherMatch,
  4023. lazyRoutePropertiesToSkip,
  4024. scopedContext
  4025. );
  4026. } else if (isMidInitialLoad) {
  4027. if (isRevalidationRequired) {
  4028. fetcherDsMatches = getTargetedDataStrategyMatches(
  4029. mapRouteProperties2,
  4030. manifest,
  4031. fetchRequest,
  4032. fetcherMatches,
  4033. fetcherMatch,
  4034. lazyRoutePropertiesToSkip,
  4035. scopedContext
  4036. );
  4037. }
  4038. } else {
  4039. let shouldRevalidateArgs = {
  4040. ...baseShouldRevalidateArgs,
  4041. defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
  4042. };
  4043. if (shouldRevalidateLoader(fetcherMatch, shouldRevalidateArgs)) {
  4044. fetcherDsMatches = getTargetedDataStrategyMatches(
  4045. mapRouteProperties2,
  4046. manifest,
  4047. fetchRequest,
  4048. fetcherMatches,
  4049. fetcherMatch,
  4050. lazyRoutePropertiesToSkip,
  4051. scopedContext,
  4052. shouldRevalidateArgs
  4053. );
  4054. }
  4055. }
  4056. if (fetcherDsMatches) {
  4057. revalidatingFetchers.push({
  4058. key,
  4059. routeId: f.routeId,
  4060. path: f.path,
  4061. matches: fetcherDsMatches,
  4062. match: fetcherMatch,
  4063. request: fetchRequest,
  4064. controller: fetchController
  4065. });
  4066. }
  4067. });
  4068. return { dsMatches, revalidatingFetchers };
  4069. }
  4070. function routeHasLoaderOrMiddleware(route) {
  4071. return route.loader != null || route.middleware != null && route.middleware.length > 0;
  4072. }
  4073. function shouldLoadRouteOnHydration(route, loaderData, errors) {
  4074. if (route.lazy) {
  4075. return true;
  4076. }
  4077. if (!routeHasLoaderOrMiddleware(route)) {
  4078. return false;
  4079. }
  4080. let hasData = loaderData != null && route.id in loaderData;
  4081. let hasError = errors != null && errors[route.id] !== void 0;
  4082. if (!hasData && hasError) {
  4083. return false;
  4084. }
  4085. if (typeof route.loader === "function" && route.loader.hydrate === true) {
  4086. return true;
  4087. }
  4088. return !hasData && !hasError;
  4089. }
  4090. function isNewLoader(currentLoaderData, currentMatch, match) {
  4091. let isNew = (
  4092. // [a] -> [a, b]
  4093. !currentMatch || // [a, b] -> [a, c]
  4094. match.route.id !== currentMatch.route.id
  4095. );
  4096. let isMissingData = !currentLoaderData.hasOwnProperty(match.route.id);
  4097. return isNew || isMissingData;
  4098. }
  4099. function isNewRouteInstance(currentMatch, match) {
  4100. let currentPath = currentMatch.route.path;
  4101. return (
  4102. // param change for this match, /users/123 -> /users/456
  4103. currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
  4104. // e.g. /files/images/avatar.jpg -> files/finances.xls
  4105. currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
  4106. );
  4107. }
  4108. function shouldRevalidateLoader(loaderMatch, arg) {
  4109. if (loaderMatch.route.shouldRevalidate) {
  4110. let routeChoice = loaderMatch.route.shouldRevalidate(arg);
  4111. if (typeof routeChoice === "boolean") {
  4112. return routeChoice;
  4113. }
  4114. }
  4115. return arg.defaultShouldRevalidate;
  4116. }
  4117. function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties2, allowElementMutations) {
  4118. let childrenToPatch;
  4119. if (routeId) {
  4120. let route = manifest[routeId];
  4121. invariant(
  4122. route,
  4123. `No route found to patch children into: routeId = ${routeId}`
  4124. );
  4125. if (!route.children) {
  4126. route.children = [];
  4127. }
  4128. childrenToPatch = route.children;
  4129. } else {
  4130. childrenToPatch = routesToUse;
  4131. }
  4132. let uniqueChildren = [];
  4133. let existingChildren = [];
  4134. children.forEach((newRoute) => {
  4135. let existingRoute = childrenToPatch.find(
  4136. (existingRoute2) => isSameRoute(newRoute, existingRoute2)
  4137. );
  4138. if (existingRoute) {
  4139. existingChildren.push({ existingRoute, newRoute });
  4140. } else {
  4141. uniqueChildren.push(newRoute);
  4142. }
  4143. });
  4144. if (uniqueChildren.length > 0) {
  4145. let newRoutes = convertRoutesToDataRoutes(
  4146. uniqueChildren,
  4147. mapRouteProperties2,
  4148. [routeId || "_", "patch", String(_optionalChain([childrenToPatch, 'optionalAccess', _39 => _39.length]) || "0")],
  4149. manifest
  4150. );
  4151. childrenToPatch.push(...newRoutes);
  4152. }
  4153. if (allowElementMutations && existingChildren.length > 0) {
  4154. for (let i = 0; i < existingChildren.length; i++) {
  4155. let { existingRoute, newRoute } = existingChildren[i];
  4156. let existingRouteTyped = existingRoute;
  4157. let [newRouteTyped] = convertRoutesToDataRoutes(
  4158. [newRoute],
  4159. mapRouteProperties2,
  4160. [],
  4161. // Doesn't matter for mutated routes since they already have an id
  4162. {},
  4163. // Don't touch the manifest here since we're updating in place
  4164. true
  4165. );
  4166. Object.assign(existingRouteTyped, {
  4167. element: newRouteTyped.element ? newRouteTyped.element : existingRouteTyped.element,
  4168. errorElement: newRouteTyped.errorElement ? newRouteTyped.errorElement : existingRouteTyped.errorElement,
  4169. hydrateFallbackElement: newRouteTyped.hydrateFallbackElement ? newRouteTyped.hydrateFallbackElement : existingRouteTyped.hydrateFallbackElement
  4170. });
  4171. }
  4172. }
  4173. }
  4174. function isSameRoute(newRoute, existingRoute) {
  4175. if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
  4176. return true;
  4177. }
  4178. if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
  4179. return false;
  4180. }
  4181. if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
  4182. return true;
  4183. }
  4184. return newRoute.children.every(
  4185. (aChild, i) => _optionalChain([existingRoute, 'access', _40 => _40.children, 'optionalAccess', _41 => _41.some, 'call', _42 => _42((bChild) => isSameRoute(aChild, bChild))])
  4186. );
  4187. }
  4188. var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
  4189. var loadLazyRouteProperty = ({
  4190. key,
  4191. route,
  4192. manifest,
  4193. mapRouteProperties: mapRouteProperties2
  4194. }) => {
  4195. let routeToUpdate = manifest[route.id];
  4196. invariant(routeToUpdate, "No route found in manifest");
  4197. if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") {
  4198. return;
  4199. }
  4200. let lazyFn = routeToUpdate.lazy[key];
  4201. if (!lazyFn) {
  4202. return;
  4203. }
  4204. let cache = lazyRoutePropertyCache.get(routeToUpdate);
  4205. if (!cache) {
  4206. cache = {};
  4207. lazyRoutePropertyCache.set(routeToUpdate, cache);
  4208. }
  4209. let cachedPromise = cache[key];
  4210. if (cachedPromise) {
  4211. return cachedPromise;
  4212. }
  4213. let propertyPromise = (async () => {
  4214. let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
  4215. let staticRouteValue = routeToUpdate[key];
  4216. let isStaticallyDefined = staticRouteValue !== void 0 && key !== "hasErrorBoundary";
  4217. if (isUnsupported) {
  4218. warning(
  4219. !isUnsupported,
  4220. "Route property " + key + " is not a supported lazy route property. This property will be ignored."
  4221. );
  4222. cache[key] = Promise.resolve();
  4223. } else if (isStaticallyDefined) {
  4224. warning(
  4225. false,
  4226. `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`
  4227. );
  4228. } else {
  4229. let value = await lazyFn();
  4230. if (value != null) {
  4231. Object.assign(routeToUpdate, { [key]: value });
  4232. Object.assign(routeToUpdate, mapRouteProperties2(routeToUpdate));
  4233. }
  4234. }
  4235. if (typeof routeToUpdate.lazy === "object") {
  4236. routeToUpdate.lazy[key] = void 0;
  4237. if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) {
  4238. routeToUpdate.lazy = void 0;
  4239. }
  4240. }
  4241. })();
  4242. cache[key] = propertyPromise;
  4243. return propertyPromise;
  4244. };
  4245. var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
  4246. function loadLazyRoute(route, type, manifest, mapRouteProperties2, lazyRoutePropertiesToSkip) {
  4247. let routeToUpdate = manifest[route.id];
  4248. invariant(routeToUpdate, "No route found in manifest");
  4249. if (!route.lazy) {
  4250. return {
  4251. lazyRoutePromise: void 0,
  4252. lazyHandlerPromise: void 0
  4253. };
  4254. }
  4255. if (typeof route.lazy === "function") {
  4256. let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
  4257. if (cachedPromise) {
  4258. return {
  4259. lazyRoutePromise: cachedPromise,
  4260. lazyHandlerPromise: cachedPromise
  4261. };
  4262. }
  4263. let lazyRoutePromise2 = (async () => {
  4264. invariant(
  4265. typeof route.lazy === "function",
  4266. "No lazy route function found"
  4267. );
  4268. let lazyRoute = await route.lazy();
  4269. let routeUpdates = {};
  4270. for (let lazyRouteProperty in lazyRoute) {
  4271. let lazyValue = lazyRoute[lazyRouteProperty];
  4272. if (lazyValue === void 0) {
  4273. continue;
  4274. }
  4275. let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
  4276. let staticRouteValue = routeToUpdate[lazyRouteProperty];
  4277. let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
  4278. // on the route updates
  4279. lazyRouteProperty !== "hasErrorBoundary";
  4280. if (isUnsupported) {
  4281. warning(
  4282. !isUnsupported,
  4283. "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored."
  4284. );
  4285. } else if (isStaticallyDefined) {
  4286. warning(
  4287. !isStaticallyDefined,
  4288. `Route "${routeToUpdate.id}" has a static property "${lazyRouteProperty}" defined but its lazy function is also returning a value for this property. The lazy route property "${lazyRouteProperty}" will be ignored.`
  4289. );
  4290. } else {
  4291. routeUpdates[lazyRouteProperty] = lazyValue;
  4292. }
  4293. }
  4294. Object.assign(routeToUpdate, routeUpdates);
  4295. Object.assign(routeToUpdate, {
  4296. // To keep things framework agnostic, we use the provided `mapRouteProperties`
  4297. // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
  4298. // since the logic will differ between frameworks.
  4299. ...mapRouteProperties2(routeToUpdate),
  4300. lazy: void 0
  4301. });
  4302. })();
  4303. lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2);
  4304. lazyRoutePromise2.catch(() => {
  4305. });
  4306. return {
  4307. lazyRoutePromise: lazyRoutePromise2,
  4308. lazyHandlerPromise: lazyRoutePromise2
  4309. };
  4310. }
  4311. let lazyKeys = Object.keys(route.lazy);
  4312. let lazyPropertyPromises = [];
  4313. let lazyHandlerPromise = void 0;
  4314. for (let key of lazyKeys) {
  4315. if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) {
  4316. continue;
  4317. }
  4318. let promise = loadLazyRouteProperty({
  4319. key,
  4320. route,
  4321. manifest,
  4322. mapRouteProperties: mapRouteProperties2
  4323. });
  4324. if (promise) {
  4325. lazyPropertyPromises.push(promise);
  4326. if (key === type) {
  4327. lazyHandlerPromise = promise;
  4328. }
  4329. }
  4330. }
  4331. let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {
  4332. }) : void 0;
  4333. _optionalChain([lazyRoutePromise, 'optionalAccess', _43 => _43.catch, 'call', _44 => _44(() => {
  4334. })]);
  4335. _optionalChain([lazyHandlerPromise, 'optionalAccess', _45 => _45.catch, 'call', _46 => _46(() => {
  4336. })]);
  4337. return {
  4338. lazyRoutePromise,
  4339. lazyHandlerPromise
  4340. };
  4341. }
  4342. function isNonNullable(value) {
  4343. return value !== void 0;
  4344. }
  4345. function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties2) {
  4346. let promises = matches.map(({ route }) => {
  4347. if (typeof route.lazy !== "object" || !route.lazy.middleware) {
  4348. return void 0;
  4349. }
  4350. return loadLazyRouteProperty({
  4351. key: "middleware",
  4352. route,
  4353. manifest,
  4354. mapRouteProperties: mapRouteProperties2
  4355. });
  4356. }).filter(isNonNullable);
  4357. return promises.length > 0 ? Promise.all(promises) : void 0;
  4358. }
  4359. async function defaultDataStrategy(args) {
  4360. let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
  4361. let keyedResults = {};
  4362. let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
  4363. results.forEach((result, i) => {
  4364. keyedResults[matchesToLoad[i].route.id] = result;
  4365. });
  4366. return keyedResults;
  4367. }
  4368. async function defaultDataStrategyWithMiddleware(args) {
  4369. if (!args.matches.some((m) => m.route.middleware)) {
  4370. return defaultDataStrategy(args);
  4371. }
  4372. return runClientMiddlewarePipeline(args, () => defaultDataStrategy(args));
  4373. }
  4374. function runServerMiddlewarePipeline(args, handler, errorHandler) {
  4375. return runMiddlewarePipeline(
  4376. args,
  4377. handler,
  4378. processResult,
  4379. isResponse,
  4380. errorHandler
  4381. );
  4382. function processResult(result) {
  4383. return isDataWithResponseInit(result) ? dataWithResponseInitToResponse(result) : result;
  4384. }
  4385. }
  4386. function runClientMiddlewarePipeline(args, handler) {
  4387. return runMiddlewarePipeline(
  4388. args,
  4389. handler,
  4390. (r) => r,
  4391. // No post-processing needed on the client
  4392. isDataStrategyResults,
  4393. errorHandler
  4394. );
  4395. function errorHandler(error, routeId, nextResult) {
  4396. if (nextResult) {
  4397. return Promise.resolve(
  4398. Object.assign(nextResult.value, {
  4399. [routeId]: { type: "error", result: error }
  4400. })
  4401. );
  4402. } else {
  4403. let { matches } = args;
  4404. let maxBoundaryIdx = Math.min(
  4405. // Throwing route
  4406. Math.max(
  4407. matches.findIndex((m) => m.route.id === routeId),
  4408. 0
  4409. ),
  4410. // or the shallowest route that needs to load data
  4411. Math.max(
  4412. matches.findIndex((m) => m.shouldCallHandler()),
  4413. 0
  4414. )
  4415. );
  4416. let boundaryRouteId = findNearestBoundary(
  4417. matches,
  4418. matches[maxBoundaryIdx].route.id
  4419. ).route.id;
  4420. return Promise.resolve({
  4421. [boundaryRouteId]: { type: "error", result: error }
  4422. });
  4423. }
  4424. }
  4425. }
  4426. async function runMiddlewarePipeline(args, handler, processResult, isResult, errorHandler) {
  4427. let { matches, request, params, context, unstable_pattern } = args;
  4428. let tuples = matches.flatMap(
  4429. (m) => m.route.middleware ? m.route.middleware.map((fn) => [m.route.id, fn]) : []
  4430. );
  4431. let result = await callRouteMiddleware(
  4432. {
  4433. request,
  4434. params,
  4435. context,
  4436. unstable_pattern
  4437. },
  4438. tuples,
  4439. handler,
  4440. processResult,
  4441. isResult,
  4442. errorHandler
  4443. );
  4444. return result;
  4445. }
  4446. async function callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx = 0) {
  4447. let { request } = args;
  4448. if (request.signal.aborted) {
  4449. throw _nullishCoalesce(request.signal.reason, () => ( new Error(`Request aborted: ${request.method} ${request.url}`)));
  4450. }
  4451. let tuple = middlewares[idx];
  4452. if (!tuple) {
  4453. let result = await handler();
  4454. return result;
  4455. }
  4456. let [routeId, middleware] = tuple;
  4457. let nextResult;
  4458. let next = async () => {
  4459. if (nextResult) {
  4460. throw new Error("You may only call `next()` once per middleware");
  4461. }
  4462. try {
  4463. let result = await callRouteMiddleware(
  4464. args,
  4465. middlewares,
  4466. handler,
  4467. processResult,
  4468. isResult,
  4469. errorHandler,
  4470. idx + 1
  4471. );
  4472. nextResult = { value: result };
  4473. return nextResult.value;
  4474. } catch (error) {
  4475. nextResult = { value: await errorHandler(error, routeId, nextResult) };
  4476. return nextResult.value;
  4477. }
  4478. };
  4479. try {
  4480. let value = await middleware(args, next);
  4481. let result = value != null ? processResult(value) : void 0;
  4482. if (isResult(result)) {
  4483. return result;
  4484. } else if (nextResult) {
  4485. return _nullishCoalesce(result, () => ( nextResult.value));
  4486. } else {
  4487. nextResult = { value: await next() };
  4488. return nextResult.value;
  4489. }
  4490. } catch (error) {
  4491. let response = await errorHandler(error, routeId, nextResult);
  4492. return response;
  4493. }
  4494. }
  4495. function getDataStrategyMatchLazyPromises(mapRouteProperties2, manifest, request, match, lazyRoutePropertiesToSkip) {
  4496. let lazyMiddlewarePromise = loadLazyRouteProperty({
  4497. key: "middleware",
  4498. route: match.route,
  4499. manifest,
  4500. mapRouteProperties: mapRouteProperties2
  4501. });
  4502. let lazyRoutePromises = loadLazyRoute(
  4503. match.route,
  4504. isMutationMethod(request.method) ? "action" : "loader",
  4505. manifest,
  4506. mapRouteProperties2,
  4507. lazyRoutePropertiesToSkip
  4508. );
  4509. return {
  4510. middleware: lazyMiddlewarePromise,
  4511. route: lazyRoutePromises.lazyRoutePromise,
  4512. handler: lazyRoutePromises.lazyHandlerPromise
  4513. };
  4514. }
  4515. function getDataStrategyMatch(mapRouteProperties2, manifest, request, unstable_pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, shouldRevalidateArgs = null) {
  4516. let isUsingNewApi = false;
  4517. let _lazyPromises = getDataStrategyMatchLazyPromises(
  4518. mapRouteProperties2,
  4519. manifest,
  4520. request,
  4521. match,
  4522. lazyRoutePropertiesToSkip
  4523. );
  4524. return {
  4525. ...match,
  4526. _lazyPromises,
  4527. shouldLoad,
  4528. shouldRevalidateArgs,
  4529. shouldCallHandler(defaultShouldRevalidate) {
  4530. isUsingNewApi = true;
  4531. if (!shouldRevalidateArgs) {
  4532. return shouldLoad;
  4533. }
  4534. if (typeof defaultShouldRevalidate === "boolean") {
  4535. return shouldRevalidateLoader(match, {
  4536. ...shouldRevalidateArgs,
  4537. defaultShouldRevalidate
  4538. });
  4539. }
  4540. return shouldRevalidateLoader(match, shouldRevalidateArgs);
  4541. },
  4542. resolve(handlerOverride) {
  4543. let { lazy, loader, middleware } = match.route;
  4544. let callHandler = isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (lazy || loader);
  4545. let isMiddlewareOnlyRoute = middleware && middleware.length > 0 && !loader && !lazy;
  4546. if (callHandler && (isMutationMethod(request.method) || !isMiddlewareOnlyRoute)) {
  4547. return callLoaderOrAction({
  4548. request,
  4549. unstable_pattern,
  4550. match,
  4551. lazyHandlerPromise: _optionalChain([_lazyPromises, 'optionalAccess', _47 => _47.handler]),
  4552. lazyRoutePromise: _optionalChain([_lazyPromises, 'optionalAccess', _48 => _48.route]),
  4553. handlerOverride,
  4554. scopedContext
  4555. });
  4556. }
  4557. return Promise.resolve({ type: "data" /* data */, result: void 0 });
  4558. }
  4559. };
  4560. }
  4561. function getTargetedDataStrategyMatches(mapRouteProperties2, manifest, request, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
  4562. return matches.map((match) => {
  4563. if (match.route.id !== targetMatch.route.id) {
  4564. return {
  4565. ...match,
  4566. shouldLoad: false,
  4567. shouldRevalidateArgs,
  4568. shouldCallHandler: () => false,
  4569. _lazyPromises: getDataStrategyMatchLazyPromises(
  4570. mapRouteProperties2,
  4571. manifest,
  4572. request,
  4573. match,
  4574. lazyRoutePropertiesToSkip
  4575. ),
  4576. resolve: () => Promise.resolve({ type: "data", result: void 0 })
  4577. };
  4578. }
  4579. return getDataStrategyMatch(
  4580. mapRouteProperties2,
  4581. manifest,
  4582. request,
  4583. getRoutePattern(matches),
  4584. match,
  4585. lazyRoutePropertiesToSkip,
  4586. scopedContext,
  4587. true,
  4588. shouldRevalidateArgs
  4589. );
  4590. });
  4591. }
  4592. async function callDataStrategyImpl(dataStrategyImpl, request, matches, fetcherKey, scopedContext, isStaticHandler) {
  4593. if (matches.some((m) => _optionalChain([m, 'access', _49 => _49._lazyPromises, 'optionalAccess', _50 => _50.middleware]))) {
  4594. await Promise.all(matches.map((m) => _optionalChain([m, 'access', _51 => _51._lazyPromises, 'optionalAccess', _52 => _52.middleware])));
  4595. }
  4596. let dataStrategyArgs = {
  4597. request,
  4598. unstable_pattern: getRoutePattern(matches),
  4599. params: matches[0].params,
  4600. context: scopedContext,
  4601. matches
  4602. };
  4603. let runClientMiddleware = isStaticHandler ? () => {
  4604. throw new Error(
  4605. "You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`"
  4606. );
  4607. } : (cb) => {
  4608. let typedDataStrategyArgs = dataStrategyArgs;
  4609. return runClientMiddlewarePipeline(typedDataStrategyArgs, () => {
  4610. return cb({
  4611. ...typedDataStrategyArgs,
  4612. fetcherKey,
  4613. runClientMiddleware: () => {
  4614. throw new Error(
  4615. "Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler"
  4616. );
  4617. }
  4618. });
  4619. });
  4620. };
  4621. let results = await dataStrategyImpl({
  4622. ...dataStrategyArgs,
  4623. fetcherKey,
  4624. runClientMiddleware
  4625. });
  4626. try {
  4627. await Promise.all(
  4628. matches.flatMap((m) => [
  4629. _optionalChain([m, 'access', _53 => _53._lazyPromises, 'optionalAccess', _54 => _54.handler]),
  4630. _optionalChain([m, 'access', _55 => _55._lazyPromises, 'optionalAccess', _56 => _56.route])
  4631. ])
  4632. );
  4633. } catch (e) {
  4634. }
  4635. return results;
  4636. }
  4637. async function callLoaderOrAction({
  4638. request,
  4639. unstable_pattern,
  4640. match,
  4641. lazyHandlerPromise,
  4642. lazyRoutePromise,
  4643. handlerOverride,
  4644. scopedContext
  4645. }) {
  4646. let result;
  4647. let onReject;
  4648. let isAction = isMutationMethod(request.method);
  4649. let type = isAction ? "action" : "loader";
  4650. let runHandler = (handler) => {
  4651. let reject;
  4652. let abortPromise = new Promise((_, r) => reject = r);
  4653. onReject = () => reject();
  4654. request.signal.addEventListener("abort", onReject);
  4655. let actualHandler = (ctx) => {
  4656. if (typeof handler !== "function") {
  4657. return Promise.reject(
  4658. new Error(
  4659. `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
  4660. )
  4661. );
  4662. }
  4663. return handler(
  4664. {
  4665. request,
  4666. unstable_pattern,
  4667. params: match.params,
  4668. context: scopedContext
  4669. },
  4670. ...ctx !== void 0 ? [ctx] : []
  4671. );
  4672. };
  4673. let handlerPromise = (async () => {
  4674. try {
  4675. let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
  4676. return { type: "data", result: val };
  4677. } catch (e) {
  4678. return { type: "error", result: e };
  4679. }
  4680. })();
  4681. return Promise.race([handlerPromise, abortPromise]);
  4682. };
  4683. try {
  4684. let handler = isAction ? match.route.action : match.route.loader;
  4685. if (lazyHandlerPromise || lazyRoutePromise) {
  4686. if (handler) {
  4687. let handlerError;
  4688. let [value] = await Promise.all([
  4689. // If the handler throws, don't let it immediately bubble out,
  4690. // since we need to let the lazy() execution finish so we know if this
  4691. // route has a boundary that can handle the error
  4692. runHandler(handler).catch((e) => {
  4693. handlerError = e;
  4694. }),
  4695. // Ensure all lazy route promises are resolved before continuing
  4696. lazyHandlerPromise,
  4697. lazyRoutePromise
  4698. ]);
  4699. if (handlerError !== void 0) {
  4700. throw handlerError;
  4701. }
  4702. result = value;
  4703. } else {
  4704. await lazyHandlerPromise;
  4705. let handler2 = isAction ? match.route.action : match.route.loader;
  4706. if (handler2) {
  4707. [result] = await Promise.all([runHandler(handler2), lazyRoutePromise]);
  4708. } else if (type === "action") {
  4709. let url = new URL(request.url);
  4710. let pathname = url.pathname + url.search;
  4711. throw getInternalRouterError(405, {
  4712. method: request.method,
  4713. pathname,
  4714. routeId: match.route.id
  4715. });
  4716. } else {
  4717. return { type: "data" /* data */, result: void 0 };
  4718. }
  4719. }
  4720. } else if (!handler) {
  4721. let url = new URL(request.url);
  4722. let pathname = url.pathname + url.search;
  4723. throw getInternalRouterError(404, {
  4724. pathname
  4725. });
  4726. } else {
  4727. result = await runHandler(handler);
  4728. }
  4729. } catch (e) {
  4730. return { type: "error" /* error */, result: e };
  4731. } finally {
  4732. if (onReject) {
  4733. request.signal.removeEventListener("abort", onReject);
  4734. }
  4735. }
  4736. return result;
  4737. }
  4738. async function parseResponseBody(response) {
  4739. let contentType = response.headers.get("Content-Type");
  4740. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  4741. return response.body == null ? null : response.json();
  4742. }
  4743. return response.text();
  4744. }
  4745. async function convertDataStrategyResultToDataResult(dataStrategyResult) {
  4746. let { result, type } = dataStrategyResult;
  4747. if (isResponse(result)) {
  4748. let data2;
  4749. try {
  4750. data2 = await parseResponseBody(result);
  4751. } catch (e) {
  4752. return { type: "error" /* error */, error: e };
  4753. }
  4754. if (type === "error" /* error */) {
  4755. return {
  4756. type: "error" /* error */,
  4757. error: new ErrorResponseImpl(result.status, result.statusText, data2),
  4758. statusCode: result.status,
  4759. headers: result.headers
  4760. };
  4761. }
  4762. return {
  4763. type: "data" /* data */,
  4764. data: data2,
  4765. statusCode: result.status,
  4766. headers: result.headers
  4767. };
  4768. }
  4769. if (type === "error" /* error */) {
  4770. if (isDataWithResponseInit(result)) {
  4771. if (result.data instanceof Error) {
  4772. return {
  4773. type: "error" /* error */,
  4774. error: result.data,
  4775. statusCode: _optionalChain([result, 'access', _57 => _57.init, 'optionalAccess', _58 => _58.status]),
  4776. headers: _optionalChain([result, 'access', _59 => _59.init, 'optionalAccess', _60 => _60.headers]) ? new Headers(result.init.headers) : void 0
  4777. };
  4778. }
  4779. return {
  4780. type: "error" /* error */,
  4781. error: dataWithResponseInitToErrorResponse(result),
  4782. statusCode: isRouteErrorResponse(result) ? result.status : void 0,
  4783. headers: _optionalChain([result, 'access', _61 => _61.init, 'optionalAccess', _62 => _62.headers]) ? new Headers(result.init.headers) : void 0
  4784. };
  4785. }
  4786. return {
  4787. type: "error" /* error */,
  4788. error: result,
  4789. statusCode: isRouteErrorResponse(result) ? result.status : void 0
  4790. };
  4791. }
  4792. if (isDataWithResponseInit(result)) {
  4793. return {
  4794. type: "data" /* data */,
  4795. data: result.data,
  4796. statusCode: _optionalChain([result, 'access', _63 => _63.init, 'optionalAccess', _64 => _64.status]),
  4797. headers: _optionalChain([result, 'access', _65 => _65.init, 'optionalAccess', _66 => _66.headers]) ? new Headers(result.init.headers) : void 0
  4798. };
  4799. }
  4800. return { type: "data" /* data */, data: result };
  4801. }
  4802. function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
  4803. let location = response.headers.get("Location");
  4804. invariant(
  4805. location,
  4806. "Redirects returned/thrown from loaders/actions must have a Location header"
  4807. );
  4808. if (!isAbsoluteUrl(location)) {
  4809. let trimmedMatches = matches.slice(
  4810. 0,
  4811. matches.findIndex((m) => m.route.id === routeId) + 1
  4812. );
  4813. location = normalizeTo(
  4814. new URL(request.url),
  4815. trimmedMatches,
  4816. basename,
  4817. location
  4818. );
  4819. response.headers.set("Location", location);
  4820. }
  4821. return response;
  4822. }
  4823. function normalizeRedirectLocation(location, currentUrl, basename) {
  4824. if (isAbsoluteUrl(location)) {
  4825. let normalizedLocation = location;
  4826. let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
  4827. let isSameBasename = stripBasename(url.pathname, basename) != null;
  4828. if (url.origin === currentUrl.origin && isSameBasename) {
  4829. return url.pathname + url.search + url.hash;
  4830. }
  4831. }
  4832. return location;
  4833. }
  4834. function createClientSideRequest(history, location, signal, submission) {
  4835. let url = history.createURL(stripHashFromPath(location)).toString();
  4836. let init = { signal };
  4837. if (submission && isMutationMethod(submission.formMethod)) {
  4838. let { formMethod, formEncType } = submission;
  4839. init.method = formMethod.toUpperCase();
  4840. if (formEncType === "application/json") {
  4841. init.headers = new Headers({ "Content-Type": formEncType });
  4842. init.body = JSON.stringify(submission.json);
  4843. } else if (formEncType === "text/plain") {
  4844. init.body = submission.text;
  4845. } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
  4846. init.body = convertFormDataToSearchParams(submission.formData);
  4847. } else {
  4848. init.body = submission.formData;
  4849. }
  4850. }
  4851. return new Request(url, init);
  4852. }
  4853. function convertFormDataToSearchParams(formData) {
  4854. let searchParams = new URLSearchParams();
  4855. for (let [key, value] of formData.entries()) {
  4856. searchParams.append(key, typeof value === "string" ? value : value.name);
  4857. }
  4858. return searchParams;
  4859. }
  4860. function convertSearchParamsToFormData(searchParams) {
  4861. let formData = new FormData();
  4862. for (let [key, value] of searchParams.entries()) {
  4863. formData.append(key, value);
  4864. }
  4865. return formData;
  4866. }
  4867. function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
  4868. let loaderData = {};
  4869. let errors = null;
  4870. let statusCode;
  4871. let foundError = false;
  4872. let loaderHeaders = {};
  4873. let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
  4874. matches.forEach((match) => {
  4875. if (!(match.route.id in results)) {
  4876. return;
  4877. }
  4878. let id = match.route.id;
  4879. let result = results[id];
  4880. invariant(
  4881. !isRedirectResult(result),
  4882. "Cannot handle redirect results in processLoaderData"
  4883. );
  4884. if (isErrorResult(result)) {
  4885. let error = result.error;
  4886. if (pendingError !== void 0) {
  4887. error = pendingError;
  4888. pendingError = void 0;
  4889. }
  4890. errors = errors || {};
  4891. if (skipLoaderErrorBubbling) {
  4892. errors[id] = error;
  4893. } else {
  4894. let boundaryMatch = findNearestBoundary(matches, id);
  4895. if (errors[boundaryMatch.route.id] == null) {
  4896. errors[boundaryMatch.route.id] = error;
  4897. }
  4898. }
  4899. if (!isStaticHandler) {
  4900. loaderData[id] = ResetLoaderDataSymbol;
  4901. }
  4902. if (!foundError) {
  4903. foundError = true;
  4904. statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
  4905. }
  4906. if (result.headers) {
  4907. loaderHeaders[id] = result.headers;
  4908. }
  4909. } else {
  4910. loaderData[id] = result.data;
  4911. if (result.statusCode && result.statusCode !== 200 && !foundError) {
  4912. statusCode = result.statusCode;
  4913. }
  4914. if (result.headers) {
  4915. loaderHeaders[id] = result.headers;
  4916. }
  4917. }
  4918. });
  4919. if (pendingError !== void 0 && pendingActionResult) {
  4920. errors = { [pendingActionResult[0]]: pendingError };
  4921. if (pendingActionResult[2]) {
  4922. loaderData[pendingActionResult[2]] = void 0;
  4923. }
  4924. }
  4925. return {
  4926. loaderData,
  4927. errors,
  4928. statusCode: statusCode || 200,
  4929. loaderHeaders
  4930. };
  4931. }
  4932. function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults) {
  4933. let { loaderData, errors } = processRouteLoaderData(
  4934. matches,
  4935. results,
  4936. pendingActionResult
  4937. );
  4938. revalidatingFetchers.filter((f) => !f.matches || f.matches.some((m) => m.shouldLoad)).forEach((rf) => {
  4939. let { key, match, controller } = rf;
  4940. if (controller && controller.signal.aborted) {
  4941. return;
  4942. }
  4943. let result = fetcherResults[key];
  4944. invariant(result, "Did not find corresponding fetcher result");
  4945. if (isErrorResult(result)) {
  4946. let boundaryMatch = findNearestBoundary(state.matches, _optionalChain([match, 'optionalAccess', _67 => _67.route, 'access', _68 => _68.id]));
  4947. if (!(errors && errors[boundaryMatch.route.id])) {
  4948. errors = {
  4949. ...errors,
  4950. [boundaryMatch.route.id]: result.error
  4951. };
  4952. }
  4953. state.fetchers.delete(key);
  4954. } else if (isRedirectResult(result)) {
  4955. invariant(false, "Unhandled fetcher revalidation redirect");
  4956. } else {
  4957. let doneFetcher = getDoneFetcher(result.data);
  4958. state.fetchers.set(key, doneFetcher);
  4959. }
  4960. });
  4961. return { loaderData, errors };
  4962. }
  4963. function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
  4964. let mergedLoaderData = Object.entries(newLoaderData).filter(([, v]) => v !== ResetLoaderDataSymbol).reduce((merged, [k, v]) => {
  4965. merged[k] = v;
  4966. return merged;
  4967. }, {});
  4968. for (let match of matches) {
  4969. let id = match.route.id;
  4970. if (!newLoaderData.hasOwnProperty(id) && loaderData.hasOwnProperty(id) && match.route.loader) {
  4971. mergedLoaderData[id] = loaderData[id];
  4972. }
  4973. if (errors && errors.hasOwnProperty(id)) {
  4974. break;
  4975. }
  4976. }
  4977. return mergedLoaderData;
  4978. }
  4979. function getActionDataForCommit(pendingActionResult) {
  4980. if (!pendingActionResult) {
  4981. return {};
  4982. }
  4983. return isErrorResult(pendingActionResult[1]) ? {
  4984. // Clear out prior actionData on errors
  4985. actionData: {}
  4986. } : {
  4987. actionData: {
  4988. [pendingActionResult[0]]: pendingActionResult[1].data
  4989. }
  4990. };
  4991. }
  4992. function findNearestBoundary(matches, routeId) {
  4993. let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
  4994. return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
  4995. }
  4996. function getShortCircuitMatches(routes) {
  4997. let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
  4998. id: `__shim-error-route__`
  4999. };
  5000. return {
  5001. matches: [
  5002. {
  5003. params: {},
  5004. pathname: "",
  5005. pathnameBase: "",
  5006. route
  5007. }
  5008. ],
  5009. route
  5010. };
  5011. }
  5012. function getInternalRouterError(status, {
  5013. pathname,
  5014. routeId,
  5015. method,
  5016. type,
  5017. message
  5018. } = {}) {
  5019. let statusText = "Unknown Server Error";
  5020. let errorMessage = "Unknown @remix-run/router error";
  5021. if (status === 400) {
  5022. statusText = "Bad Request";
  5023. if (method && pathname && routeId) {
  5024. errorMessage = `You made a ${method} request to "${pathname}" but did not provide a \`loader\` for route "${routeId}", so there is no way to handle the request.`;
  5025. } else if (type === "invalid-body") {
  5026. errorMessage = "Unable to encode submission body";
  5027. }
  5028. } else if (status === 403) {
  5029. statusText = "Forbidden";
  5030. errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
  5031. } else if (status === 404) {
  5032. statusText = "Not Found";
  5033. errorMessage = `No route matches URL "${pathname}"`;
  5034. } else if (status === 405) {
  5035. statusText = "Method Not Allowed";
  5036. if (method && pathname && routeId) {
  5037. errorMessage = `You made a ${method.toUpperCase()} request to "${pathname}" but did not provide an \`action\` for route "${routeId}", so there is no way to handle the request.`;
  5038. } else if (method) {
  5039. errorMessage = `Invalid request method "${method.toUpperCase()}"`;
  5040. }
  5041. }
  5042. return new ErrorResponseImpl(
  5043. status || 500,
  5044. statusText,
  5045. new Error(errorMessage),
  5046. true
  5047. );
  5048. }
  5049. function findRedirect(results) {
  5050. let entries = Object.entries(results);
  5051. for (let i = entries.length - 1; i >= 0; i--) {
  5052. let [key, result] = entries[i];
  5053. if (isRedirectResult(result)) {
  5054. return { key, result };
  5055. }
  5056. }
  5057. }
  5058. function stripHashFromPath(path) {
  5059. let parsedPath = typeof path === "string" ? parsePath(path) : path;
  5060. return createPath({ ...parsedPath, hash: "" });
  5061. }
  5062. function isHashChangeOnly(a, b) {
  5063. if (a.pathname !== b.pathname || a.search !== b.search) {
  5064. return false;
  5065. }
  5066. if (a.hash === "") {
  5067. return b.hash !== "";
  5068. } else if (a.hash === b.hash) {
  5069. return true;
  5070. } else if (b.hash !== "") {
  5071. return true;
  5072. }
  5073. return false;
  5074. }
  5075. function dataWithResponseInitToResponse(data2) {
  5076. return Response.json(data2.data, _nullishCoalesce(data2.init, () => ( void 0)));
  5077. }
  5078. function dataWithResponseInitToErrorResponse(data2) {
  5079. return new ErrorResponseImpl(
  5080. _nullishCoalesce(_optionalChain([data2, 'access', _69 => _69.init, 'optionalAccess', _70 => _70.status]), () => ( 500)),
  5081. _nullishCoalesce(_optionalChain([data2, 'access', _71 => _71.init, 'optionalAccess', _72 => _72.statusText]), () => ( "Internal Server Error")),
  5082. data2.data
  5083. );
  5084. }
  5085. function isDataStrategyResults(result) {
  5086. return result != null && typeof result === "object" && Object.entries(result).every(
  5087. ([key, value]) => typeof key === "string" && isDataStrategyResult(value)
  5088. );
  5089. }
  5090. function isDataStrategyResult(result) {
  5091. return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" /* data */ || result.type === "error" /* error */);
  5092. }
  5093. function isRedirectDataStrategyResult(result) {
  5094. return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
  5095. }
  5096. function isErrorResult(result) {
  5097. return result.type === "error" /* error */;
  5098. }
  5099. function isRedirectResult(result) {
  5100. return (result && result.type) === "redirect" /* redirect */;
  5101. }
  5102. function isDataWithResponseInit(value) {
  5103. return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
  5104. }
  5105. function isResponse(value) {
  5106. return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
  5107. }
  5108. function isRedirectStatusCode(statusCode) {
  5109. return redirectStatusCodes.has(statusCode);
  5110. }
  5111. function isRedirectResponse(result) {
  5112. return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
  5113. }
  5114. function isValidMethod(method) {
  5115. return validRequestMethods.has(method.toUpperCase());
  5116. }
  5117. function isMutationMethod(method) {
  5118. return validMutationMethods.has(method.toUpperCase());
  5119. }
  5120. function hasNakedIndexQuery(search) {
  5121. return new URLSearchParams(search).getAll("index").some((v) => v === "");
  5122. }
  5123. function getTargetMatch(matches, location) {
  5124. let search = typeof location === "string" ? parsePath(location).search : location.search;
  5125. if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
  5126. return matches[matches.length - 1];
  5127. }
  5128. let pathMatches = getPathContributingMatches(matches);
  5129. return pathMatches[pathMatches.length - 1];
  5130. }
  5131. function getSubmissionFromNavigation(navigation) {
  5132. let { formMethod, formAction, formEncType, text, formData, json } = navigation;
  5133. if (!formMethod || !formAction || !formEncType) {
  5134. return;
  5135. }
  5136. if (text != null) {
  5137. return {
  5138. formMethod,
  5139. formAction,
  5140. formEncType,
  5141. formData: void 0,
  5142. json: void 0,
  5143. text
  5144. };
  5145. } else if (formData != null) {
  5146. return {
  5147. formMethod,
  5148. formAction,
  5149. formEncType,
  5150. formData,
  5151. json: void 0,
  5152. text: void 0
  5153. };
  5154. } else if (json !== void 0) {
  5155. return {
  5156. formMethod,
  5157. formAction,
  5158. formEncType,
  5159. formData: void 0,
  5160. json,
  5161. text: void 0
  5162. };
  5163. }
  5164. }
  5165. function getLoadingNavigation(location, submission) {
  5166. if (submission) {
  5167. let navigation = {
  5168. state: "loading",
  5169. location,
  5170. formMethod: submission.formMethod,
  5171. formAction: submission.formAction,
  5172. formEncType: submission.formEncType,
  5173. formData: submission.formData,
  5174. json: submission.json,
  5175. text: submission.text
  5176. };
  5177. return navigation;
  5178. } else {
  5179. let navigation = {
  5180. state: "loading",
  5181. location,
  5182. formMethod: void 0,
  5183. formAction: void 0,
  5184. formEncType: void 0,
  5185. formData: void 0,
  5186. json: void 0,
  5187. text: void 0
  5188. };
  5189. return navigation;
  5190. }
  5191. }
  5192. function getSubmittingNavigation(location, submission) {
  5193. let navigation = {
  5194. state: "submitting",
  5195. location,
  5196. formMethod: submission.formMethod,
  5197. formAction: submission.formAction,
  5198. formEncType: submission.formEncType,
  5199. formData: submission.formData,
  5200. json: submission.json,
  5201. text: submission.text
  5202. };
  5203. return navigation;
  5204. }
  5205. function getLoadingFetcher(submission, data2) {
  5206. if (submission) {
  5207. let fetcher = {
  5208. state: "loading",
  5209. formMethod: submission.formMethod,
  5210. formAction: submission.formAction,
  5211. formEncType: submission.formEncType,
  5212. formData: submission.formData,
  5213. json: submission.json,
  5214. text: submission.text,
  5215. data: data2
  5216. };
  5217. return fetcher;
  5218. } else {
  5219. let fetcher = {
  5220. state: "loading",
  5221. formMethod: void 0,
  5222. formAction: void 0,
  5223. formEncType: void 0,
  5224. formData: void 0,
  5225. json: void 0,
  5226. text: void 0,
  5227. data: data2
  5228. };
  5229. return fetcher;
  5230. }
  5231. }
  5232. function getSubmittingFetcher(submission, existingFetcher) {
  5233. let fetcher = {
  5234. state: "submitting",
  5235. formMethod: submission.formMethod,
  5236. formAction: submission.formAction,
  5237. formEncType: submission.formEncType,
  5238. formData: submission.formData,
  5239. json: submission.json,
  5240. text: submission.text,
  5241. data: existingFetcher ? existingFetcher.data : void 0
  5242. };
  5243. return fetcher;
  5244. }
  5245. function getDoneFetcher(data2) {
  5246. let fetcher = {
  5247. state: "idle",
  5248. formMethod: void 0,
  5249. formAction: void 0,
  5250. formEncType: void 0,
  5251. formData: void 0,
  5252. json: void 0,
  5253. text: void 0,
  5254. data: data2
  5255. };
  5256. return fetcher;
  5257. }
  5258. function restoreAppliedTransitions(_window, transitions) {
  5259. try {
  5260. let sessionPositions = _window.sessionStorage.getItem(
  5261. TRANSITIONS_STORAGE_KEY
  5262. );
  5263. if (sessionPositions) {
  5264. let json = JSON.parse(sessionPositions);
  5265. for (let [k, v] of Object.entries(json || {})) {
  5266. if (v && Array.isArray(v)) {
  5267. transitions.set(k, new Set(v || []));
  5268. }
  5269. }
  5270. }
  5271. } catch (e) {
  5272. }
  5273. }
  5274. function persistAppliedTransitions(_window, transitions) {
  5275. if (transitions.size > 0) {
  5276. let json = {};
  5277. for (let [k, v] of transitions) {
  5278. json[k] = [...v];
  5279. }
  5280. try {
  5281. _window.sessionStorage.setItem(
  5282. TRANSITIONS_STORAGE_KEY,
  5283. JSON.stringify(json)
  5284. );
  5285. } catch (error) {
  5286. warning(
  5287. false,
  5288. `Failed to save applied view transitions in sessionStorage (${error}).`
  5289. );
  5290. }
  5291. }
  5292. }
  5293. function createDeferred() {
  5294. let resolve;
  5295. let reject;
  5296. let promise = new Promise((res, rej) => {
  5297. resolve = async (val) => {
  5298. res(val);
  5299. try {
  5300. await promise;
  5301. } catch (e) {
  5302. }
  5303. };
  5304. reject = async (error) => {
  5305. rej(error);
  5306. try {
  5307. await promise;
  5308. } catch (e) {
  5309. }
  5310. };
  5311. });
  5312. return {
  5313. promise,
  5314. //@ts-ignore
  5315. resolve,
  5316. //@ts-ignore
  5317. reject
  5318. };
  5319. }
  5320. // lib/dom/ssr/single-fetch.tsx
  5321. var _react = require('react'); var React = _interopRequireWildcard(_react); var React2 = _interopRequireWildcard(_react); var React3 = _interopRequireWildcard(_react); var React8 = _interopRequireWildcard(_react); var React7 = _interopRequireWildcard(_react); var React6 = _interopRequireWildcard(_react); var React5 = _interopRequireWildcard(_react); var React4 = _interopRequireWildcard(_react); var React9 = _interopRequireWildcard(_react);
  5322. // vendor/turbo-stream-v2/utils.ts
  5323. var HOLE = -1;
  5324. var NAN = -2;
  5325. var NEGATIVE_INFINITY = -3;
  5326. var NEGATIVE_ZERO = -4;
  5327. var NULL = -5;
  5328. var POSITIVE_INFINITY = -6;
  5329. var UNDEFINED = -7;
  5330. var TYPE_BIGINT = "B";
  5331. var TYPE_DATE = "D";
  5332. var TYPE_ERROR = "E";
  5333. var TYPE_MAP = "M";
  5334. var TYPE_NULL_OBJECT = "N";
  5335. var TYPE_PROMISE = "P";
  5336. var TYPE_REGEXP = "R";
  5337. var TYPE_SET = "S";
  5338. var TYPE_SYMBOL = "Y";
  5339. var TYPE_URL = "U";
  5340. var TYPE_PREVIOUS_RESOLVED = "Z";
  5341. var Deferred = class {
  5342. constructor() {
  5343. this.promise = new Promise((resolve, reject) => {
  5344. this.resolve = resolve;
  5345. this.reject = reject;
  5346. });
  5347. }
  5348. };
  5349. function createLineSplittingTransform() {
  5350. const decoder = new TextDecoder();
  5351. let leftover = "";
  5352. return new TransformStream({
  5353. transform(chunk, controller) {
  5354. const str = decoder.decode(chunk, { stream: true });
  5355. const parts = (leftover + str).split("\n");
  5356. leftover = parts.pop() || "";
  5357. for (const part of parts) {
  5358. controller.enqueue(part);
  5359. }
  5360. },
  5361. flush(controller) {
  5362. if (leftover) {
  5363. controller.enqueue(leftover);
  5364. }
  5365. }
  5366. });
  5367. }
  5368. // vendor/turbo-stream-v2/flatten.ts
  5369. function flatten(input) {
  5370. const { indices } = this;
  5371. const existing = indices.get(input);
  5372. if (existing) return [existing];
  5373. if (input === void 0) return UNDEFINED;
  5374. if (input === null) return NULL;
  5375. if (Number.isNaN(input)) return NAN;
  5376. if (input === Number.POSITIVE_INFINITY) return POSITIVE_INFINITY;
  5377. if (input === Number.NEGATIVE_INFINITY) return NEGATIVE_INFINITY;
  5378. if (input === 0 && 1 / input < 0) return NEGATIVE_ZERO;
  5379. const index = this.index++;
  5380. indices.set(input, index);
  5381. stringify.call(this, input, index);
  5382. return index;
  5383. }
  5384. function stringify(input, index) {
  5385. const { deferred, plugins, postPlugins } = this;
  5386. const str = this.stringified;
  5387. const stack = [[input, index]];
  5388. while (stack.length > 0) {
  5389. const [input2, index2] = stack.pop();
  5390. const partsForObj = (obj) => Object.keys(obj).map((k) => `"_${flatten.call(this, k)}":${flatten.call(this, obj[k])}`).join(",");
  5391. let error = null;
  5392. switch (typeof input2) {
  5393. case "boolean":
  5394. case "number":
  5395. case "string":
  5396. str[index2] = JSON.stringify(input2);
  5397. break;
  5398. case "bigint":
  5399. str[index2] = `["${TYPE_BIGINT}","${input2}"]`;
  5400. break;
  5401. case "symbol": {
  5402. const keyFor = Symbol.keyFor(input2);
  5403. if (!keyFor) {
  5404. error = new Error(
  5405. "Cannot encode symbol unless created with Symbol.for()"
  5406. );
  5407. } else {
  5408. str[index2] = `["${TYPE_SYMBOL}",${JSON.stringify(keyFor)}]`;
  5409. }
  5410. break;
  5411. }
  5412. case "object": {
  5413. if (!input2) {
  5414. str[index2] = `${NULL}`;
  5415. break;
  5416. }
  5417. const isArray = Array.isArray(input2);
  5418. let pluginHandled = false;
  5419. if (!isArray && plugins) {
  5420. for (const plugin of plugins) {
  5421. const pluginResult = plugin(input2);
  5422. if (Array.isArray(pluginResult)) {
  5423. pluginHandled = true;
  5424. const [pluginIdentifier, ...rest] = pluginResult;
  5425. str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
  5426. if (rest.length > 0) {
  5427. str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`;
  5428. }
  5429. str[index2] += "]";
  5430. break;
  5431. }
  5432. }
  5433. }
  5434. if (!pluginHandled) {
  5435. let result = isArray ? "[" : "{";
  5436. if (isArray) {
  5437. for (let i = 0; i < input2.length; i++)
  5438. result += (i ? "," : "") + (i in input2 ? flatten.call(this, input2[i]) : HOLE);
  5439. str[index2] = `${result}]`;
  5440. } else if (input2 instanceof Date) {
  5441. const dateTime = input2.getTime();
  5442. str[index2] = `["${TYPE_DATE}",${Number.isNaN(dateTime) ? JSON.stringify("invalid") : dateTime}]`;
  5443. } else if (input2 instanceof URL) {
  5444. str[index2] = `["${TYPE_URL}",${JSON.stringify(input2.href)}]`;
  5445. } else if (input2 instanceof RegExp) {
  5446. str[index2] = `["${TYPE_REGEXP}",${JSON.stringify(
  5447. input2.source
  5448. )},${JSON.stringify(input2.flags)}]`;
  5449. } else if (input2 instanceof Set) {
  5450. if (input2.size > 0) {
  5451. str[index2] = `["${TYPE_SET}",${[...input2].map((val) => flatten.call(this, val)).join(",")}]`;
  5452. } else {
  5453. str[index2] = `["${TYPE_SET}"]`;
  5454. }
  5455. } else if (input2 instanceof Map) {
  5456. if (input2.size > 0) {
  5457. str[index2] = `["${TYPE_MAP}",${[...input2].flatMap(([k, v]) => [
  5458. flatten.call(this, k),
  5459. flatten.call(this, v)
  5460. ]).join(",")}]`;
  5461. } else {
  5462. str[index2] = `["${TYPE_MAP}"]`;
  5463. }
  5464. } else if (input2 instanceof Promise) {
  5465. str[index2] = `["${TYPE_PROMISE}",${index2}]`;
  5466. deferred[index2] = input2;
  5467. } else if (input2 instanceof Error) {
  5468. str[index2] = `["${TYPE_ERROR}",${JSON.stringify(input2.message)}`;
  5469. if (input2.name !== "Error") {
  5470. str[index2] += `,${JSON.stringify(input2.name)}`;
  5471. }
  5472. str[index2] += "]";
  5473. } else if (Object.getPrototypeOf(input2) === null) {
  5474. str[index2] = `["${TYPE_NULL_OBJECT}",{${partsForObj(input2)}}]`;
  5475. } else if (isPlainObject2(input2)) {
  5476. str[index2] = `{${partsForObj(input2)}}`;
  5477. } else {
  5478. error = new Error("Cannot encode object with prototype");
  5479. }
  5480. }
  5481. break;
  5482. }
  5483. default: {
  5484. const isArray = Array.isArray(input2);
  5485. let pluginHandled = false;
  5486. if (!isArray && plugins) {
  5487. for (const plugin of plugins) {
  5488. const pluginResult = plugin(input2);
  5489. if (Array.isArray(pluginResult)) {
  5490. pluginHandled = true;
  5491. const [pluginIdentifier, ...rest] = pluginResult;
  5492. str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
  5493. if (rest.length > 0) {
  5494. str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`;
  5495. }
  5496. str[index2] += "]";
  5497. break;
  5498. }
  5499. }
  5500. }
  5501. if (!pluginHandled) {
  5502. error = new Error("Cannot encode function or unexpected type");
  5503. }
  5504. }
  5505. }
  5506. if (error) {
  5507. let pluginHandled = false;
  5508. if (postPlugins) {
  5509. for (const plugin of postPlugins) {
  5510. const pluginResult = plugin(input2);
  5511. if (Array.isArray(pluginResult)) {
  5512. pluginHandled = true;
  5513. const [pluginIdentifier, ...rest] = pluginResult;
  5514. str[index2] = `[${JSON.stringify(pluginIdentifier)}`;
  5515. if (rest.length > 0) {
  5516. str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`;
  5517. }
  5518. str[index2] += "]";
  5519. break;
  5520. }
  5521. }
  5522. }
  5523. if (!pluginHandled) {
  5524. throw error;
  5525. }
  5526. }
  5527. }
  5528. }
  5529. var objectProtoNames2 = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
  5530. function isPlainObject2(thing) {
  5531. const proto = Object.getPrototypeOf(thing);
  5532. return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames2;
  5533. }
  5534. // vendor/turbo-stream-v2/unflatten.ts
  5535. var globalObj = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : void 0;
  5536. function unflatten(parsed) {
  5537. const { hydrated, values } = this;
  5538. if (typeof parsed === "number") return hydrate.call(this, parsed);
  5539. if (!Array.isArray(parsed) || !parsed.length) throw new SyntaxError();
  5540. const startIndex = values.length;
  5541. for (const value of parsed) {
  5542. values.push(value);
  5543. }
  5544. hydrated.length = values.length;
  5545. return hydrate.call(this, startIndex);
  5546. }
  5547. function hydrate(index) {
  5548. const { hydrated, values, deferred, plugins } = this;
  5549. let result;
  5550. const stack = [
  5551. [
  5552. index,
  5553. (v) => {
  5554. result = v;
  5555. }
  5556. ]
  5557. ];
  5558. let postRun = [];
  5559. while (stack.length > 0) {
  5560. const [index2, set] = stack.pop();
  5561. switch (index2) {
  5562. case UNDEFINED:
  5563. set(void 0);
  5564. continue;
  5565. case NULL:
  5566. set(null);
  5567. continue;
  5568. case NAN:
  5569. set(NaN);
  5570. continue;
  5571. case POSITIVE_INFINITY:
  5572. set(Infinity);
  5573. continue;
  5574. case NEGATIVE_INFINITY:
  5575. set(-Infinity);
  5576. continue;
  5577. case NEGATIVE_ZERO:
  5578. set(-0);
  5579. continue;
  5580. }
  5581. if (hydrated[index2]) {
  5582. set(hydrated[index2]);
  5583. continue;
  5584. }
  5585. const value = values[index2];
  5586. if (!value || typeof value !== "object") {
  5587. hydrated[index2] = value;
  5588. set(value);
  5589. continue;
  5590. }
  5591. if (Array.isArray(value)) {
  5592. if (typeof value[0] === "string") {
  5593. const [type, b, c] = value;
  5594. switch (type) {
  5595. case TYPE_DATE:
  5596. set(hydrated[index2] = new Date(b));
  5597. continue;
  5598. case TYPE_URL:
  5599. set(hydrated[index2] = new URL(b));
  5600. continue;
  5601. case TYPE_BIGINT:
  5602. set(hydrated[index2] = BigInt(b));
  5603. continue;
  5604. case TYPE_REGEXP:
  5605. set(hydrated[index2] = new RegExp(b, c));
  5606. continue;
  5607. case TYPE_SYMBOL:
  5608. set(hydrated[index2] = Symbol.for(b));
  5609. continue;
  5610. case TYPE_SET:
  5611. const newSet = /* @__PURE__ */ new Set();
  5612. hydrated[index2] = newSet;
  5613. for (let i = value.length - 1; i > 0; i--)
  5614. stack.push([
  5615. value[i],
  5616. (v) => {
  5617. newSet.add(v);
  5618. }
  5619. ]);
  5620. set(newSet);
  5621. continue;
  5622. case TYPE_MAP:
  5623. const map = /* @__PURE__ */ new Map();
  5624. hydrated[index2] = map;
  5625. for (let i = value.length - 2; i > 0; i -= 2) {
  5626. const r = [];
  5627. stack.push([
  5628. value[i + 1],
  5629. (v) => {
  5630. r[1] = v;
  5631. }
  5632. ]);
  5633. stack.push([
  5634. value[i],
  5635. (k) => {
  5636. r[0] = k;
  5637. }
  5638. ]);
  5639. postRun.push(() => {
  5640. map.set(r[0], r[1]);
  5641. });
  5642. }
  5643. set(map);
  5644. continue;
  5645. case TYPE_NULL_OBJECT:
  5646. const obj = /* @__PURE__ */ Object.create(null);
  5647. hydrated[index2] = obj;
  5648. for (const key of Object.keys(b).reverse()) {
  5649. const r = [];
  5650. stack.push([
  5651. b[key],
  5652. (v) => {
  5653. r[1] = v;
  5654. }
  5655. ]);
  5656. stack.push([
  5657. Number(key.slice(1)),
  5658. (k) => {
  5659. r[0] = k;
  5660. }
  5661. ]);
  5662. postRun.push(() => {
  5663. obj[r[0]] = r[1];
  5664. });
  5665. }
  5666. set(obj);
  5667. continue;
  5668. case TYPE_PROMISE:
  5669. if (hydrated[b]) {
  5670. set(hydrated[index2] = hydrated[b]);
  5671. } else {
  5672. const d = new Deferred();
  5673. deferred[b] = d;
  5674. set(hydrated[index2] = d.promise);
  5675. }
  5676. continue;
  5677. case TYPE_ERROR:
  5678. const [, message, errorType] = value;
  5679. let error = errorType && globalObj && globalObj[errorType] ? new globalObj[errorType](message) : new Error(message);
  5680. hydrated[index2] = error;
  5681. set(error);
  5682. continue;
  5683. case TYPE_PREVIOUS_RESOLVED:
  5684. set(hydrated[index2] = hydrated[b]);
  5685. continue;
  5686. default:
  5687. if (Array.isArray(plugins)) {
  5688. const r = [];
  5689. const vals = value.slice(1);
  5690. for (let i = 0; i < vals.length; i++) {
  5691. const v = vals[i];
  5692. stack.push([
  5693. v,
  5694. (v2) => {
  5695. r[i] = v2;
  5696. }
  5697. ]);
  5698. }
  5699. postRun.push(() => {
  5700. for (const plugin of plugins) {
  5701. const result2 = plugin(value[0], ...r);
  5702. if (result2) {
  5703. set(hydrated[index2] = result2.value);
  5704. return;
  5705. }
  5706. }
  5707. throw new SyntaxError();
  5708. });
  5709. continue;
  5710. }
  5711. throw new SyntaxError();
  5712. }
  5713. } else {
  5714. const array = [];
  5715. hydrated[index2] = array;
  5716. for (let i = 0; i < value.length; i++) {
  5717. const n = value[i];
  5718. if (n !== HOLE) {
  5719. stack.push([
  5720. n,
  5721. (v) => {
  5722. array[i] = v;
  5723. }
  5724. ]);
  5725. }
  5726. }
  5727. set(array);
  5728. continue;
  5729. }
  5730. } else {
  5731. const object = {};
  5732. hydrated[index2] = object;
  5733. for (const key of Object.keys(value).reverse()) {
  5734. const r = [];
  5735. stack.push([
  5736. value[key],
  5737. (v) => {
  5738. r[1] = v;
  5739. }
  5740. ]);
  5741. stack.push([
  5742. Number(key.slice(1)),
  5743. (k) => {
  5744. r[0] = k;
  5745. }
  5746. ]);
  5747. postRun.push(() => {
  5748. object[r[0]] = r[1];
  5749. });
  5750. }
  5751. set(object);
  5752. continue;
  5753. }
  5754. }
  5755. while (postRun.length > 0) {
  5756. postRun.pop()();
  5757. }
  5758. return result;
  5759. }
  5760. // vendor/turbo-stream-v2/turbo-stream.ts
  5761. async function decode(readable, options) {
  5762. const { plugins } = _nullishCoalesce(options, () => ( {}));
  5763. const done = new Deferred();
  5764. const reader = readable.pipeThrough(createLineSplittingTransform()).getReader();
  5765. const decoder = {
  5766. values: [],
  5767. hydrated: [],
  5768. deferred: {},
  5769. plugins
  5770. };
  5771. const decoded = await decodeInitial.call(decoder, reader);
  5772. let donePromise = done.promise;
  5773. if (decoded.done) {
  5774. done.resolve();
  5775. } else {
  5776. donePromise = decodeDeferred.call(decoder, reader).then(done.resolve).catch((reason) => {
  5777. for (const deferred of Object.values(decoder.deferred)) {
  5778. deferred.reject(reason);
  5779. }
  5780. done.reject(reason);
  5781. });
  5782. }
  5783. return {
  5784. done: donePromise.then(() => reader.closed),
  5785. value: decoded.value
  5786. };
  5787. }
  5788. async function decodeInitial(reader) {
  5789. const read = await reader.read();
  5790. if (!read.value) {
  5791. throw new SyntaxError();
  5792. }
  5793. let line;
  5794. try {
  5795. line = JSON.parse(read.value);
  5796. } catch (reason) {
  5797. throw new SyntaxError();
  5798. }
  5799. return {
  5800. done: read.done,
  5801. value: unflatten.call(this, line)
  5802. };
  5803. }
  5804. async function decodeDeferred(reader) {
  5805. let read = await reader.read();
  5806. while (!read.done) {
  5807. if (!read.value) continue;
  5808. const line = read.value;
  5809. switch (line[0]) {
  5810. case TYPE_PROMISE: {
  5811. const colonIndex = line.indexOf(":");
  5812. const deferredId = Number(line.slice(1, colonIndex));
  5813. const deferred = this.deferred[deferredId];
  5814. if (!deferred) {
  5815. throw new Error(`Deferred ID ${deferredId} not found in stream`);
  5816. }
  5817. const lineData = line.slice(colonIndex + 1);
  5818. let jsonLine;
  5819. try {
  5820. jsonLine = JSON.parse(lineData);
  5821. } catch (reason) {
  5822. throw new SyntaxError();
  5823. }
  5824. const value = unflatten.call(this, jsonLine);
  5825. deferred.resolve(value);
  5826. break;
  5827. }
  5828. case TYPE_ERROR: {
  5829. const colonIndex = line.indexOf(":");
  5830. const deferredId = Number(line.slice(1, colonIndex));
  5831. const deferred = this.deferred[deferredId];
  5832. if (!deferred) {
  5833. throw new Error(`Deferred ID ${deferredId} not found in stream`);
  5834. }
  5835. const lineData = line.slice(colonIndex + 1);
  5836. let jsonLine;
  5837. try {
  5838. jsonLine = JSON.parse(lineData);
  5839. } catch (reason) {
  5840. throw new SyntaxError();
  5841. }
  5842. const value = unflatten.call(this, jsonLine);
  5843. deferred.reject(value);
  5844. break;
  5845. }
  5846. default:
  5847. throw new SyntaxError();
  5848. }
  5849. read = await reader.read();
  5850. }
  5851. }
  5852. function encode(input, options) {
  5853. const { plugins, postPlugins, signal } = _nullishCoalesce(options, () => ( {}));
  5854. const encoder = {
  5855. deferred: {},
  5856. index: 0,
  5857. indices: /* @__PURE__ */ new Map(),
  5858. stringified: [],
  5859. plugins,
  5860. postPlugins,
  5861. signal
  5862. };
  5863. const textEncoder = new TextEncoder();
  5864. let lastSentIndex = 0;
  5865. const readable = new ReadableStream({
  5866. async start(controller) {
  5867. const id = flatten.call(encoder, input);
  5868. if (Array.isArray(id)) {
  5869. throw new Error("This should never happen");
  5870. }
  5871. if (id < 0) {
  5872. controller.enqueue(textEncoder.encode(`${id}
  5873. `));
  5874. } else {
  5875. controller.enqueue(
  5876. textEncoder.encode(`[${encoder.stringified.join(",")}]
  5877. `)
  5878. );
  5879. lastSentIndex = encoder.stringified.length - 1;
  5880. }
  5881. const seenPromises = /* @__PURE__ */ new WeakSet();
  5882. if (Object.keys(encoder.deferred).length) {
  5883. let raceDone;
  5884. const racePromise = new Promise((resolve, reject) => {
  5885. raceDone = resolve;
  5886. if (signal) {
  5887. const rejectPromise = () => reject(signal.reason || new Error("Signal was aborted."));
  5888. if (signal.aborted) {
  5889. rejectPromise();
  5890. } else {
  5891. signal.addEventListener("abort", (event) => {
  5892. rejectPromise();
  5893. });
  5894. }
  5895. }
  5896. });
  5897. while (Object.keys(encoder.deferred).length > 0) {
  5898. for (const [deferredId, deferred] of Object.entries(
  5899. encoder.deferred
  5900. )) {
  5901. if (seenPromises.has(deferred)) continue;
  5902. seenPromises.add(
  5903. // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
  5904. encoder.deferred[Number(deferredId)] = Promise.race([
  5905. racePromise,
  5906. deferred
  5907. ]).then(
  5908. (resolved) => {
  5909. const id2 = flatten.call(encoder, resolved);
  5910. if (Array.isArray(id2)) {
  5911. controller.enqueue(
  5912. textEncoder.encode(
  5913. `${TYPE_PROMISE}${deferredId}:[["${TYPE_PREVIOUS_RESOLVED}",${id2[0]}]]
  5914. `
  5915. )
  5916. );
  5917. encoder.index++;
  5918. lastSentIndex++;
  5919. } else if (id2 < 0) {
  5920. controller.enqueue(
  5921. textEncoder.encode(
  5922. `${TYPE_PROMISE}${deferredId}:${id2}
  5923. `
  5924. )
  5925. );
  5926. } else {
  5927. const values = encoder.stringified.slice(lastSentIndex + 1).join(",");
  5928. controller.enqueue(
  5929. textEncoder.encode(
  5930. `${TYPE_PROMISE}${deferredId}:[${values}]
  5931. `
  5932. )
  5933. );
  5934. lastSentIndex = encoder.stringified.length - 1;
  5935. }
  5936. },
  5937. (reason) => {
  5938. if (!reason || typeof reason !== "object" || !(reason instanceof Error)) {
  5939. reason = new Error("An unknown error occurred");
  5940. }
  5941. const id2 = flatten.call(encoder, reason);
  5942. if (Array.isArray(id2)) {
  5943. controller.enqueue(
  5944. textEncoder.encode(
  5945. `${TYPE_ERROR}${deferredId}:[["${TYPE_PREVIOUS_RESOLVED}",${id2[0]}]]
  5946. `
  5947. )
  5948. );
  5949. encoder.index++;
  5950. lastSentIndex++;
  5951. } else if (id2 < 0) {
  5952. controller.enqueue(
  5953. textEncoder.encode(
  5954. `${TYPE_ERROR}${deferredId}:${id2}
  5955. `
  5956. )
  5957. );
  5958. } else {
  5959. const values = encoder.stringified.slice(lastSentIndex + 1).join(",");
  5960. controller.enqueue(
  5961. textEncoder.encode(
  5962. `${TYPE_ERROR}${deferredId}:[${values}]
  5963. `
  5964. )
  5965. );
  5966. lastSentIndex = encoder.stringified.length - 1;
  5967. }
  5968. }
  5969. ).finally(() => {
  5970. delete encoder.deferred[Number(deferredId)];
  5971. })
  5972. );
  5973. }
  5974. await Promise.race(Object.values(encoder.deferred));
  5975. }
  5976. raceDone();
  5977. }
  5978. await Promise.all(Object.values(encoder.deferred));
  5979. controller.close();
  5980. }
  5981. });
  5982. return readable;
  5983. }
  5984. // lib/dom/ssr/data.ts
  5985. async function createRequestInit(request) {
  5986. let init = { signal: request.signal };
  5987. if (request.method !== "GET") {
  5988. init.method = request.method;
  5989. let contentType = request.headers.get("Content-Type");
  5990. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  5991. init.headers = { "Content-Type": contentType };
  5992. init.body = JSON.stringify(await request.json());
  5993. } else if (contentType && /\btext\/plain\b/.test(contentType)) {
  5994. init.headers = { "Content-Type": contentType };
  5995. init.body = await request.text();
  5996. } else if (contentType && /\bapplication\/x-www-form-urlencoded\b/.test(contentType)) {
  5997. init.body = new URLSearchParams(await request.text());
  5998. } else {
  5999. init.body = await request.formData();
  6000. }
  6001. }
  6002. return init;
  6003. }
  6004. // lib/dom/ssr/markup.ts
  6005. var ESCAPE_LOOKUP = {
  6006. "&": "\\u0026",
  6007. ">": "\\u003e",
  6008. "<": "\\u003c",
  6009. "\u2028": "\\u2028",
  6010. "\u2029": "\\u2029"
  6011. };
  6012. var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
  6013. function escapeHtml(html) {
  6014. return html.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
  6015. }
  6016. // lib/dom/ssr/invariant.ts
  6017. function invariant2(value, message) {
  6018. if (value === false || value === null || typeof value === "undefined") {
  6019. throw new Error(message);
  6020. }
  6021. }
  6022. // lib/dom/ssr/single-fetch.tsx
  6023. var SingleFetchRedirectSymbol = Symbol("SingleFetchRedirect");
  6024. var SingleFetchNoResultError = class extends Error {
  6025. };
  6026. var SINGLE_FETCH_REDIRECT_STATUS = 202;
  6027. var NO_BODY_STATUS_CODES = /* @__PURE__ */ new Set([100, 101, 204, 205]);
  6028. function StreamTransfer({
  6029. context,
  6030. identifier,
  6031. reader,
  6032. textDecoder,
  6033. nonce
  6034. }) {
  6035. if (!context.renderMeta || !context.renderMeta.didRenderScripts) {
  6036. return null;
  6037. }
  6038. if (!context.renderMeta.streamCache) {
  6039. context.renderMeta.streamCache = {};
  6040. }
  6041. let { streamCache } = context.renderMeta;
  6042. let promise = streamCache[identifier];
  6043. if (!promise) {
  6044. promise = streamCache[identifier] = reader.read().then((result) => {
  6045. streamCache[identifier].result = {
  6046. done: result.done,
  6047. value: textDecoder.decode(result.value, { stream: true })
  6048. };
  6049. }).catch((e) => {
  6050. streamCache[identifier].error = e;
  6051. });
  6052. }
  6053. if (promise.error) {
  6054. throw promise.error;
  6055. }
  6056. if (promise.result === void 0) {
  6057. throw promise;
  6058. }
  6059. let { done, value } = promise.result;
  6060. let scriptTag = value ? /* @__PURE__ */ React.createElement(
  6061. "script",
  6062. {
  6063. nonce,
  6064. dangerouslySetInnerHTML: {
  6065. __html: `window.__reactRouterContext.streamController.enqueue(${escapeHtml(
  6066. JSON.stringify(value)
  6067. )});`
  6068. }
  6069. }
  6070. ) : null;
  6071. if (done) {
  6072. return /* @__PURE__ */ React.createElement(React.Fragment, null, scriptTag, /* @__PURE__ */ React.createElement(
  6073. "script",
  6074. {
  6075. nonce,
  6076. dangerouslySetInnerHTML: {
  6077. __html: `window.__reactRouterContext.streamController.close();`
  6078. }
  6079. }
  6080. ));
  6081. } else {
  6082. return /* @__PURE__ */ React.createElement(React.Fragment, null, scriptTag, /* @__PURE__ */ React.createElement(React.Suspense, null, /* @__PURE__ */ React.createElement(
  6083. StreamTransfer,
  6084. {
  6085. context,
  6086. identifier: identifier + 1,
  6087. reader,
  6088. textDecoder,
  6089. nonce
  6090. }
  6091. )));
  6092. }
  6093. }
  6094. function getTurboStreamSingleFetchDataStrategy(getRouter, manifest, routeModules, ssr, basename) {
  6095. let dataStrategy = getSingleFetchDataStrategyImpl(
  6096. getRouter,
  6097. (match) => {
  6098. let manifestRoute = manifest.routes[match.route.id];
  6099. invariant2(manifestRoute, "Route not found in manifest");
  6100. let routeModule = routeModules[match.route.id];
  6101. return {
  6102. hasLoader: manifestRoute.hasLoader,
  6103. hasClientLoader: manifestRoute.hasClientLoader,
  6104. hasShouldRevalidate: Boolean(_optionalChain([routeModule, 'optionalAccess', _73 => _73.shouldRevalidate]))
  6105. };
  6106. },
  6107. fetchAndDecodeViaTurboStream,
  6108. ssr,
  6109. basename
  6110. );
  6111. return async (args) => args.runClientMiddleware(dataStrategy);
  6112. }
  6113. function getSingleFetchDataStrategyImpl(getRouter, getRouteInfo, fetchAndDecode, ssr, basename, shouldAllowOptOut = () => true) {
  6114. return async (args) => {
  6115. let { request, matches, fetcherKey } = args;
  6116. let router = getRouter();
  6117. if (request.method !== "GET") {
  6118. return singleFetchActionStrategy(args, fetchAndDecode, basename);
  6119. }
  6120. let foundRevalidatingServerLoader = matches.some((m) => {
  6121. let { hasLoader, hasClientLoader } = getRouteInfo(m);
  6122. return m.shouldCallHandler() && hasLoader && !hasClientLoader;
  6123. });
  6124. if (!ssr && !foundRevalidatingServerLoader) {
  6125. return nonSsrStrategy(args, getRouteInfo, fetchAndDecode, basename);
  6126. }
  6127. if (fetcherKey) {
  6128. return singleFetchLoaderFetcherStrategy(args, fetchAndDecode, basename);
  6129. }
  6130. return singleFetchLoaderNavigationStrategy(
  6131. args,
  6132. router,
  6133. getRouteInfo,
  6134. fetchAndDecode,
  6135. ssr,
  6136. basename,
  6137. shouldAllowOptOut
  6138. );
  6139. };
  6140. }
  6141. async function singleFetchActionStrategy(args, fetchAndDecode, basename) {
  6142. let actionMatch = args.matches.find((m) => m.shouldCallHandler());
  6143. invariant2(actionMatch, "No action match found");
  6144. let actionStatus = void 0;
  6145. let result = await actionMatch.resolve(async (handler) => {
  6146. let result2 = await handler(async () => {
  6147. let { data: data2, status } = await fetchAndDecode(args, basename, [
  6148. actionMatch.route.id
  6149. ]);
  6150. actionStatus = status;
  6151. return unwrapSingleFetchResult(data2, actionMatch.route.id);
  6152. });
  6153. return result2;
  6154. });
  6155. if (isResponse(result.result) || isRouteErrorResponse(result.result) || isDataWithResponseInit(result.result)) {
  6156. return { [actionMatch.route.id]: result };
  6157. }
  6158. return {
  6159. [actionMatch.route.id]: {
  6160. type: result.type,
  6161. result: data(result.result, actionStatus)
  6162. }
  6163. };
  6164. }
  6165. async function nonSsrStrategy(args, getRouteInfo, fetchAndDecode, basename) {
  6166. let matchesToLoad = args.matches.filter((m) => m.shouldCallHandler());
  6167. let results = {};
  6168. await Promise.all(
  6169. matchesToLoad.map(
  6170. (m) => m.resolve(async (handler) => {
  6171. try {
  6172. let { hasClientLoader } = getRouteInfo(m);
  6173. let routeId = m.route.id;
  6174. let result = hasClientLoader ? await handler(async () => {
  6175. let { data: data2 } = await fetchAndDecode(args, basename, [routeId]);
  6176. return unwrapSingleFetchResult(data2, routeId);
  6177. }) : await handler();
  6178. results[m.route.id] = { type: "data", result };
  6179. } catch (e) {
  6180. results[m.route.id] = { type: "error", result: e };
  6181. }
  6182. })
  6183. )
  6184. );
  6185. return results;
  6186. }
  6187. async function singleFetchLoaderNavigationStrategy(args, router, getRouteInfo, fetchAndDecode, ssr, basename, shouldAllowOptOut = () => true) {
  6188. let routesParams = /* @__PURE__ */ new Set();
  6189. let foundOptOutRoute = false;
  6190. let routeDfds = args.matches.map(() => createDeferred2());
  6191. let singleFetchDfd = createDeferred2();
  6192. let results = {};
  6193. let resolvePromise = Promise.all(
  6194. args.matches.map(
  6195. async (m, i) => m.resolve(async (handler) => {
  6196. routeDfds[i].resolve();
  6197. let routeId = m.route.id;
  6198. let { hasLoader, hasClientLoader, hasShouldRevalidate } = getRouteInfo(m);
  6199. let defaultShouldRevalidate = !m.shouldRevalidateArgs || m.shouldRevalidateArgs.actionStatus == null || m.shouldRevalidateArgs.actionStatus < 400;
  6200. let shouldCall = m.shouldCallHandler(defaultShouldRevalidate);
  6201. if (!shouldCall) {
  6202. foundOptOutRoute || (foundOptOutRoute = m.shouldRevalidateArgs != null && // This is a revalidation,
  6203. hasLoader && // for a route with a server loader,
  6204. hasShouldRevalidate === true);
  6205. return;
  6206. }
  6207. if (shouldAllowOptOut(m) && hasClientLoader) {
  6208. if (hasLoader) {
  6209. foundOptOutRoute = true;
  6210. }
  6211. try {
  6212. let result = await handler(async () => {
  6213. let { data: data2 } = await fetchAndDecode(args, basename, [routeId]);
  6214. return unwrapSingleFetchResult(data2, routeId);
  6215. });
  6216. results[routeId] = { type: "data", result };
  6217. } catch (e) {
  6218. results[routeId] = { type: "error", result: e };
  6219. }
  6220. return;
  6221. }
  6222. if (hasLoader) {
  6223. routesParams.add(routeId);
  6224. }
  6225. try {
  6226. let result = await handler(async () => {
  6227. let data2 = await singleFetchDfd.promise;
  6228. return unwrapSingleFetchResult(data2, routeId);
  6229. });
  6230. results[routeId] = { type: "data", result };
  6231. } catch (e) {
  6232. results[routeId] = { type: "error", result: e };
  6233. }
  6234. })
  6235. )
  6236. );
  6237. await Promise.all(routeDfds.map((d) => d.promise));
  6238. let isInitialLoad = !router.state.initialized && router.state.navigation.state === "idle";
  6239. if ((isInitialLoad || routesParams.size === 0) && !window.__reactRouterHdrActive) {
  6240. singleFetchDfd.resolve({ routes: {} });
  6241. } else {
  6242. let targetRoutes = ssr && foundOptOutRoute && routesParams.size > 0 ? [...routesParams.keys()] : void 0;
  6243. try {
  6244. let data2 = await fetchAndDecode(args, basename, targetRoutes);
  6245. singleFetchDfd.resolve(data2.data);
  6246. } catch (e) {
  6247. singleFetchDfd.reject(e);
  6248. }
  6249. }
  6250. await resolvePromise;
  6251. await bubbleMiddlewareErrors(
  6252. singleFetchDfd.promise,
  6253. args.matches,
  6254. routesParams,
  6255. results
  6256. );
  6257. return results;
  6258. }
  6259. async function bubbleMiddlewareErrors(singleFetchPromise, matches, routesParams, results) {
  6260. try {
  6261. let middlewareError;
  6262. let fetchedData = await singleFetchPromise;
  6263. if ("routes" in fetchedData) {
  6264. for (let match of matches) {
  6265. if (match.route.id in fetchedData.routes) {
  6266. let routeResult = fetchedData.routes[match.route.id];
  6267. if ("error" in routeResult) {
  6268. middlewareError = routeResult.error;
  6269. if (_optionalChain([results, 'access', _74 => _74[match.route.id], 'optionalAccess', _75 => _75.result]) == null) {
  6270. results[match.route.id] = {
  6271. type: "error",
  6272. result: middlewareError
  6273. };
  6274. }
  6275. break;
  6276. }
  6277. }
  6278. }
  6279. }
  6280. if (middlewareError !== void 0) {
  6281. Array.from(routesParams.values()).forEach((routeId) => {
  6282. if (results[routeId].result instanceof SingleFetchNoResultError) {
  6283. results[routeId].result = middlewareError;
  6284. }
  6285. });
  6286. }
  6287. } catch (e) {
  6288. }
  6289. }
  6290. async function singleFetchLoaderFetcherStrategy(args, fetchAndDecode, basename) {
  6291. let fetcherMatch = args.matches.find((m) => m.shouldCallHandler());
  6292. invariant2(fetcherMatch, "No fetcher match found");
  6293. let routeId = fetcherMatch.route.id;
  6294. let result = await fetcherMatch.resolve(
  6295. async (handler) => handler(async () => {
  6296. let { data: data2 } = await fetchAndDecode(args, basename, [routeId]);
  6297. return unwrapSingleFetchResult(data2, routeId);
  6298. })
  6299. );
  6300. return { [fetcherMatch.route.id]: result };
  6301. }
  6302. function stripIndexParam(url) {
  6303. let indexValues = url.searchParams.getAll("index");
  6304. url.searchParams.delete("index");
  6305. let indexValuesToKeep = [];
  6306. for (let indexValue of indexValues) {
  6307. if (indexValue) {
  6308. indexValuesToKeep.push(indexValue);
  6309. }
  6310. }
  6311. for (let toKeep of indexValuesToKeep) {
  6312. url.searchParams.append("index", toKeep);
  6313. }
  6314. return url;
  6315. }
  6316. function singleFetchUrl(reqUrl, basename, extension) {
  6317. let url = typeof reqUrl === "string" ? new URL(
  6318. reqUrl,
  6319. // This can be called during the SSR flow via PrefetchPageLinksImpl so
  6320. // don't assume window is available
  6321. typeof window === "undefined" ? "server://singlefetch/" : window.location.origin
  6322. ) : reqUrl;
  6323. if (url.pathname === "/") {
  6324. url.pathname = `_root.${extension}`;
  6325. } else if (basename && stripBasename(url.pathname, basename) === "/") {
  6326. url.pathname = `${basename.replace(/\/$/, "")}/_root.${extension}`;
  6327. } else {
  6328. url.pathname = `${url.pathname.replace(/\/$/, "")}.${extension}`;
  6329. }
  6330. return url;
  6331. }
  6332. async function fetchAndDecodeViaTurboStream(args, basename, targetRoutes) {
  6333. let { request } = args;
  6334. let url = singleFetchUrl(request.url, basename, "data");
  6335. if (request.method === "GET") {
  6336. url = stripIndexParam(url);
  6337. if (targetRoutes) {
  6338. url.searchParams.set("_routes", targetRoutes.join(","));
  6339. }
  6340. }
  6341. let res = await fetch(url, await createRequestInit(request));
  6342. if (res.status >= 400 && !res.headers.has("X-Remix-Response")) {
  6343. throw new ErrorResponseImpl(res.status, res.statusText, await res.text());
  6344. }
  6345. if (res.status === 204 && res.headers.has("X-Remix-Redirect")) {
  6346. return {
  6347. status: SINGLE_FETCH_REDIRECT_STATUS,
  6348. data: {
  6349. redirect: {
  6350. redirect: res.headers.get("X-Remix-Redirect"),
  6351. status: Number(res.headers.get("X-Remix-Status") || "302"),
  6352. revalidate: res.headers.get("X-Remix-Revalidate") === "true",
  6353. reload: res.headers.get("X-Remix-Reload-Document") === "true",
  6354. replace: res.headers.get("X-Remix-Replace") === "true"
  6355. }
  6356. }
  6357. };
  6358. }
  6359. if (NO_BODY_STATUS_CODES.has(res.status)) {
  6360. let routes = {};
  6361. if (targetRoutes && request.method !== "GET") {
  6362. routes[targetRoutes[0]] = { data: void 0 };
  6363. }
  6364. return {
  6365. status: res.status,
  6366. data: { routes }
  6367. };
  6368. }
  6369. invariant2(res.body, "No response body to decode");
  6370. try {
  6371. let decoded = await decodeViaTurboStream(res.body, window);
  6372. let data2;
  6373. if (request.method === "GET") {
  6374. let typed = decoded.value;
  6375. if (SingleFetchRedirectSymbol in typed) {
  6376. data2 = { redirect: typed[SingleFetchRedirectSymbol] };
  6377. } else {
  6378. data2 = { routes: typed };
  6379. }
  6380. } else {
  6381. let typed = decoded.value;
  6382. let routeId = _optionalChain([targetRoutes, 'optionalAccess', _76 => _76[0]]);
  6383. invariant2(routeId, "No routeId found for single fetch call decoding");
  6384. if ("redirect" in typed) {
  6385. data2 = { redirect: typed };
  6386. } else {
  6387. data2 = { routes: { [routeId]: typed } };
  6388. }
  6389. }
  6390. return { status: res.status, data: data2 };
  6391. } catch (e) {
  6392. throw new Error("Unable to decode turbo-stream response");
  6393. }
  6394. }
  6395. function decodeViaTurboStream(body, global) {
  6396. return decode(body, {
  6397. plugins: [
  6398. (type, ...rest) => {
  6399. if (type === "SanitizedError") {
  6400. let [name, message, stack] = rest;
  6401. let Constructor = Error;
  6402. if (name && name in global && typeof global[name] === "function") {
  6403. Constructor = global[name];
  6404. }
  6405. let error = new Constructor(message);
  6406. error.stack = stack;
  6407. return { value: error };
  6408. }
  6409. if (type === "ErrorResponse") {
  6410. let [data2, status, statusText] = rest;
  6411. return {
  6412. value: new ErrorResponseImpl(status, statusText, data2)
  6413. };
  6414. }
  6415. if (type === "SingleFetchRedirect") {
  6416. return { value: { [SingleFetchRedirectSymbol]: rest[0] } };
  6417. }
  6418. if (type === "SingleFetchClassInstance") {
  6419. return { value: rest[0] };
  6420. }
  6421. if (type === "SingleFetchFallback") {
  6422. return { value: void 0 };
  6423. }
  6424. }
  6425. ]
  6426. });
  6427. }
  6428. function unwrapSingleFetchResult(result, routeId) {
  6429. if ("redirect" in result) {
  6430. let {
  6431. redirect: location,
  6432. revalidate,
  6433. reload,
  6434. replace: replace2,
  6435. status
  6436. } = result.redirect;
  6437. throw redirect(location, {
  6438. status,
  6439. headers: {
  6440. // Three R's of redirecting (lol Veep)
  6441. ...revalidate ? { "X-Remix-Revalidate": "yes" } : null,
  6442. ...reload ? { "X-Remix-Reload-Document": "yes" } : null,
  6443. ...replace2 ? { "X-Remix-Replace": "yes" } : null
  6444. }
  6445. });
  6446. }
  6447. let routeResult = result.routes[routeId];
  6448. if (routeResult == null) {
  6449. throw new SingleFetchNoResultError(
  6450. `No result found for routeId "${routeId}"`
  6451. );
  6452. } else if ("error" in routeResult) {
  6453. throw routeResult.error;
  6454. } else if ("data" in routeResult) {
  6455. return routeResult.data;
  6456. } else {
  6457. throw new Error(`Invalid response found for routeId "${routeId}"`);
  6458. }
  6459. }
  6460. function createDeferred2() {
  6461. let resolve;
  6462. let reject;
  6463. let promise = new Promise((res, rej) => {
  6464. resolve = async (val) => {
  6465. res(val);
  6466. try {
  6467. await promise;
  6468. } catch (e) {
  6469. }
  6470. };
  6471. reject = async (error) => {
  6472. rej(error);
  6473. try {
  6474. await promise;
  6475. } catch (e) {
  6476. }
  6477. };
  6478. });
  6479. return {
  6480. promise,
  6481. //@ts-ignore
  6482. resolve,
  6483. //@ts-ignore
  6484. reject
  6485. };
  6486. }
  6487. // lib/context.ts
  6488. var DataRouterContext = React2.createContext(null);
  6489. DataRouterContext.displayName = "DataRouter";
  6490. var DataRouterStateContext = React2.createContext(null);
  6491. DataRouterStateContext.displayName = "DataRouterState";
  6492. var RSCRouterContext = React2.createContext(false);
  6493. function useIsRSCRouterContext() {
  6494. return React2.useContext(RSCRouterContext);
  6495. }
  6496. var ViewTransitionContext = React2.createContext({
  6497. isTransitioning: false
  6498. });
  6499. ViewTransitionContext.displayName = "ViewTransition";
  6500. var FetchersContext = React2.createContext(
  6501. /* @__PURE__ */ new Map()
  6502. );
  6503. FetchersContext.displayName = "Fetchers";
  6504. var AwaitContext = React2.createContext(null);
  6505. AwaitContext.displayName = "Await";
  6506. var AwaitContextProvider = (props) => React2.createElement(AwaitContext.Provider, props);
  6507. var NavigationContext = React2.createContext(
  6508. null
  6509. );
  6510. NavigationContext.displayName = "Navigation";
  6511. var LocationContext = React2.createContext(
  6512. null
  6513. );
  6514. LocationContext.displayName = "Location";
  6515. var RouteContext = React2.createContext({
  6516. outlet: null,
  6517. matches: [],
  6518. isDataRoute: false
  6519. });
  6520. RouteContext.displayName = "Route";
  6521. var RouteErrorContext = React2.createContext(null);
  6522. RouteErrorContext.displayName = "RouteError";
  6523. var ENABLE_DEV_WARNINGS = true;
  6524. // lib/hooks.tsx
  6525. function useHref(to, { relative } = {}) {
  6526. invariant(
  6527. useInRouterContext(),
  6528. // TODO: This error is probably because they somehow have 2 versions of the
  6529. // router loaded. We can help them understand how to avoid that.
  6530. `useHref() may be used only in the context of a <Router> component.`
  6531. );
  6532. let { basename, navigator } = React3.useContext(NavigationContext);
  6533. let { hash, pathname, search } = useResolvedPath(to, { relative });
  6534. let joinedPathname = pathname;
  6535. if (basename !== "/") {
  6536. joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
  6537. }
  6538. return navigator.createHref({ pathname: joinedPathname, search, hash });
  6539. }
  6540. function useInRouterContext() {
  6541. return React3.useContext(LocationContext) != null;
  6542. }
  6543. function useLocation() {
  6544. invariant(
  6545. useInRouterContext(),
  6546. // TODO: This error is probably because they somehow have 2 versions of the
  6547. // router loaded. We can help them understand how to avoid that.
  6548. `useLocation() may be used only in the context of a <Router> component.`
  6549. );
  6550. return React3.useContext(LocationContext).location;
  6551. }
  6552. function useNavigationType() {
  6553. return React3.useContext(LocationContext).navigationType;
  6554. }
  6555. function useMatch(pattern) {
  6556. invariant(
  6557. useInRouterContext(),
  6558. // TODO: This error is probably because they somehow have 2 versions of the
  6559. // router loaded. We can help them understand how to avoid that.
  6560. `useMatch() may be used only in the context of a <Router> component.`
  6561. );
  6562. let { pathname } = useLocation();
  6563. return React3.useMemo(
  6564. () => matchPath(pattern, decodePath(pathname)),
  6565. [pathname, pattern]
  6566. );
  6567. }
  6568. var navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when your component is first rendered.`;
  6569. function useIsomorphicLayoutEffect(cb) {
  6570. let isStatic = React3.useContext(NavigationContext).static;
  6571. if (!isStatic) {
  6572. React3.useLayoutEffect(cb);
  6573. }
  6574. }
  6575. function useNavigate() {
  6576. let { isDataRoute } = React3.useContext(RouteContext);
  6577. return isDataRoute ? useNavigateStable() : useNavigateUnstable();
  6578. }
  6579. function useNavigateUnstable() {
  6580. invariant(
  6581. useInRouterContext(),
  6582. // TODO: This error is probably because they somehow have 2 versions of the
  6583. // router loaded. We can help them understand how to avoid that.
  6584. `useNavigate() may be used only in the context of a <Router> component.`
  6585. );
  6586. let dataRouterContext = React3.useContext(DataRouterContext);
  6587. let { basename, navigator } = React3.useContext(NavigationContext);
  6588. let { matches } = React3.useContext(RouteContext);
  6589. let { pathname: locationPathname } = useLocation();
  6590. let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
  6591. let activeRef = React3.useRef(false);
  6592. useIsomorphicLayoutEffect(() => {
  6593. activeRef.current = true;
  6594. });
  6595. let navigate = React3.useCallback(
  6596. (to, options = {}) => {
  6597. warning(activeRef.current, navigateEffectWarning);
  6598. if (!activeRef.current) return;
  6599. if (typeof to === "number") {
  6600. navigator.go(to);
  6601. return;
  6602. }
  6603. let path = resolveTo(
  6604. to,
  6605. JSON.parse(routePathnamesJson),
  6606. locationPathname,
  6607. options.relative === "path"
  6608. );
  6609. if (dataRouterContext == null && basename !== "/") {
  6610. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  6611. }
  6612. (!!options.replace ? navigator.replace : navigator.push)(
  6613. path,
  6614. options.state,
  6615. options
  6616. );
  6617. },
  6618. [
  6619. basename,
  6620. navigator,
  6621. routePathnamesJson,
  6622. locationPathname,
  6623. dataRouterContext
  6624. ]
  6625. );
  6626. return navigate;
  6627. }
  6628. var OutletContext = React3.createContext(null);
  6629. function useOutletContext() {
  6630. return React3.useContext(OutletContext);
  6631. }
  6632. function useOutlet(context) {
  6633. let outlet = React3.useContext(RouteContext).outlet;
  6634. return React3.useMemo(
  6635. () => outlet && /* @__PURE__ */ React3.createElement(OutletContext.Provider, { value: context }, outlet),
  6636. [outlet, context]
  6637. );
  6638. }
  6639. function useParams() {
  6640. let { matches } = React3.useContext(RouteContext);
  6641. let routeMatch = matches[matches.length - 1];
  6642. return routeMatch ? routeMatch.params : {};
  6643. }
  6644. function useResolvedPath(to, { relative } = {}) {
  6645. let { matches } = React3.useContext(RouteContext);
  6646. let { pathname: locationPathname } = useLocation();
  6647. let routePathnamesJson = JSON.stringify(getResolveToMatches(matches));
  6648. return React3.useMemo(
  6649. () => resolveTo(
  6650. to,
  6651. JSON.parse(routePathnamesJson),
  6652. locationPathname,
  6653. relative === "path"
  6654. ),
  6655. [to, routePathnamesJson, locationPathname, relative]
  6656. );
  6657. }
  6658. function useRoutes(routes, locationArg) {
  6659. return useRoutesImpl(routes, locationArg);
  6660. }
  6661. function useRoutesImpl(routes, locationArg, dataRouterState, unstable_onError, future) {
  6662. invariant(
  6663. useInRouterContext(),
  6664. // TODO: This error is probably because they somehow have 2 versions of the
  6665. // router loaded. We can help them understand how to avoid that.
  6666. `useRoutes() may be used only in the context of a <Router> component.`
  6667. );
  6668. let { navigator } = React3.useContext(NavigationContext);
  6669. let { matches: parentMatches } = React3.useContext(RouteContext);
  6670. let routeMatch = parentMatches[parentMatches.length - 1];
  6671. let parentParams = routeMatch ? routeMatch.params : {};
  6672. let parentPathname = routeMatch ? routeMatch.pathname : "/";
  6673. let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  6674. let parentRoute = routeMatch && routeMatch.route;
  6675. if (ENABLE_DEV_WARNINGS) {
  6676. let parentPath = parentRoute && parentRoute.path || "";
  6677. warningOnce(
  6678. parentPathname,
  6679. !parentRoute || parentPath.endsWith("*") || parentPath.endsWith("*?"),
  6680. `You rendered descendant <Routes> (or called \`useRoutes()\`) at "${parentPathname}" (under <Route path="${parentPath}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
  6681. Please change the parent <Route path="${parentPath}"> to <Route path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`
  6682. );
  6683. }
  6684. let locationFromContext = useLocation();
  6685. let location;
  6686. if (locationArg) {
  6687. let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  6688. invariant(
  6689. parentPathnameBase === "/" || _optionalChain([parsedLocationArg, 'access', _77 => _77.pathname, 'optionalAccess', _78 => _78.startsWith, 'call', _79 => _79(parentPathnameBase)]),
  6690. `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${parentPathnameBase}" but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`
  6691. );
  6692. location = parsedLocationArg;
  6693. } else {
  6694. location = locationFromContext;
  6695. }
  6696. let pathname = location.pathname || "/";
  6697. let remainingPathname = pathname;
  6698. if (parentPathnameBase !== "/") {
  6699. let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
  6700. let segments = pathname.replace(/^\//, "").split("/");
  6701. remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
  6702. }
  6703. let matches = matchRoutes(routes, { pathname: remainingPathname });
  6704. if (ENABLE_DEV_WARNINGS) {
  6705. warning(
  6706. parentRoute || matches != null,
  6707. `No routes matched location "${location.pathname}${location.search}${location.hash}" `
  6708. );
  6709. warning(
  6710. matches == null || matches[matches.length - 1].route.element !== void 0 || matches[matches.length - 1].route.Component !== void 0 || matches[matches.length - 1].route.lazy !== void 0,
  6711. `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`
  6712. );
  6713. }
  6714. let renderedMatches = _renderMatches(
  6715. matches && matches.map(
  6716. (match) => Object.assign({}, match, {
  6717. params: Object.assign({}, parentParams, match.params),
  6718. pathname: joinPaths([
  6719. parentPathnameBase,
  6720. // Re-encode pathnames that were decoded inside matchRoutes.
  6721. // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses
  6722. // `new URL()` internally and we need to prevent it from treating
  6723. // them as separators
  6724. navigator.encodeLocation ? navigator.encodeLocation(
  6725. match.pathname.replace(/\?/g, "%3F").replace(/#/g, "%23")
  6726. ).pathname : match.pathname
  6727. ]),
  6728. pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([
  6729. parentPathnameBase,
  6730. // Re-encode pathnames that were decoded inside matchRoutes
  6731. // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses
  6732. // `new URL()` internally and we need to prevent it from treating
  6733. // them as separators
  6734. navigator.encodeLocation ? navigator.encodeLocation(
  6735. match.pathnameBase.replace(/\?/g, "%3F").replace(/#/g, "%23")
  6736. ).pathname : match.pathnameBase
  6737. ])
  6738. })
  6739. ),
  6740. parentMatches,
  6741. dataRouterState,
  6742. unstable_onError,
  6743. future
  6744. );
  6745. if (locationArg && renderedMatches) {
  6746. return /* @__PURE__ */ React3.createElement(
  6747. LocationContext.Provider,
  6748. {
  6749. value: {
  6750. location: {
  6751. pathname: "/",
  6752. search: "",
  6753. hash: "",
  6754. state: null,
  6755. key: "default",
  6756. ...location
  6757. },
  6758. navigationType: "POP" /* Pop */
  6759. }
  6760. },
  6761. renderedMatches
  6762. );
  6763. }
  6764. return renderedMatches;
  6765. }
  6766. function DefaultErrorComponent() {
  6767. let error = useRouteError();
  6768. let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
  6769. let stack = error instanceof Error ? error.stack : null;
  6770. let lightgrey = "rgba(200,200,200, 0.5)";
  6771. let preStyles = { padding: "0.5rem", backgroundColor: lightgrey };
  6772. let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey };
  6773. let devInfo = null;
  6774. if (ENABLE_DEV_WARNINGS) {
  6775. console.error(
  6776. "Error handled by React Router default ErrorBoundary:",
  6777. error
  6778. );
  6779. devInfo = /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("p", null, "\u{1F4BF} Hey developer \u{1F44B}"), /* @__PURE__ */ React3.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */ React3.createElement("code", { style: codeStyles }, "ErrorBoundary"), " or", " ", /* @__PURE__ */ React3.createElement("code", { style: codeStyles }, "errorElement"), " prop on your route."));
  6780. }
  6781. return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ React3.createElement("h3", { style: { fontStyle: "italic" } }, message), stack ? /* @__PURE__ */ React3.createElement("pre", { style: preStyles }, stack) : null, devInfo);
  6782. }
  6783. var defaultErrorElement = /* @__PURE__ */ React3.createElement(DefaultErrorComponent, null);
  6784. var RenderErrorBoundary = class extends React3.Component {
  6785. constructor(props) {
  6786. super(props);
  6787. this.state = {
  6788. location: props.location,
  6789. revalidation: props.revalidation,
  6790. error: props.error
  6791. };
  6792. }
  6793. static getDerivedStateFromError(error) {
  6794. return { error };
  6795. }
  6796. static getDerivedStateFromProps(props, state) {
  6797. if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
  6798. return {
  6799. error: props.error,
  6800. location: props.location,
  6801. revalidation: props.revalidation
  6802. };
  6803. }
  6804. return {
  6805. error: props.error !== void 0 ? props.error : state.error,
  6806. location: state.location,
  6807. revalidation: props.revalidation || state.revalidation
  6808. };
  6809. }
  6810. componentDidCatch(error, errorInfo) {
  6811. if (this.props.onError) {
  6812. this.props.onError(error, errorInfo);
  6813. } else {
  6814. console.error(
  6815. "React Router caught the following error during render",
  6816. error
  6817. );
  6818. }
  6819. }
  6820. render() {
  6821. return this.state.error !== void 0 ? /* @__PURE__ */ React3.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ React3.createElement(
  6822. RouteErrorContext.Provider,
  6823. {
  6824. value: this.state.error,
  6825. children: this.props.component
  6826. }
  6827. )) : this.props.children;
  6828. }
  6829. };
  6830. function RenderedRoute({ routeContext, match, children }) {
  6831. let dataRouterContext = React3.useContext(DataRouterContext);
  6832. if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
  6833. dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
  6834. }
  6835. return /* @__PURE__ */ React3.createElement(RouteContext.Provider, { value: routeContext }, children);
  6836. }
  6837. function _renderMatches(matches, parentMatches = [], dataRouterState = null, unstable_onError = null, future = null) {
  6838. if (matches == null) {
  6839. if (!dataRouterState) {
  6840. return null;
  6841. }
  6842. if (dataRouterState.errors) {
  6843. matches = dataRouterState.matches;
  6844. } else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
  6845. matches = dataRouterState.matches;
  6846. } else {
  6847. return null;
  6848. }
  6849. }
  6850. let renderedMatches = matches;
  6851. let errors = _optionalChain([dataRouterState, 'optionalAccess', _80 => _80.errors]);
  6852. if (errors != null) {
  6853. let errorIndex = renderedMatches.findIndex(
  6854. (m) => m.route.id && _optionalChain([errors, 'optionalAccess', _81 => _81[m.route.id]]) !== void 0
  6855. );
  6856. invariant(
  6857. errorIndex >= 0,
  6858. `Could not find a matching route for errors on route IDs: ${Object.keys(
  6859. errors
  6860. ).join(",")}`
  6861. );
  6862. renderedMatches = renderedMatches.slice(
  6863. 0,
  6864. Math.min(renderedMatches.length, errorIndex + 1)
  6865. );
  6866. }
  6867. let renderFallback = false;
  6868. let fallbackIndex = -1;
  6869. if (dataRouterState) {
  6870. for (let i = 0; i < renderedMatches.length; i++) {
  6871. let match = renderedMatches[i];
  6872. if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
  6873. fallbackIndex = i;
  6874. }
  6875. if (match.route.id) {
  6876. let { loaderData, errors: errors2 } = dataRouterState;
  6877. let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors2 || errors2[match.route.id] === void 0);
  6878. if (match.route.lazy || needsToRunLoader) {
  6879. renderFallback = true;
  6880. if (fallbackIndex >= 0) {
  6881. renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
  6882. } else {
  6883. renderedMatches = [renderedMatches[0]];
  6884. }
  6885. break;
  6886. }
  6887. }
  6888. }
  6889. }
  6890. let onError = dataRouterState && unstable_onError ? (error, errorInfo) => {
  6891. unstable_onError(error, {
  6892. location: dataRouterState.location,
  6893. params: _nullishCoalesce(_optionalChain([dataRouterState, 'access', _82 => _82.matches, 'optionalAccess', _83 => _83[0], 'optionalAccess', _84 => _84.params]), () => ( {})),
  6894. unstable_pattern: getRoutePattern(dataRouterState.matches),
  6895. errorInfo
  6896. });
  6897. } : void 0;
  6898. return renderedMatches.reduceRight(
  6899. (outlet, match, index) => {
  6900. let error;
  6901. let shouldRenderHydrateFallback = false;
  6902. let errorElement = null;
  6903. let hydrateFallbackElement = null;
  6904. if (dataRouterState) {
  6905. error = errors && match.route.id ? errors[match.route.id] : void 0;
  6906. errorElement = match.route.errorElement || defaultErrorElement;
  6907. if (renderFallback) {
  6908. if (fallbackIndex < 0 && index === 0) {
  6909. warningOnce(
  6910. "route-fallback",
  6911. false,
  6912. "No `HydrateFallback` element provided to render during initial hydration"
  6913. );
  6914. shouldRenderHydrateFallback = true;
  6915. hydrateFallbackElement = null;
  6916. } else if (fallbackIndex === index) {
  6917. shouldRenderHydrateFallback = true;
  6918. hydrateFallbackElement = match.route.hydrateFallbackElement || null;
  6919. }
  6920. }
  6921. }
  6922. let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1));
  6923. let getChildren = () => {
  6924. let children;
  6925. if (error) {
  6926. children = errorElement;
  6927. } else if (shouldRenderHydrateFallback) {
  6928. children = hydrateFallbackElement;
  6929. } else if (match.route.Component) {
  6930. children = /* @__PURE__ */ React3.createElement(match.route.Component, null);
  6931. } else if (match.route.element) {
  6932. children = match.route.element;
  6933. } else {
  6934. children = outlet;
  6935. }
  6936. return /* @__PURE__ */ React3.createElement(
  6937. RenderedRoute,
  6938. {
  6939. match,
  6940. routeContext: {
  6941. outlet,
  6942. matches: matches2,
  6943. isDataRoute: dataRouterState != null
  6944. },
  6945. children
  6946. }
  6947. );
  6948. };
  6949. return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ React3.createElement(
  6950. RenderErrorBoundary,
  6951. {
  6952. location: dataRouterState.location,
  6953. revalidation: dataRouterState.revalidation,
  6954. component: errorElement,
  6955. error,
  6956. children: getChildren(),
  6957. routeContext: { outlet: null, matches: matches2, isDataRoute: true },
  6958. onError
  6959. }
  6960. ) : getChildren();
  6961. },
  6962. null
  6963. );
  6964. }
  6965. function getDataRouterConsoleError(hookName) {
  6966. return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`;
  6967. }
  6968. function useDataRouterContext(hookName) {
  6969. let ctx = React3.useContext(DataRouterContext);
  6970. invariant(ctx, getDataRouterConsoleError(hookName));
  6971. return ctx;
  6972. }
  6973. function useDataRouterState(hookName) {
  6974. let state = React3.useContext(DataRouterStateContext);
  6975. invariant(state, getDataRouterConsoleError(hookName));
  6976. return state;
  6977. }
  6978. function useRouteContext(hookName) {
  6979. let route = React3.useContext(RouteContext);
  6980. invariant(route, getDataRouterConsoleError(hookName));
  6981. return route;
  6982. }
  6983. function useCurrentRouteId(hookName) {
  6984. let route = useRouteContext(hookName);
  6985. let thisRoute = route.matches[route.matches.length - 1];
  6986. invariant(
  6987. thisRoute.route.id,
  6988. `${hookName} can only be used on routes that contain a unique "id"`
  6989. );
  6990. return thisRoute.route.id;
  6991. }
  6992. function useRouteId() {
  6993. return useCurrentRouteId("useRouteId" /* UseRouteId */);
  6994. }
  6995. function useNavigation() {
  6996. let state = useDataRouterState("useNavigation" /* UseNavigation */);
  6997. return state.navigation;
  6998. }
  6999. function useRevalidator() {
  7000. let dataRouterContext = useDataRouterContext("useRevalidator" /* UseRevalidator */);
  7001. let state = useDataRouterState("useRevalidator" /* UseRevalidator */);
  7002. let revalidate = React3.useCallback(async () => {
  7003. await dataRouterContext.router.revalidate();
  7004. }, [dataRouterContext.router]);
  7005. return React3.useMemo(
  7006. () => ({ revalidate, state: state.revalidation }),
  7007. [revalidate, state.revalidation]
  7008. );
  7009. }
  7010. function useMatches() {
  7011. let { matches, loaderData } = useDataRouterState(
  7012. "useMatches" /* UseMatches */
  7013. );
  7014. return React3.useMemo(
  7015. () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)),
  7016. [matches, loaderData]
  7017. );
  7018. }
  7019. function useLoaderData() {
  7020. let state = useDataRouterState("useLoaderData" /* UseLoaderData */);
  7021. let routeId = useCurrentRouteId("useLoaderData" /* UseLoaderData */);
  7022. return state.loaderData[routeId];
  7023. }
  7024. function useRouteLoaderData(routeId) {
  7025. let state = useDataRouterState("useRouteLoaderData" /* UseRouteLoaderData */);
  7026. return state.loaderData[routeId];
  7027. }
  7028. function useActionData() {
  7029. let state = useDataRouterState("useActionData" /* UseActionData */);
  7030. let routeId = useCurrentRouteId("useLoaderData" /* UseLoaderData */);
  7031. return state.actionData ? state.actionData[routeId] : void 0;
  7032. }
  7033. function useRouteError() {
  7034. let error = React3.useContext(RouteErrorContext);
  7035. let state = useDataRouterState("useRouteError" /* UseRouteError */);
  7036. let routeId = useCurrentRouteId("useRouteError" /* UseRouteError */);
  7037. if (error !== void 0) {
  7038. return error;
  7039. }
  7040. return _optionalChain([state, 'access', _85 => _85.errors, 'optionalAccess', _86 => _86[routeId]]);
  7041. }
  7042. function useAsyncValue() {
  7043. let value = React3.useContext(AwaitContext);
  7044. return _optionalChain([value, 'optionalAccess', _87 => _87._data]);
  7045. }
  7046. function useAsyncError() {
  7047. let value = React3.useContext(AwaitContext);
  7048. return _optionalChain([value, 'optionalAccess', _88 => _88._error]);
  7049. }
  7050. var blockerId = 0;
  7051. function useBlocker(shouldBlock) {
  7052. let { router, basename } = useDataRouterContext("useBlocker" /* UseBlocker */);
  7053. let state = useDataRouterState("useBlocker" /* UseBlocker */);
  7054. let [blockerKey, setBlockerKey] = React3.useState("");
  7055. let blockerFunction = React3.useCallback(
  7056. (arg) => {
  7057. if (typeof shouldBlock !== "function") {
  7058. return !!shouldBlock;
  7059. }
  7060. if (basename === "/") {
  7061. return shouldBlock(arg);
  7062. }
  7063. let { currentLocation, nextLocation, historyAction } = arg;
  7064. return shouldBlock({
  7065. currentLocation: {
  7066. ...currentLocation,
  7067. pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
  7068. },
  7069. nextLocation: {
  7070. ...nextLocation,
  7071. pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
  7072. },
  7073. historyAction
  7074. });
  7075. },
  7076. [basename, shouldBlock]
  7077. );
  7078. React3.useEffect(() => {
  7079. let key = String(++blockerId);
  7080. setBlockerKey(key);
  7081. return () => router.deleteBlocker(key);
  7082. }, [router]);
  7083. React3.useEffect(() => {
  7084. if (blockerKey !== "") {
  7085. router.getBlocker(blockerKey, blockerFunction);
  7086. }
  7087. }, [router, blockerKey, blockerFunction]);
  7088. return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
  7089. }
  7090. function useNavigateStable() {
  7091. let { router } = useDataRouterContext("useNavigate" /* UseNavigateStable */);
  7092. let id = useCurrentRouteId("useNavigate" /* UseNavigateStable */);
  7093. let activeRef = React3.useRef(false);
  7094. useIsomorphicLayoutEffect(() => {
  7095. activeRef.current = true;
  7096. });
  7097. let navigate = React3.useCallback(
  7098. async (to, options = {}) => {
  7099. warning(activeRef.current, navigateEffectWarning);
  7100. if (!activeRef.current) return;
  7101. if (typeof to === "number") {
  7102. await router.navigate(to);
  7103. } else {
  7104. await router.navigate(to, { fromRouteId: id, ...options });
  7105. }
  7106. },
  7107. [router, id]
  7108. );
  7109. return navigate;
  7110. }
  7111. var alreadyWarned = {};
  7112. function warningOnce(key, cond, message) {
  7113. if (!cond && !alreadyWarned[key]) {
  7114. alreadyWarned[key] = true;
  7115. warning(false, message);
  7116. }
  7117. }
  7118. function useRoute(...args) {
  7119. const currentRouteId = useCurrentRouteId(
  7120. "useRoute" /* UseRoute */
  7121. );
  7122. const id = _nullishCoalesce(args[0], () => ( currentRouteId));
  7123. const state = useDataRouterState("useRoute" /* UseRoute */);
  7124. const route = state.matches.find(({ route: route2 }) => route2.id === id);
  7125. if (route === void 0) return void 0;
  7126. return {
  7127. handle: route.route.handle,
  7128. loaderData: state.loaderData[id],
  7129. actionData: _optionalChain([state, 'access', _89 => _89.actionData, 'optionalAccess', _90 => _90[id]])
  7130. };
  7131. }
  7132. // lib/dom/ssr/errorBoundaries.tsx
  7133. // lib/dom/ssr/components.tsx
  7134. // lib/dom/ssr/routeModules.ts
  7135. async function loadRouteModule(route, routeModulesCache) {
  7136. if (route.id in routeModulesCache) {
  7137. return routeModulesCache[route.id];
  7138. }
  7139. try {
  7140. let routeModule = await Promise.resolve().then(() => _interopRequireWildcard(require(
  7141. /* @vite-ignore */
  7142. /* webpackIgnore: true */
  7143. route.module
  7144. )));
  7145. routeModulesCache[route.id] = routeModule;
  7146. return routeModule;
  7147. } catch (error) {
  7148. console.error(
  7149. `Error loading route module \`${route.module}\`, reloading page...`
  7150. );
  7151. console.error(error);
  7152. if (window.__reactRouterContext && window.__reactRouterContext.isSpaMode && // @ts-expect-error
  7153. void 0) {
  7154. throw error;
  7155. }
  7156. window.location.reload();
  7157. return new Promise(() => {
  7158. });
  7159. }
  7160. }
  7161. // lib/dom/ssr/links.ts
  7162. function getKeyedLinksForMatches(matches, routeModules, manifest) {
  7163. let descriptors = matches.map((match) => {
  7164. let module = routeModules[match.route.id];
  7165. let route = manifest.routes[match.route.id];
  7166. return [
  7167. route && route.css ? route.css.map((href) => ({ rel: "stylesheet", href })) : [],
  7168. _optionalChain([module, 'optionalAccess', _91 => _91.links, 'optionalCall', _92 => _92()]) || []
  7169. ];
  7170. }).flat(2);
  7171. let preloads = getModuleLinkHrefs(matches, manifest);
  7172. return dedupeLinkDescriptors(descriptors, preloads);
  7173. }
  7174. function getRouteCssDescriptors(route) {
  7175. if (!route.css) return [];
  7176. return route.css.map((href) => ({ rel: "stylesheet", href }));
  7177. }
  7178. async function prefetchRouteCss(route) {
  7179. if (!route.css) return;
  7180. let descriptors = getRouteCssDescriptors(route);
  7181. await Promise.all(descriptors.map(prefetchStyleLink));
  7182. }
  7183. async function prefetchStyleLinks(route, routeModule) {
  7184. if (!route.css && !routeModule.links || !isPreloadSupported()) return;
  7185. let descriptors = [];
  7186. if (route.css) {
  7187. descriptors.push(...getRouteCssDescriptors(route));
  7188. }
  7189. if (routeModule.links) {
  7190. descriptors.push(...routeModule.links());
  7191. }
  7192. if (descriptors.length === 0) return;
  7193. let styleLinks = [];
  7194. for (let descriptor of descriptors) {
  7195. if (!isPageLinkDescriptor(descriptor) && descriptor.rel === "stylesheet") {
  7196. styleLinks.push({
  7197. ...descriptor,
  7198. rel: "preload",
  7199. as: "style"
  7200. });
  7201. }
  7202. }
  7203. await Promise.all(styleLinks.map(prefetchStyleLink));
  7204. }
  7205. async function prefetchStyleLink(descriptor) {
  7206. return new Promise((resolve) => {
  7207. if (descriptor.media && !window.matchMedia(descriptor.media).matches || document.querySelector(
  7208. `link[rel="stylesheet"][href="${descriptor.href}"]`
  7209. )) {
  7210. return resolve();
  7211. }
  7212. let link = document.createElement("link");
  7213. Object.assign(link, descriptor);
  7214. function removeLink() {
  7215. if (document.head.contains(link)) {
  7216. document.head.removeChild(link);
  7217. }
  7218. }
  7219. link.onload = () => {
  7220. removeLink();
  7221. resolve();
  7222. };
  7223. link.onerror = () => {
  7224. removeLink();
  7225. resolve();
  7226. };
  7227. document.head.appendChild(link);
  7228. });
  7229. }
  7230. function isPageLinkDescriptor(object) {
  7231. return object != null && typeof object.page === "string";
  7232. }
  7233. function isHtmlLinkDescriptor(object) {
  7234. if (object == null) {
  7235. return false;
  7236. }
  7237. if (object.href == null) {
  7238. return object.rel === "preload" && typeof object.imageSrcSet === "string" && typeof object.imageSizes === "string";
  7239. }
  7240. return typeof object.rel === "string" && typeof object.href === "string";
  7241. }
  7242. async function getKeyedPrefetchLinks(matches, manifest, routeModules) {
  7243. let links = await Promise.all(
  7244. matches.map(async (match) => {
  7245. let route = manifest.routes[match.route.id];
  7246. if (route) {
  7247. let mod = await loadRouteModule(route, routeModules);
  7248. return mod.links ? mod.links() : [];
  7249. }
  7250. return [];
  7251. })
  7252. );
  7253. return dedupeLinkDescriptors(
  7254. links.flat(1).filter(isHtmlLinkDescriptor).filter((link) => link.rel === "stylesheet" || link.rel === "preload").map(
  7255. (link) => link.rel === "stylesheet" ? { ...link, rel: "prefetch", as: "style" } : { ...link, rel: "prefetch" }
  7256. )
  7257. );
  7258. }
  7259. function getNewMatchesForLinks(page, nextMatches, currentMatches, manifest, location, mode) {
  7260. let isNew = (match, index) => {
  7261. if (!currentMatches[index]) return true;
  7262. return match.route.id !== currentMatches[index].route.id;
  7263. };
  7264. let matchPathChanged = (match, index) => {
  7265. return (
  7266. // param change, /users/123 -> /users/456
  7267. currentMatches[index].pathname !== match.pathname || // splat param changed, which is not present in match.path
  7268. // e.g. /files/images/avatar.jpg -> files/finances.xls
  7269. _optionalChain([currentMatches, 'access', _93 => _93[index], 'access', _94 => _94.route, 'access', _95 => _95.path, 'optionalAccess', _96 => _96.endsWith, 'call', _97 => _97("*")]) && currentMatches[index].params["*"] !== match.params["*"]
  7270. );
  7271. };
  7272. if (mode === "assets") {
  7273. return nextMatches.filter(
  7274. (match, index) => isNew(match, index) || matchPathChanged(match, index)
  7275. );
  7276. }
  7277. if (mode === "data") {
  7278. return nextMatches.filter((match, index) => {
  7279. let manifestRoute = manifest.routes[match.route.id];
  7280. if (!manifestRoute || !manifestRoute.hasLoader) {
  7281. return false;
  7282. }
  7283. if (isNew(match, index) || matchPathChanged(match, index)) {
  7284. return true;
  7285. }
  7286. if (match.route.shouldRevalidate) {
  7287. let routeChoice = match.route.shouldRevalidate({
  7288. currentUrl: new URL(
  7289. location.pathname + location.search + location.hash,
  7290. window.origin
  7291. ),
  7292. currentParams: _optionalChain([currentMatches, 'access', _98 => _98[0], 'optionalAccess', _99 => _99.params]) || {},
  7293. nextUrl: new URL(page, window.origin),
  7294. nextParams: match.params,
  7295. defaultShouldRevalidate: true
  7296. });
  7297. if (typeof routeChoice === "boolean") {
  7298. return routeChoice;
  7299. }
  7300. }
  7301. return true;
  7302. });
  7303. }
  7304. return [];
  7305. }
  7306. function getModuleLinkHrefs(matches, manifest, { includeHydrateFallback } = {}) {
  7307. return dedupeHrefs(
  7308. matches.map((match) => {
  7309. let route = manifest.routes[match.route.id];
  7310. if (!route) return [];
  7311. let hrefs = [route.module];
  7312. if (route.clientActionModule) {
  7313. hrefs = hrefs.concat(route.clientActionModule);
  7314. }
  7315. if (route.clientLoaderModule) {
  7316. hrefs = hrefs.concat(route.clientLoaderModule);
  7317. }
  7318. if (includeHydrateFallback && route.hydrateFallbackModule) {
  7319. hrefs = hrefs.concat(route.hydrateFallbackModule);
  7320. }
  7321. if (route.imports) {
  7322. hrefs = hrefs.concat(route.imports);
  7323. }
  7324. return hrefs;
  7325. }).flat(1)
  7326. );
  7327. }
  7328. function dedupeHrefs(hrefs) {
  7329. return [...new Set(hrefs)];
  7330. }
  7331. function sortKeys(obj) {
  7332. let sorted = {};
  7333. let keys = Object.keys(obj).sort();
  7334. for (let key of keys) {
  7335. sorted[key] = obj[key];
  7336. }
  7337. return sorted;
  7338. }
  7339. function dedupeLinkDescriptors(descriptors, preloads) {
  7340. let set = /* @__PURE__ */ new Set();
  7341. let preloadsSet = new Set(preloads);
  7342. return descriptors.reduce((deduped, descriptor) => {
  7343. let alreadyModulePreload = preloads && !isPageLinkDescriptor(descriptor) && descriptor.as === "script" && descriptor.href && preloadsSet.has(descriptor.href);
  7344. if (alreadyModulePreload) {
  7345. return deduped;
  7346. }
  7347. let key = JSON.stringify(sortKeys(descriptor));
  7348. if (!set.has(key)) {
  7349. set.add(key);
  7350. deduped.push({ key, link: descriptor });
  7351. }
  7352. return deduped;
  7353. }, []);
  7354. }
  7355. var _isPreloadSupported;
  7356. function isPreloadSupported() {
  7357. if (_isPreloadSupported !== void 0) {
  7358. return _isPreloadSupported;
  7359. }
  7360. let el = document.createElement("link");
  7361. _isPreloadSupported = el.relList.supports("preload");
  7362. el = null;
  7363. return _isPreloadSupported;
  7364. }
  7365. // lib/server-runtime/warnings.ts
  7366. var alreadyWarned2 = {};
  7367. function warnOnce(condition, message) {
  7368. if (!condition && !alreadyWarned2[message]) {
  7369. alreadyWarned2[message] = true;
  7370. console.warn(message);
  7371. }
  7372. }
  7373. // lib/dom/ssr/fog-of-war.ts
  7374. // lib/dom/ssr/routes.tsx
  7375. // lib/dom/ssr/fallback.tsx
  7376. function RemixRootDefaultHydrateFallback() {
  7377. return /* @__PURE__ */ React4.createElement(BoundaryShell, { title: "Loading...", renderScripts: true }, ENABLE_DEV_WARNINGS ? /* @__PURE__ */ React4.createElement(
  7378. "script",
  7379. {
  7380. dangerouslySetInnerHTML: {
  7381. __html: `
  7382. console.log(
  7383. "\u{1F4BF} Hey developer \u{1F44B}. You can provide a way better UX than this " +
  7384. "when your app is loading JS modules and/or running \`clientLoader\` " +
  7385. "functions. Check out https://reactrouter.com/start/framework/route-module#hydratefallback " +
  7386. "for more information."
  7387. );
  7388. `
  7389. }
  7390. }
  7391. ) : null);
  7392. }
  7393. // lib/dom/ssr/routes.tsx
  7394. function groupRoutesByParentId(manifest) {
  7395. let routes = {};
  7396. Object.values(manifest).forEach((route) => {
  7397. if (route) {
  7398. let parentId = route.parentId || "";
  7399. if (!routes[parentId]) {
  7400. routes[parentId] = [];
  7401. }
  7402. routes[parentId].push(route);
  7403. }
  7404. });
  7405. return routes;
  7406. }
  7407. function getRouteComponents(route, routeModule, isSpaMode) {
  7408. let Component4 = getRouteModuleComponent(routeModule);
  7409. let HydrateFallback = routeModule.HydrateFallback && (!isSpaMode || route.id === "root") ? routeModule.HydrateFallback : route.id === "root" ? RemixRootDefaultHydrateFallback : void 0;
  7410. let ErrorBoundary = routeModule.ErrorBoundary ? routeModule.ErrorBoundary : route.id === "root" ? () => /* @__PURE__ */ React5.createElement(RemixRootDefaultErrorBoundary, { error: useRouteError() }) : void 0;
  7411. if (route.id === "root" && routeModule.Layout) {
  7412. return {
  7413. ...Component4 ? {
  7414. element: /* @__PURE__ */ React5.createElement(routeModule.Layout, null, /* @__PURE__ */ React5.createElement(Component4, null))
  7415. } : { Component: Component4 },
  7416. ...ErrorBoundary ? {
  7417. errorElement: /* @__PURE__ */ React5.createElement(routeModule.Layout, null, /* @__PURE__ */ React5.createElement(ErrorBoundary, null))
  7418. } : { ErrorBoundary },
  7419. ...HydrateFallback ? {
  7420. hydrateFallbackElement: /* @__PURE__ */ React5.createElement(routeModule.Layout, null, /* @__PURE__ */ React5.createElement(HydrateFallback, null))
  7421. } : { HydrateFallback }
  7422. };
  7423. }
  7424. return { Component: Component4, ErrorBoundary, HydrateFallback };
  7425. }
  7426. function createServerRoutes(manifest, routeModules, future, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), spaModeLazyPromise = Promise.resolve({ Component: () => null })) {
  7427. return (routesByParentId[parentId] || []).map((route) => {
  7428. let routeModule = routeModules[route.id];
  7429. invariant2(
  7430. routeModule,
  7431. "No `routeModule` available to create server routes"
  7432. );
  7433. let dataRoute = {
  7434. ...getRouteComponents(route, routeModule, isSpaMode),
  7435. caseSensitive: route.caseSensitive,
  7436. id: route.id,
  7437. index: route.index,
  7438. path: route.path,
  7439. handle: routeModule.handle,
  7440. // For SPA Mode, all routes are lazy except root. However we tell the
  7441. // router root is also lazy here too since we don't need a full
  7442. // implementation - we just need a `lazy` prop to tell the RR rendering
  7443. // where to stop which is always at the root route in SPA mode
  7444. lazy: isSpaMode ? () => spaModeLazyPromise : void 0,
  7445. // For partial hydration rendering, we need to indicate when the route
  7446. // has a loader/clientLoader, but it won't ever be called during the static
  7447. // render, so just give it a no-op function so we can render down to the
  7448. // proper fallback
  7449. loader: route.hasLoader || route.hasClientLoader ? () => null : void 0
  7450. // We don't need middleware/action/shouldRevalidate on these routes since
  7451. // they're for a static render
  7452. };
  7453. let children = createServerRoutes(
  7454. manifest,
  7455. routeModules,
  7456. future,
  7457. isSpaMode,
  7458. route.id,
  7459. routesByParentId,
  7460. spaModeLazyPromise
  7461. );
  7462. if (children.length > 0) dataRoute.children = children;
  7463. return dataRoute;
  7464. });
  7465. }
  7466. function createClientRoutesWithHMRRevalidationOptOut(needsRevalidation, manifest, routeModulesCache, initialState, ssr, isSpaMode) {
  7467. return createClientRoutes(
  7468. manifest,
  7469. routeModulesCache,
  7470. initialState,
  7471. ssr,
  7472. isSpaMode,
  7473. "",
  7474. groupRoutesByParentId(manifest),
  7475. needsRevalidation
  7476. );
  7477. }
  7478. function preventInvalidServerHandlerCall(type, route) {
  7479. if (type === "loader" && !route.hasLoader || type === "action" && !route.hasAction) {
  7480. let fn = type === "action" ? "serverAction()" : "serverLoader()";
  7481. let msg = `You are trying to call ${fn} on a route that does not have a server ${type} (routeId: "${route.id}")`;
  7482. console.error(msg);
  7483. throw new ErrorResponseImpl(400, "Bad Request", new Error(msg), true);
  7484. }
  7485. }
  7486. function noActionDefinedError(type, routeId) {
  7487. let article = type === "clientAction" ? "a" : "an";
  7488. let msg = `Route "${routeId}" does not have ${article} ${type}, but you are trying to submit to it. To fix this, please add ${article} \`${type}\` function to the route`;
  7489. console.error(msg);
  7490. throw new ErrorResponseImpl(405, "Method Not Allowed", new Error(msg), true);
  7491. }
  7492. function createClientRoutes(manifest, routeModulesCache, initialState, ssr, isSpaMode, parentId = "", routesByParentId = groupRoutesByParentId(manifest), needsRevalidation) {
  7493. return (routesByParentId[parentId] || []).map((route) => {
  7494. let routeModule = routeModulesCache[route.id];
  7495. function fetchServerHandler(singleFetch) {
  7496. invariant2(
  7497. typeof singleFetch === "function",
  7498. "No single fetch function available for route handler"
  7499. );
  7500. return singleFetch();
  7501. }
  7502. function fetchServerLoader(singleFetch) {
  7503. if (!route.hasLoader) return Promise.resolve(null);
  7504. return fetchServerHandler(singleFetch);
  7505. }
  7506. function fetchServerAction(singleFetch) {
  7507. if (!route.hasAction) {
  7508. throw noActionDefinedError("action", route.id);
  7509. }
  7510. return fetchServerHandler(singleFetch);
  7511. }
  7512. function prefetchModule(modulePath) {
  7513. Promise.resolve().then(() => _interopRequireWildcard(require(
  7514. /* @vite-ignore */
  7515. /* webpackIgnore: true */
  7516. modulePath
  7517. )));
  7518. }
  7519. function prefetchRouteModuleChunks(route2) {
  7520. if (route2.clientActionModule) {
  7521. prefetchModule(route2.clientActionModule);
  7522. }
  7523. if (route2.clientLoaderModule) {
  7524. prefetchModule(route2.clientLoaderModule);
  7525. }
  7526. }
  7527. async function prefetchStylesAndCallHandler(handler) {
  7528. let cachedModule = routeModulesCache[route.id];
  7529. let linkPrefetchPromise = cachedModule ? prefetchStyleLinks(route, cachedModule) : Promise.resolve();
  7530. try {
  7531. return handler();
  7532. } finally {
  7533. await linkPrefetchPromise;
  7534. }
  7535. }
  7536. let dataRoute = {
  7537. id: route.id,
  7538. index: route.index,
  7539. path: route.path
  7540. };
  7541. if (routeModule) {
  7542. Object.assign(dataRoute, {
  7543. ...dataRoute,
  7544. ...getRouteComponents(route, routeModule, isSpaMode),
  7545. middleware: routeModule.clientMiddleware,
  7546. handle: routeModule.handle,
  7547. shouldRevalidate: getShouldRevalidateFunction(
  7548. dataRoute.path,
  7549. routeModule,
  7550. route,
  7551. ssr,
  7552. needsRevalidation
  7553. )
  7554. });
  7555. let hasInitialData = initialState && initialState.loaderData && route.id in initialState.loaderData;
  7556. let initialData = hasInitialData ? _optionalChain([initialState, 'optionalAccess', _100 => _100.loaderData, 'optionalAccess', _101 => _101[route.id]]) : void 0;
  7557. let hasInitialError = initialState && initialState.errors && route.id in initialState.errors;
  7558. let initialError = hasInitialError ? _optionalChain([initialState, 'optionalAccess', _102 => _102.errors, 'optionalAccess', _103 => _103[route.id]]) : void 0;
  7559. let isHydrationRequest = needsRevalidation == null && (_optionalChain([routeModule, 'access', _104 => _104.clientLoader, 'optionalAccess', _105 => _105.hydrate]) === true || !route.hasLoader);
  7560. dataRoute.loader = async ({ request, params, context, unstable_pattern }, singleFetch) => {
  7561. try {
  7562. let result = await prefetchStylesAndCallHandler(async () => {
  7563. invariant2(
  7564. routeModule,
  7565. "No `routeModule` available for critical-route loader"
  7566. );
  7567. if (!routeModule.clientLoader) {
  7568. return fetchServerLoader(singleFetch);
  7569. }
  7570. return routeModule.clientLoader({
  7571. request,
  7572. params,
  7573. context,
  7574. unstable_pattern,
  7575. async serverLoader() {
  7576. preventInvalidServerHandlerCall("loader", route);
  7577. if (isHydrationRequest) {
  7578. if (hasInitialData) {
  7579. return initialData;
  7580. }
  7581. if (hasInitialError) {
  7582. throw initialError;
  7583. }
  7584. }
  7585. return fetchServerLoader(singleFetch);
  7586. }
  7587. });
  7588. });
  7589. return result;
  7590. } finally {
  7591. isHydrationRequest = false;
  7592. }
  7593. };
  7594. dataRoute.loader.hydrate = shouldHydrateRouteLoader(
  7595. route.id,
  7596. routeModule.clientLoader,
  7597. route.hasLoader,
  7598. isSpaMode
  7599. );
  7600. dataRoute.action = ({ request, params, context, unstable_pattern }, singleFetch) => {
  7601. return prefetchStylesAndCallHandler(async () => {
  7602. invariant2(
  7603. routeModule,
  7604. "No `routeModule` available for critical-route action"
  7605. );
  7606. if (!routeModule.clientAction) {
  7607. if (isSpaMode) {
  7608. throw noActionDefinedError("clientAction", route.id);
  7609. }
  7610. return fetchServerAction(singleFetch);
  7611. }
  7612. return routeModule.clientAction({
  7613. request,
  7614. params,
  7615. context,
  7616. unstable_pattern,
  7617. async serverAction() {
  7618. preventInvalidServerHandlerCall("action", route);
  7619. return fetchServerAction(singleFetch);
  7620. }
  7621. });
  7622. });
  7623. };
  7624. } else {
  7625. if (!route.hasClientLoader) {
  7626. dataRoute.loader = (_, singleFetch) => prefetchStylesAndCallHandler(() => {
  7627. return fetchServerLoader(singleFetch);
  7628. });
  7629. }
  7630. if (!route.hasClientAction) {
  7631. dataRoute.action = (_, singleFetch) => prefetchStylesAndCallHandler(() => {
  7632. if (isSpaMode) {
  7633. throw noActionDefinedError("clientAction", route.id);
  7634. }
  7635. return fetchServerAction(singleFetch);
  7636. });
  7637. }
  7638. let lazyRoutePromise;
  7639. async function getLazyRoute() {
  7640. if (lazyRoutePromise) {
  7641. return await lazyRoutePromise;
  7642. }
  7643. lazyRoutePromise = (async () => {
  7644. if (route.clientLoaderModule || route.clientActionModule) {
  7645. await new Promise((resolve) => setTimeout(resolve, 0));
  7646. }
  7647. let routeModulePromise = loadRouteModuleWithBlockingLinks(
  7648. route,
  7649. routeModulesCache
  7650. );
  7651. prefetchRouteModuleChunks(route);
  7652. return await routeModulePromise;
  7653. })();
  7654. return await lazyRoutePromise;
  7655. }
  7656. dataRoute.lazy = {
  7657. loader: route.hasClientLoader ? async () => {
  7658. let { clientLoader } = route.clientLoaderModule ? await Promise.resolve().then(() => _interopRequireWildcard(require(
  7659. /* @vite-ignore */
  7660. /* webpackIgnore: true */
  7661. route.clientLoaderModule
  7662. ))) : await getLazyRoute();
  7663. invariant2(clientLoader, "No `clientLoader` export found");
  7664. return (args, singleFetch) => clientLoader({
  7665. ...args,
  7666. async serverLoader() {
  7667. preventInvalidServerHandlerCall("loader", route);
  7668. return fetchServerLoader(singleFetch);
  7669. }
  7670. });
  7671. } : void 0,
  7672. action: route.hasClientAction ? async () => {
  7673. let clientActionPromise = route.clientActionModule ? Promise.resolve().then(() => _interopRequireWildcard(require(
  7674. /* @vite-ignore */
  7675. /* webpackIgnore: true */
  7676. route.clientActionModule
  7677. ))) : getLazyRoute();
  7678. prefetchRouteModuleChunks(route);
  7679. let { clientAction } = await clientActionPromise;
  7680. invariant2(clientAction, "No `clientAction` export found");
  7681. return (args, singleFetch) => clientAction({
  7682. ...args,
  7683. async serverAction() {
  7684. preventInvalidServerHandlerCall("action", route);
  7685. return fetchServerAction(singleFetch);
  7686. }
  7687. });
  7688. } : void 0,
  7689. middleware: route.hasClientMiddleware ? async () => {
  7690. let { clientMiddleware } = route.clientMiddlewareModule ? await Promise.resolve().then(() => _interopRequireWildcard(require(
  7691. /* @vite-ignore */
  7692. /* webpackIgnore: true */
  7693. route.clientMiddlewareModule
  7694. ))) : await getLazyRoute();
  7695. invariant2(clientMiddleware, "No `clientMiddleware` export found");
  7696. return clientMiddleware;
  7697. } : void 0,
  7698. shouldRevalidate: async () => {
  7699. let lazyRoute = await getLazyRoute();
  7700. return getShouldRevalidateFunction(
  7701. dataRoute.path,
  7702. lazyRoute,
  7703. route,
  7704. ssr,
  7705. needsRevalidation
  7706. );
  7707. },
  7708. handle: async () => (await getLazyRoute()).handle,
  7709. // No need to wrap these in layout since the root route is never
  7710. // loaded via route.lazy()
  7711. Component: async () => (await getLazyRoute()).Component,
  7712. ErrorBoundary: route.hasErrorBoundary ? async () => (await getLazyRoute()).ErrorBoundary : void 0
  7713. };
  7714. }
  7715. let children = createClientRoutes(
  7716. manifest,
  7717. routeModulesCache,
  7718. initialState,
  7719. ssr,
  7720. isSpaMode,
  7721. route.id,
  7722. routesByParentId,
  7723. needsRevalidation
  7724. );
  7725. if (children.length > 0) dataRoute.children = children;
  7726. return dataRoute;
  7727. });
  7728. }
  7729. function getShouldRevalidateFunction(path, route, manifestRoute, ssr, needsRevalidation) {
  7730. if (needsRevalidation) {
  7731. return wrapShouldRevalidateForHdr(
  7732. manifestRoute.id,
  7733. route.shouldRevalidate,
  7734. needsRevalidation
  7735. );
  7736. }
  7737. if (!ssr && manifestRoute.hasLoader && !manifestRoute.hasClientLoader) {
  7738. let myParams = path ? compilePath(path)[1].map((p) => p.paramName) : [];
  7739. const didParamsChange = (opts) => myParams.some((p) => opts.currentParams[p] !== opts.nextParams[p]);
  7740. if (route.shouldRevalidate) {
  7741. let fn = route.shouldRevalidate;
  7742. return (opts) => fn({
  7743. ...opts,
  7744. defaultShouldRevalidate: didParamsChange(opts)
  7745. });
  7746. } else {
  7747. return (opts) => didParamsChange(opts);
  7748. }
  7749. }
  7750. return route.shouldRevalidate;
  7751. }
  7752. function wrapShouldRevalidateForHdr(routeId, routeShouldRevalidate, needsRevalidation) {
  7753. let handledRevalidation = false;
  7754. return (arg) => {
  7755. if (!handledRevalidation) {
  7756. handledRevalidation = true;
  7757. return needsRevalidation.has(routeId);
  7758. }
  7759. return routeShouldRevalidate ? routeShouldRevalidate(arg) : arg.defaultShouldRevalidate;
  7760. };
  7761. }
  7762. async function loadRouteModuleWithBlockingLinks(route, routeModules) {
  7763. let routeModulePromise = loadRouteModule(route, routeModules);
  7764. let prefetchRouteCssPromise = prefetchRouteCss(route);
  7765. let routeModule = await routeModulePromise;
  7766. await Promise.all([
  7767. prefetchRouteCssPromise,
  7768. prefetchStyleLinks(route, routeModule)
  7769. ]);
  7770. return {
  7771. Component: getRouteModuleComponent(routeModule),
  7772. ErrorBoundary: routeModule.ErrorBoundary,
  7773. clientMiddleware: routeModule.clientMiddleware,
  7774. clientAction: routeModule.clientAction,
  7775. clientLoader: routeModule.clientLoader,
  7776. handle: routeModule.handle,
  7777. links: routeModule.links,
  7778. meta: routeModule.meta,
  7779. shouldRevalidate: routeModule.shouldRevalidate
  7780. };
  7781. }
  7782. function getRouteModuleComponent(routeModule) {
  7783. if (routeModule.default == null) return void 0;
  7784. let isEmptyObject = typeof routeModule.default === "object" && Object.keys(routeModule.default).length === 0;
  7785. if (!isEmptyObject) {
  7786. return routeModule.default;
  7787. }
  7788. }
  7789. function shouldHydrateRouteLoader(routeId, clientLoader, hasLoader, isSpaMode) {
  7790. return isSpaMode && routeId !== "root" || clientLoader != null && (clientLoader.hydrate === true || hasLoader !== true);
  7791. }
  7792. // lib/dom/ssr/fog-of-war.ts
  7793. var nextPaths = /* @__PURE__ */ new Set();
  7794. var discoveredPathsMaxSize = 1e3;
  7795. var discoveredPaths = /* @__PURE__ */ new Set();
  7796. var URL_LIMIT = 7680;
  7797. function isFogOfWarEnabled(routeDiscovery, ssr) {
  7798. return routeDiscovery.mode === "lazy" && ssr === true;
  7799. }
  7800. function getPartialManifest({ sri, ...manifest }, router) {
  7801. let routeIds = new Set(router.state.matches.map((m) => m.route.id));
  7802. let segments = router.state.location.pathname.split("/").filter(Boolean);
  7803. let paths = ["/"];
  7804. segments.pop();
  7805. while (segments.length > 0) {
  7806. paths.push(`/${segments.join("/")}`);
  7807. segments.pop();
  7808. }
  7809. paths.forEach((path) => {
  7810. let matches = matchRoutes(router.routes, path, router.basename);
  7811. if (matches) {
  7812. matches.forEach((m) => routeIds.add(m.route.id));
  7813. }
  7814. });
  7815. let initialRoutes = [...routeIds].reduce(
  7816. (acc, id) => Object.assign(acc, { [id]: manifest.routes[id] }),
  7817. {}
  7818. );
  7819. return {
  7820. ...manifest,
  7821. routes: initialRoutes,
  7822. sri: sri ? true : void 0
  7823. };
  7824. }
  7825. function getPatchRoutesOnNavigationFunction(manifest, routeModules, ssr, routeDiscovery, isSpaMode, basename) {
  7826. if (!isFogOfWarEnabled(routeDiscovery, ssr)) {
  7827. return void 0;
  7828. }
  7829. return async ({ path, patch, signal, fetcherKey }) => {
  7830. if (discoveredPaths.has(path)) {
  7831. return;
  7832. }
  7833. await fetchAndApplyManifestPatches(
  7834. [path],
  7835. fetcherKey ? window.location.href : path,
  7836. manifest,
  7837. routeModules,
  7838. ssr,
  7839. isSpaMode,
  7840. basename,
  7841. routeDiscovery.manifestPath,
  7842. patch,
  7843. signal
  7844. );
  7845. };
  7846. }
  7847. function useFogOFWarDiscovery(router, manifest, routeModules, ssr, routeDiscovery, isSpaMode) {
  7848. React6.useEffect(() => {
  7849. if (!isFogOfWarEnabled(routeDiscovery, ssr) || // @ts-expect-error - TS doesn't know about this yet
  7850. _optionalChain([window, 'access', _106 => _106.navigator, 'optionalAccess', _107 => _107.connection, 'optionalAccess', _108 => _108.saveData]) === true) {
  7851. return;
  7852. }
  7853. function registerElement(el) {
  7854. let path = el.tagName === "FORM" ? el.getAttribute("action") : el.getAttribute("href");
  7855. if (!path) {
  7856. return;
  7857. }
  7858. let pathname = el.tagName === "A" ? el.pathname : new URL(path, window.location.origin).pathname;
  7859. if (!discoveredPaths.has(pathname)) {
  7860. nextPaths.add(pathname);
  7861. }
  7862. }
  7863. async function fetchPatches() {
  7864. document.querySelectorAll("a[data-discover], form[data-discover]").forEach(registerElement);
  7865. let lazyPaths = Array.from(nextPaths.keys()).filter((path) => {
  7866. if (discoveredPaths.has(path)) {
  7867. nextPaths.delete(path);
  7868. return false;
  7869. }
  7870. return true;
  7871. });
  7872. if (lazyPaths.length === 0) {
  7873. return;
  7874. }
  7875. try {
  7876. await fetchAndApplyManifestPatches(
  7877. lazyPaths,
  7878. null,
  7879. manifest,
  7880. routeModules,
  7881. ssr,
  7882. isSpaMode,
  7883. router.basename,
  7884. routeDiscovery.manifestPath,
  7885. router.patchRoutes
  7886. );
  7887. } catch (e) {
  7888. console.error("Failed to fetch manifest patches", e);
  7889. }
  7890. }
  7891. let debouncedFetchPatches = debounce(fetchPatches, 100);
  7892. fetchPatches();
  7893. let observer = new MutationObserver(() => debouncedFetchPatches());
  7894. observer.observe(document.documentElement, {
  7895. subtree: true,
  7896. childList: true,
  7897. attributes: true,
  7898. attributeFilter: ["data-discover", "href", "action"]
  7899. });
  7900. return () => observer.disconnect();
  7901. }, [ssr, isSpaMode, manifest, routeModules, router, routeDiscovery]);
  7902. }
  7903. function getManifestPath(_manifestPath, basename) {
  7904. let manifestPath = _manifestPath || "/__manifest";
  7905. if (basename == null) {
  7906. return manifestPath;
  7907. }
  7908. return `${basename}${manifestPath}`.replace(/\/+/g, "/");
  7909. }
  7910. var MANIFEST_VERSION_STORAGE_KEY = "react-router-manifest-version";
  7911. async function fetchAndApplyManifestPatches(paths, errorReloadPath, manifest, routeModules, ssr, isSpaMode, basename, manifestPath, patchRoutes, signal) {
  7912. const searchParams = new URLSearchParams();
  7913. searchParams.set("paths", paths.sort().join(","));
  7914. searchParams.set("version", manifest.version);
  7915. let url = new URL(
  7916. getManifestPath(manifestPath, basename),
  7917. window.location.origin
  7918. );
  7919. url.search = searchParams.toString();
  7920. if (url.toString().length > URL_LIMIT) {
  7921. nextPaths.clear();
  7922. return;
  7923. }
  7924. let serverPatches;
  7925. try {
  7926. let res = await fetch(url, { signal });
  7927. if (!res.ok) {
  7928. throw new Error(`${res.status} ${res.statusText}`);
  7929. } else if (res.status === 204 && res.headers.has("X-Remix-Reload-Document")) {
  7930. if (!errorReloadPath) {
  7931. console.warn(
  7932. "Detected a manifest version mismatch during eager route discovery. The next navigation/fetch to an undiscovered route will result in a new document navigation to sync up with the latest manifest."
  7933. );
  7934. return;
  7935. }
  7936. try {
  7937. if (sessionStorage.getItem(MANIFEST_VERSION_STORAGE_KEY) === manifest.version) {
  7938. console.error(
  7939. "Unable to discover routes due to manifest version mismatch."
  7940. );
  7941. return;
  7942. }
  7943. sessionStorage.setItem(MANIFEST_VERSION_STORAGE_KEY, manifest.version);
  7944. } catch (e2) {
  7945. }
  7946. window.location.href = errorReloadPath;
  7947. console.warn("Detected manifest version mismatch, reloading...");
  7948. await new Promise(() => {
  7949. });
  7950. } else if (res.status >= 400) {
  7951. throw new Error(await res.text());
  7952. }
  7953. try {
  7954. sessionStorage.removeItem(MANIFEST_VERSION_STORAGE_KEY);
  7955. } catch (e3) {
  7956. }
  7957. serverPatches = await res.json();
  7958. } catch (e) {
  7959. if (_optionalChain([signal, 'optionalAccess', _109 => _109.aborted])) return;
  7960. throw e;
  7961. }
  7962. let knownRoutes = new Set(Object.keys(manifest.routes));
  7963. let patches = Object.values(serverPatches).reduce((acc, route) => {
  7964. if (route && !knownRoutes.has(route.id)) {
  7965. acc[route.id] = route;
  7966. }
  7967. return acc;
  7968. }, {});
  7969. Object.assign(manifest.routes, patches);
  7970. paths.forEach((p) => addToFifoQueue(p, discoveredPaths));
  7971. let parentIds = /* @__PURE__ */ new Set();
  7972. Object.values(patches).forEach((patch) => {
  7973. if (patch && (!patch.parentId || !patches[patch.parentId])) {
  7974. parentIds.add(patch.parentId);
  7975. }
  7976. });
  7977. parentIds.forEach(
  7978. (parentId) => patchRoutes(
  7979. parentId || null,
  7980. createClientRoutes(patches, routeModules, null, ssr, isSpaMode, parentId)
  7981. )
  7982. );
  7983. }
  7984. function addToFifoQueue(path, queue) {
  7985. if (queue.size >= discoveredPathsMaxSize) {
  7986. let first = queue.values().next().value;
  7987. queue.delete(first);
  7988. }
  7989. queue.add(path);
  7990. }
  7991. function debounce(callback, wait) {
  7992. let timeoutId;
  7993. return (...args) => {
  7994. window.clearTimeout(timeoutId);
  7995. timeoutId = window.setTimeout(() => callback(...args), wait);
  7996. };
  7997. }
  7998. // lib/dom/ssr/components.tsx
  7999. function useDataRouterContext2() {
  8000. let context = React7.useContext(DataRouterContext);
  8001. invariant2(
  8002. context,
  8003. "You must render this element inside a <DataRouterContext.Provider> element"
  8004. );
  8005. return context;
  8006. }
  8007. function useDataRouterStateContext() {
  8008. let context = React7.useContext(DataRouterStateContext);
  8009. invariant2(
  8010. context,
  8011. "You must render this element inside a <DataRouterStateContext.Provider> element"
  8012. );
  8013. return context;
  8014. }
  8015. var FrameworkContext = React7.createContext(void 0);
  8016. FrameworkContext.displayName = "FrameworkContext";
  8017. function useFrameworkContext() {
  8018. let context = React7.useContext(FrameworkContext);
  8019. invariant2(
  8020. context,
  8021. "You must render this element inside a <HydratedRouter> element"
  8022. );
  8023. return context;
  8024. }
  8025. function usePrefetchBehavior(prefetch, theirElementProps) {
  8026. let frameworkContext = React7.useContext(FrameworkContext);
  8027. let [maybePrefetch, setMaybePrefetch] = React7.useState(false);
  8028. let [shouldPrefetch, setShouldPrefetch] = React7.useState(false);
  8029. let { onFocus, onBlur, onMouseEnter, onMouseLeave, onTouchStart } = theirElementProps;
  8030. let ref = React7.useRef(null);
  8031. React7.useEffect(() => {
  8032. if (prefetch === "render") {
  8033. setShouldPrefetch(true);
  8034. }
  8035. if (prefetch === "viewport") {
  8036. let callback = (entries) => {
  8037. entries.forEach((entry) => {
  8038. setShouldPrefetch(entry.isIntersecting);
  8039. });
  8040. };
  8041. let observer = new IntersectionObserver(callback, { threshold: 0.5 });
  8042. if (ref.current) observer.observe(ref.current);
  8043. return () => {
  8044. observer.disconnect();
  8045. };
  8046. }
  8047. }, [prefetch]);
  8048. React7.useEffect(() => {
  8049. if (maybePrefetch) {
  8050. let id = setTimeout(() => {
  8051. setShouldPrefetch(true);
  8052. }, 100);
  8053. return () => {
  8054. clearTimeout(id);
  8055. };
  8056. }
  8057. }, [maybePrefetch]);
  8058. let setIntent = () => {
  8059. setMaybePrefetch(true);
  8060. };
  8061. let cancelIntent = () => {
  8062. setMaybePrefetch(false);
  8063. setShouldPrefetch(false);
  8064. };
  8065. if (!frameworkContext) {
  8066. return [false, ref, {}];
  8067. }
  8068. if (prefetch !== "intent") {
  8069. return [shouldPrefetch, ref, {}];
  8070. }
  8071. return [
  8072. shouldPrefetch,
  8073. ref,
  8074. {
  8075. onFocus: composeEventHandlers(onFocus, setIntent),
  8076. onBlur: composeEventHandlers(onBlur, cancelIntent),
  8077. onMouseEnter: composeEventHandlers(onMouseEnter, setIntent),
  8078. onMouseLeave: composeEventHandlers(onMouseLeave, cancelIntent),
  8079. onTouchStart: composeEventHandlers(onTouchStart, setIntent)
  8080. }
  8081. ];
  8082. }
  8083. function composeEventHandlers(theirHandler, ourHandler) {
  8084. return (event) => {
  8085. theirHandler && theirHandler(event);
  8086. if (!event.defaultPrevented) {
  8087. ourHandler(event);
  8088. }
  8089. };
  8090. }
  8091. function getActiveMatches(matches, errors, isSpaMode) {
  8092. if (isSpaMode && !isHydrated) {
  8093. return [matches[0]];
  8094. }
  8095. if (errors) {
  8096. let errorIdx = matches.findIndex((m) => errors[m.route.id] !== void 0);
  8097. return matches.slice(0, errorIdx + 1);
  8098. }
  8099. return matches;
  8100. }
  8101. var CRITICAL_CSS_DATA_ATTRIBUTE = "data-react-router-critical-css";
  8102. function Links({ nonce }) {
  8103. let { isSpaMode, manifest, routeModules, criticalCss } = useFrameworkContext();
  8104. let { errors, matches: routerMatches } = useDataRouterStateContext();
  8105. let matches = getActiveMatches(routerMatches, errors, isSpaMode);
  8106. let keyedLinks = React7.useMemo(
  8107. () => getKeyedLinksForMatches(matches, routeModules, manifest),
  8108. [matches, routeModules, manifest]
  8109. );
  8110. return /* @__PURE__ */ React7.createElement(React7.Fragment, null, typeof criticalCss === "string" ? /* @__PURE__ */ React7.createElement(
  8111. "style",
  8112. {
  8113. ...{ [CRITICAL_CSS_DATA_ATTRIBUTE]: "" },
  8114. dangerouslySetInnerHTML: { __html: criticalCss }
  8115. }
  8116. ) : null, typeof criticalCss === "object" ? /* @__PURE__ */ React7.createElement(
  8117. "link",
  8118. {
  8119. ...{ [CRITICAL_CSS_DATA_ATTRIBUTE]: "" },
  8120. rel: "stylesheet",
  8121. href: criticalCss.href,
  8122. nonce
  8123. }
  8124. ) : null, keyedLinks.map(
  8125. ({ key, link }) => isPageLinkDescriptor(link) ? /* @__PURE__ */ React7.createElement(PrefetchPageLinks, { key, nonce, ...link }) : /* @__PURE__ */ React7.createElement("link", { key, nonce, ...link })
  8126. ));
  8127. }
  8128. function PrefetchPageLinks({ page, ...linkProps }) {
  8129. let { router } = useDataRouterContext2();
  8130. let matches = React7.useMemo(
  8131. () => matchRoutes(router.routes, page, router.basename),
  8132. [router.routes, page, router.basename]
  8133. );
  8134. if (!matches) {
  8135. return null;
  8136. }
  8137. return /* @__PURE__ */ React7.createElement(PrefetchPageLinksImpl, { page, matches, ...linkProps });
  8138. }
  8139. function useKeyedPrefetchLinks(matches) {
  8140. let { manifest, routeModules } = useFrameworkContext();
  8141. let [keyedPrefetchLinks, setKeyedPrefetchLinks] = React7.useState([]);
  8142. React7.useEffect(() => {
  8143. let interrupted = false;
  8144. void getKeyedPrefetchLinks(matches, manifest, routeModules).then(
  8145. (links) => {
  8146. if (!interrupted) {
  8147. setKeyedPrefetchLinks(links);
  8148. }
  8149. }
  8150. );
  8151. return () => {
  8152. interrupted = true;
  8153. };
  8154. }, [matches, manifest, routeModules]);
  8155. return keyedPrefetchLinks;
  8156. }
  8157. function PrefetchPageLinksImpl({
  8158. page,
  8159. matches: nextMatches,
  8160. ...linkProps
  8161. }) {
  8162. let location = useLocation();
  8163. let { manifest, routeModules } = useFrameworkContext();
  8164. let { basename } = useDataRouterContext2();
  8165. let { loaderData, matches } = useDataRouterStateContext();
  8166. let newMatchesForData = React7.useMemo(
  8167. () => getNewMatchesForLinks(
  8168. page,
  8169. nextMatches,
  8170. matches,
  8171. manifest,
  8172. location,
  8173. "data"
  8174. ),
  8175. [page, nextMatches, matches, manifest, location]
  8176. );
  8177. let newMatchesForAssets = React7.useMemo(
  8178. () => getNewMatchesForLinks(
  8179. page,
  8180. nextMatches,
  8181. matches,
  8182. manifest,
  8183. location,
  8184. "assets"
  8185. ),
  8186. [page, nextMatches, matches, manifest, location]
  8187. );
  8188. let dataHrefs = React7.useMemo(() => {
  8189. if (page === location.pathname + location.search + location.hash) {
  8190. return [];
  8191. }
  8192. let routesParams = /* @__PURE__ */ new Set();
  8193. let foundOptOutRoute = false;
  8194. nextMatches.forEach((m) => {
  8195. let manifestRoute = manifest.routes[m.route.id];
  8196. if (!manifestRoute || !manifestRoute.hasLoader) {
  8197. return;
  8198. }
  8199. if (!newMatchesForData.some((m2) => m2.route.id === m.route.id) && m.route.id in loaderData && _optionalChain([routeModules, 'access', _110 => _110[m.route.id], 'optionalAccess', _111 => _111.shouldRevalidate])) {
  8200. foundOptOutRoute = true;
  8201. } else if (manifestRoute.hasClientLoader) {
  8202. foundOptOutRoute = true;
  8203. } else {
  8204. routesParams.add(m.route.id);
  8205. }
  8206. });
  8207. if (routesParams.size === 0) {
  8208. return [];
  8209. }
  8210. let url = singleFetchUrl(page, basename, "data");
  8211. if (foundOptOutRoute && routesParams.size > 0) {
  8212. url.searchParams.set(
  8213. "_routes",
  8214. nextMatches.filter((m) => routesParams.has(m.route.id)).map((m) => m.route.id).join(",")
  8215. );
  8216. }
  8217. return [url.pathname + url.search];
  8218. }, [
  8219. basename,
  8220. loaderData,
  8221. location,
  8222. manifest,
  8223. newMatchesForData,
  8224. nextMatches,
  8225. page,
  8226. routeModules
  8227. ]);
  8228. let moduleHrefs = React7.useMemo(
  8229. () => getModuleLinkHrefs(newMatchesForAssets, manifest),
  8230. [newMatchesForAssets, manifest]
  8231. );
  8232. let keyedPrefetchLinks = useKeyedPrefetchLinks(newMatchesForAssets);
  8233. return /* @__PURE__ */ React7.createElement(React7.Fragment, null, dataHrefs.map((href) => /* @__PURE__ */ React7.createElement("link", { key: href, rel: "prefetch", as: "fetch", href, ...linkProps })), moduleHrefs.map((href) => /* @__PURE__ */ React7.createElement("link", { key: href, rel: "modulepreload", href, ...linkProps })), keyedPrefetchLinks.map(({ key, link }) => (
  8234. // these don't spread `linkProps` because they are full link descriptors
  8235. // already with their own props
  8236. /* @__PURE__ */ React7.createElement("link", { key, nonce: linkProps.nonce, ...link })
  8237. )));
  8238. }
  8239. function Meta() {
  8240. let { isSpaMode, routeModules } = useFrameworkContext();
  8241. let {
  8242. errors,
  8243. matches: routerMatches,
  8244. loaderData
  8245. } = useDataRouterStateContext();
  8246. let location = useLocation();
  8247. let _matches = getActiveMatches(routerMatches, errors, isSpaMode);
  8248. let error = null;
  8249. if (errors) {
  8250. error = errors[_matches[_matches.length - 1].route.id];
  8251. }
  8252. let meta = [];
  8253. let leafMeta = null;
  8254. let matches = [];
  8255. for (let i = 0; i < _matches.length; i++) {
  8256. let _match = _matches[i];
  8257. let routeId = _match.route.id;
  8258. let data2 = loaderData[routeId];
  8259. let params = _match.params;
  8260. let routeModule = routeModules[routeId];
  8261. let routeMeta = [];
  8262. let match = {
  8263. id: routeId,
  8264. data: data2,
  8265. loaderData: data2,
  8266. meta: [],
  8267. params: _match.params,
  8268. pathname: _match.pathname,
  8269. handle: _match.route.handle,
  8270. error
  8271. };
  8272. matches[i] = match;
  8273. if (_optionalChain([routeModule, 'optionalAccess', _112 => _112.meta])) {
  8274. routeMeta = typeof routeModule.meta === "function" ? routeModule.meta({
  8275. data: data2,
  8276. loaderData: data2,
  8277. params,
  8278. location,
  8279. matches,
  8280. error
  8281. }) : Array.isArray(routeModule.meta) ? [...routeModule.meta] : routeModule.meta;
  8282. } else if (leafMeta) {
  8283. routeMeta = [...leafMeta];
  8284. }
  8285. routeMeta = routeMeta || [];
  8286. if (!Array.isArray(routeMeta)) {
  8287. throw new Error(
  8288. "The route at " + _match.route.path + " returns an invalid value. All route meta functions must return an array of meta objects.\n\nTo reference the meta function API, see https://remix.run/route/meta"
  8289. );
  8290. }
  8291. match.meta = routeMeta;
  8292. matches[i] = match;
  8293. meta = [...routeMeta];
  8294. leafMeta = meta;
  8295. }
  8296. return /* @__PURE__ */ React7.createElement(React7.Fragment, null, meta.flat().map((metaProps) => {
  8297. if (!metaProps) {
  8298. return null;
  8299. }
  8300. if ("tagName" in metaProps) {
  8301. let { tagName, ...rest } = metaProps;
  8302. if (!isValidMetaTag(tagName)) {
  8303. console.warn(
  8304. `A meta object uses an invalid tagName: ${tagName}. Expected either 'link' or 'meta'`
  8305. );
  8306. return null;
  8307. }
  8308. let Comp = tagName;
  8309. return /* @__PURE__ */ React7.createElement(Comp, { key: JSON.stringify(rest), ...rest });
  8310. }
  8311. if ("title" in metaProps) {
  8312. return /* @__PURE__ */ React7.createElement("title", { key: "title" }, String(metaProps.title));
  8313. }
  8314. if ("charset" in metaProps) {
  8315. _nullishCoalesce(metaProps.charSet, () => ( (metaProps.charSet = metaProps.charset)));
  8316. delete metaProps.charset;
  8317. }
  8318. if ("charSet" in metaProps && metaProps.charSet != null) {
  8319. return typeof metaProps.charSet === "string" ? /* @__PURE__ */ React7.createElement("meta", { key: "charSet", charSet: metaProps.charSet }) : null;
  8320. }
  8321. if ("script:ld+json" in metaProps) {
  8322. try {
  8323. let json = JSON.stringify(metaProps["script:ld+json"]);
  8324. return /* @__PURE__ */ React7.createElement(
  8325. "script",
  8326. {
  8327. key: `script:ld+json:${json}`,
  8328. type: "application/ld+json",
  8329. dangerouslySetInnerHTML: { __html: escapeHtml(json) }
  8330. }
  8331. );
  8332. } catch (err) {
  8333. return null;
  8334. }
  8335. }
  8336. return /* @__PURE__ */ React7.createElement("meta", { key: JSON.stringify(metaProps), ...metaProps });
  8337. }));
  8338. }
  8339. function isValidMetaTag(tagName) {
  8340. return typeof tagName === "string" && /^(meta|link)$/.test(tagName);
  8341. }
  8342. var isHydrated = false;
  8343. function setIsHydrated() {
  8344. isHydrated = true;
  8345. }
  8346. function Scripts(scriptProps) {
  8347. let {
  8348. manifest,
  8349. serverHandoffString,
  8350. isSpaMode,
  8351. renderMeta,
  8352. routeDiscovery,
  8353. ssr
  8354. } = useFrameworkContext();
  8355. let { router, static: isStatic, staticContext } = useDataRouterContext2();
  8356. let { matches: routerMatches } = useDataRouterStateContext();
  8357. let isRSCRouterContext = useIsRSCRouterContext();
  8358. let enableFogOfWar = isFogOfWarEnabled(routeDiscovery, ssr);
  8359. if (renderMeta) {
  8360. renderMeta.didRenderScripts = true;
  8361. }
  8362. let matches = getActiveMatches(routerMatches, null, isSpaMode);
  8363. React7.useEffect(() => {
  8364. setIsHydrated();
  8365. }, []);
  8366. let initialScripts = React7.useMemo(() => {
  8367. if (isRSCRouterContext) {
  8368. return null;
  8369. }
  8370. let streamScript = "window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream());";
  8371. let contextScript = staticContext ? `window.__reactRouterContext = ${serverHandoffString};${streamScript}` : " ";
  8372. let routeModulesScript = !isStatic ? " " : `${_optionalChain([manifest, 'access', _113 => _113.hmr, 'optionalAccess', _114 => _114.runtime]) ? `import ${JSON.stringify(manifest.hmr.runtime)};` : ""}${!enableFogOfWar ? `import ${JSON.stringify(manifest.url)}` : ""};
  8373. ${matches.map((match, routeIndex) => {
  8374. let routeVarName = `route${routeIndex}`;
  8375. let manifestEntry = manifest.routes[match.route.id];
  8376. invariant2(manifestEntry, `Route ${match.route.id} not found in manifest`);
  8377. let {
  8378. clientActionModule,
  8379. clientLoaderModule,
  8380. clientMiddlewareModule,
  8381. hydrateFallbackModule,
  8382. module
  8383. } = manifestEntry;
  8384. let chunks = [
  8385. ...clientActionModule ? [
  8386. {
  8387. module: clientActionModule,
  8388. varName: `${routeVarName}_clientAction`
  8389. }
  8390. ] : [],
  8391. ...clientLoaderModule ? [
  8392. {
  8393. module: clientLoaderModule,
  8394. varName: `${routeVarName}_clientLoader`
  8395. }
  8396. ] : [],
  8397. ...clientMiddlewareModule ? [
  8398. {
  8399. module: clientMiddlewareModule,
  8400. varName: `${routeVarName}_clientMiddleware`
  8401. }
  8402. ] : [],
  8403. ...hydrateFallbackModule ? [
  8404. {
  8405. module: hydrateFallbackModule,
  8406. varName: `${routeVarName}_HydrateFallback`
  8407. }
  8408. ] : [],
  8409. { module, varName: `${routeVarName}_main` }
  8410. ];
  8411. if (chunks.length === 1) {
  8412. return `import * as ${routeVarName} from ${JSON.stringify(module)};`;
  8413. }
  8414. let chunkImportsSnippet = chunks.map((chunk) => `import * as ${chunk.varName} from "${chunk.module}";`).join("\n");
  8415. let mergedChunksSnippet = `const ${routeVarName} = {${chunks.map((chunk) => `...${chunk.varName}`).join(",")}};`;
  8416. return [chunkImportsSnippet, mergedChunksSnippet].join("\n");
  8417. }).join("\n")}
  8418. ${enableFogOfWar ? (
  8419. // Inline a minimal manifest with the SSR matches
  8420. `window.__reactRouterManifest = ${JSON.stringify(
  8421. getPartialManifest(manifest, router),
  8422. null,
  8423. 2
  8424. )};`
  8425. ) : ""}
  8426. window.__reactRouterRouteModules = {${matches.map((match, index) => `${JSON.stringify(match.route.id)}:route${index}`).join(",")}};
  8427. import(${JSON.stringify(manifest.entry.module)});`;
  8428. return /* @__PURE__ */ React7.createElement(React7.Fragment, null, /* @__PURE__ */ React7.createElement(
  8429. "script",
  8430. {
  8431. ...scriptProps,
  8432. suppressHydrationWarning: true,
  8433. dangerouslySetInnerHTML: { __html: contextScript },
  8434. type: void 0
  8435. }
  8436. ), /* @__PURE__ */ React7.createElement(
  8437. "script",
  8438. {
  8439. ...scriptProps,
  8440. suppressHydrationWarning: true,
  8441. dangerouslySetInnerHTML: { __html: routeModulesScript },
  8442. type: "module",
  8443. async: true
  8444. }
  8445. ));
  8446. }, []);
  8447. let preloads = isHydrated || isRSCRouterContext ? [] : dedupe(
  8448. manifest.entry.imports.concat(
  8449. getModuleLinkHrefs(matches, manifest, {
  8450. includeHydrateFallback: true
  8451. })
  8452. )
  8453. );
  8454. let sri = typeof manifest.sri === "object" ? manifest.sri : {};
  8455. warnOnce(
  8456. !isRSCRouterContext,
  8457. "The <Scripts /> element is a no-op when using RSC and can be safely removed."
  8458. );
  8459. return isHydrated || isRSCRouterContext ? null : /* @__PURE__ */ React7.createElement(React7.Fragment, null, typeof manifest.sri === "object" ? /* @__PURE__ */ React7.createElement(
  8460. "script",
  8461. {
  8462. "rr-importmap": "",
  8463. type: "importmap",
  8464. suppressHydrationWarning: true,
  8465. dangerouslySetInnerHTML: {
  8466. __html: JSON.stringify({
  8467. integrity: sri
  8468. })
  8469. }
  8470. }
  8471. ) : null, !enableFogOfWar ? /* @__PURE__ */ React7.createElement(
  8472. "link",
  8473. {
  8474. rel: "modulepreload",
  8475. href: manifest.url,
  8476. crossOrigin: scriptProps.crossOrigin,
  8477. integrity: sri[manifest.url],
  8478. suppressHydrationWarning: true
  8479. }
  8480. ) : null, /* @__PURE__ */ React7.createElement(
  8481. "link",
  8482. {
  8483. rel: "modulepreload",
  8484. href: manifest.entry.module,
  8485. crossOrigin: scriptProps.crossOrigin,
  8486. integrity: sri[manifest.entry.module],
  8487. suppressHydrationWarning: true
  8488. }
  8489. ), preloads.map((path) => /* @__PURE__ */ React7.createElement(
  8490. "link",
  8491. {
  8492. key: path,
  8493. rel: "modulepreload",
  8494. href: path,
  8495. crossOrigin: scriptProps.crossOrigin,
  8496. integrity: sri[path],
  8497. suppressHydrationWarning: true
  8498. }
  8499. )), initialScripts);
  8500. }
  8501. function dedupe(array) {
  8502. return [...new Set(array)];
  8503. }
  8504. function mergeRefs(...refs) {
  8505. return (value) => {
  8506. refs.forEach((ref) => {
  8507. if (typeof ref === "function") {
  8508. ref(value);
  8509. } else if (ref != null) {
  8510. ref.current = value;
  8511. }
  8512. });
  8513. };
  8514. }
  8515. // lib/dom/ssr/errorBoundaries.tsx
  8516. var RemixErrorBoundary = class extends React8.Component {
  8517. constructor(props) {
  8518. super(props);
  8519. this.state = { error: props.error || null, location: props.location };
  8520. }
  8521. static getDerivedStateFromError(error) {
  8522. return { error };
  8523. }
  8524. static getDerivedStateFromProps(props, state) {
  8525. if (state.location !== props.location) {
  8526. return { error: props.error || null, location: props.location };
  8527. }
  8528. return { error: props.error || state.error, location: state.location };
  8529. }
  8530. render() {
  8531. if (this.state.error) {
  8532. return /* @__PURE__ */ React8.createElement(
  8533. RemixRootDefaultErrorBoundary,
  8534. {
  8535. error: this.state.error,
  8536. isOutsideRemixApp: true
  8537. }
  8538. );
  8539. } else {
  8540. return this.props.children;
  8541. }
  8542. }
  8543. };
  8544. function RemixRootDefaultErrorBoundary({
  8545. error,
  8546. isOutsideRemixApp
  8547. }) {
  8548. console.error(error);
  8549. let heyDeveloper = /* @__PURE__ */ React8.createElement(
  8550. "script",
  8551. {
  8552. dangerouslySetInnerHTML: {
  8553. __html: `
  8554. console.log(
  8555. "\u{1F4BF} Hey developer \u{1F44B}. You can provide a way better UX than this when your app throws errors. Check out https://reactrouter.com/how-to/error-boundary for more information."
  8556. );
  8557. `
  8558. }
  8559. }
  8560. );
  8561. if (isRouteErrorResponse(error)) {
  8562. return /* @__PURE__ */ React8.createElement(BoundaryShell, { title: "Unhandled Thrown Response!" }, /* @__PURE__ */ React8.createElement("h1", { style: { fontSize: "24px" } }, error.status, " ", error.statusText), ENABLE_DEV_WARNINGS ? heyDeveloper : null);
  8563. }
  8564. let errorInstance;
  8565. if (error instanceof Error) {
  8566. errorInstance = error;
  8567. } else {
  8568. let errorString = error == null ? "Unknown Error" : typeof error === "object" && "toString" in error ? error.toString() : JSON.stringify(error);
  8569. errorInstance = new Error(errorString);
  8570. }
  8571. return /* @__PURE__ */ React8.createElement(
  8572. BoundaryShell,
  8573. {
  8574. title: "Application Error!",
  8575. isOutsideRemixApp
  8576. },
  8577. /* @__PURE__ */ React8.createElement("h1", { style: { fontSize: "24px" } }, "Application Error"),
  8578. /* @__PURE__ */ React8.createElement(
  8579. "pre",
  8580. {
  8581. style: {
  8582. padding: "2rem",
  8583. background: "hsla(10, 50%, 50%, 0.1)",
  8584. color: "red",
  8585. overflow: "auto"
  8586. }
  8587. },
  8588. errorInstance.stack
  8589. ),
  8590. heyDeveloper
  8591. );
  8592. }
  8593. function BoundaryShell({
  8594. title,
  8595. renderScripts,
  8596. isOutsideRemixApp,
  8597. children
  8598. }) {
  8599. let { routeModules } = useFrameworkContext();
  8600. if (_optionalChain([routeModules, 'access', _115 => _115.root, 'optionalAccess', _116 => _116.Layout]) && !isOutsideRemixApp) {
  8601. return children;
  8602. }
  8603. return /* @__PURE__ */ React8.createElement("html", { lang: "en" }, /* @__PURE__ */ React8.createElement("head", null, /* @__PURE__ */ React8.createElement("meta", { charSet: "utf-8" }), /* @__PURE__ */ React8.createElement(
  8604. "meta",
  8605. {
  8606. name: "viewport",
  8607. content: "width=device-width,initial-scale=1,viewport-fit=cover"
  8608. }
  8609. ), /* @__PURE__ */ React8.createElement("title", null, title)), /* @__PURE__ */ React8.createElement("body", null, /* @__PURE__ */ React8.createElement("main", { style: { fontFamily: "system-ui, sans-serif", padding: "2rem" } }, children, renderScripts ? /* @__PURE__ */ React8.createElement(Scripts, null) : null)));
  8610. }
  8611. // lib/components.tsx
  8612. var USE_OPTIMISTIC = "useOptimistic";
  8613. var useOptimisticImpl = React9[USE_OPTIMISTIC];
  8614. var stableUseOptimisticSetter = () => void 0;
  8615. function useOptimisticSafe(val) {
  8616. if (useOptimisticImpl) {
  8617. return useOptimisticImpl(val);
  8618. } else {
  8619. return [val, stableUseOptimisticSetter];
  8620. }
  8621. }
  8622. function mapRouteProperties(route) {
  8623. let updates = {
  8624. // Note: this check also occurs in createRoutesFromChildren so update
  8625. // there if you change this -- please and thank you!
  8626. hasErrorBoundary: route.hasErrorBoundary || route.ErrorBoundary != null || route.errorElement != null
  8627. };
  8628. if (route.Component) {
  8629. if (ENABLE_DEV_WARNINGS) {
  8630. if (route.element) {
  8631. warning(
  8632. false,
  8633. "You should not include both `Component` and `element` on your route - `Component` will be used."
  8634. );
  8635. }
  8636. }
  8637. Object.assign(updates, {
  8638. element: React9.createElement(route.Component),
  8639. Component: void 0
  8640. });
  8641. }
  8642. if (route.HydrateFallback) {
  8643. if (ENABLE_DEV_WARNINGS) {
  8644. if (route.hydrateFallbackElement) {
  8645. warning(
  8646. false,
  8647. "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used."
  8648. );
  8649. }
  8650. }
  8651. Object.assign(updates, {
  8652. hydrateFallbackElement: React9.createElement(route.HydrateFallback),
  8653. HydrateFallback: void 0
  8654. });
  8655. }
  8656. if (route.ErrorBoundary) {
  8657. if (ENABLE_DEV_WARNINGS) {
  8658. if (route.errorElement) {
  8659. warning(
  8660. false,
  8661. "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used."
  8662. );
  8663. }
  8664. }
  8665. Object.assign(updates, {
  8666. errorElement: React9.createElement(route.ErrorBoundary),
  8667. ErrorBoundary: void 0
  8668. });
  8669. }
  8670. return updates;
  8671. }
  8672. var hydrationRouteProperties = [
  8673. "HydrateFallback",
  8674. "hydrateFallbackElement"
  8675. ];
  8676. function createMemoryRouter(routes, opts) {
  8677. return createRouter({
  8678. basename: _optionalChain([opts, 'optionalAccess', _117 => _117.basename]),
  8679. getContext: _optionalChain([opts, 'optionalAccess', _118 => _118.getContext]),
  8680. future: _optionalChain([opts, 'optionalAccess', _119 => _119.future]),
  8681. history: createMemoryHistory({
  8682. initialEntries: _optionalChain([opts, 'optionalAccess', _120 => _120.initialEntries]),
  8683. initialIndex: _optionalChain([opts, 'optionalAccess', _121 => _121.initialIndex])
  8684. }),
  8685. hydrationData: _optionalChain([opts, 'optionalAccess', _122 => _122.hydrationData]),
  8686. routes,
  8687. hydrationRouteProperties,
  8688. mapRouteProperties,
  8689. dataStrategy: _optionalChain([opts, 'optionalAccess', _123 => _123.dataStrategy]),
  8690. patchRoutesOnNavigation: _optionalChain([opts, 'optionalAccess', _124 => _124.patchRoutesOnNavigation]),
  8691. unstable_instrumentations: _optionalChain([opts, 'optionalAccess', _125 => _125.unstable_instrumentations])
  8692. }).initialize();
  8693. }
  8694. var Deferred2 = class {
  8695. constructor() {
  8696. this.status = "pending";
  8697. this.promise = new Promise((resolve, reject) => {
  8698. this.resolve = (value) => {
  8699. if (this.status === "pending") {
  8700. this.status = "resolved";
  8701. resolve(value);
  8702. }
  8703. };
  8704. this.reject = (reason) => {
  8705. if (this.status === "pending") {
  8706. this.status = "rejected";
  8707. reject(reason);
  8708. }
  8709. };
  8710. });
  8711. }
  8712. };
  8713. function RouterProvider({
  8714. router,
  8715. flushSync: reactDomFlushSyncImpl,
  8716. unstable_onError,
  8717. unstable_useTransitions
  8718. }) {
  8719. let [_state, setStateImpl] = React9.useState(router.state);
  8720. let [state, setOptimisticState] = useOptimisticSafe(_state);
  8721. let [pendingState, setPendingState] = React9.useState();
  8722. let [vtContext, setVtContext] = React9.useState({
  8723. isTransitioning: false
  8724. });
  8725. let [renderDfd, setRenderDfd] = React9.useState();
  8726. let [transition, setTransition] = React9.useState();
  8727. let [interruption, setInterruption] = React9.useState();
  8728. let fetcherData = React9.useRef(/* @__PURE__ */ new Map());
  8729. let setState = React9.useCallback(
  8730. (newState, { deletedFetchers, newErrors, flushSync, viewTransitionOpts }) => {
  8731. if (newErrors && unstable_onError) {
  8732. Object.values(newErrors).forEach(
  8733. (error) => unstable_onError(error, {
  8734. location: newState.location,
  8735. params: _nullishCoalesce(_optionalChain([newState, 'access', _126 => _126.matches, 'access', _127 => _127[0], 'optionalAccess', _128 => _128.params]), () => ( {})),
  8736. unstable_pattern: getRoutePattern(newState.matches)
  8737. })
  8738. );
  8739. }
  8740. newState.fetchers.forEach((fetcher, key) => {
  8741. if (fetcher.data !== void 0) {
  8742. fetcherData.current.set(key, fetcher.data);
  8743. }
  8744. });
  8745. deletedFetchers.forEach((key) => fetcherData.current.delete(key));
  8746. warnOnce(
  8747. flushSync === false || reactDomFlushSyncImpl != null,
  8748. 'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.'
  8749. );
  8750. let isViewTransitionAvailable = router.window != null && router.window.document != null && typeof router.window.document.startViewTransition === "function";
  8751. warnOnce(
  8752. viewTransitionOpts == null || isViewTransitionAvailable,
  8753. "You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."
  8754. );
  8755. if (!viewTransitionOpts || !isViewTransitionAvailable) {
  8756. if (reactDomFlushSyncImpl && flushSync) {
  8757. reactDomFlushSyncImpl(() => setStateImpl(newState));
  8758. } else if (unstable_useTransitions === false) {
  8759. setStateImpl(newState);
  8760. } else {
  8761. React9.startTransition(() => {
  8762. if (unstable_useTransitions === true) {
  8763. setOptimisticState((s) => getOptimisticRouterState(s, newState));
  8764. }
  8765. setStateImpl(newState);
  8766. });
  8767. }
  8768. return;
  8769. }
  8770. if (reactDomFlushSyncImpl && flushSync) {
  8771. reactDomFlushSyncImpl(() => {
  8772. if (transition) {
  8773. _optionalChain([renderDfd, 'optionalAccess', _129 => _129.resolve, 'call', _130 => _130()]);
  8774. transition.skipTransition();
  8775. }
  8776. setVtContext({
  8777. isTransitioning: true,
  8778. flushSync: true,
  8779. currentLocation: viewTransitionOpts.currentLocation,
  8780. nextLocation: viewTransitionOpts.nextLocation
  8781. });
  8782. });
  8783. let t = router.window.document.startViewTransition(() => {
  8784. reactDomFlushSyncImpl(() => setStateImpl(newState));
  8785. });
  8786. t.finished.finally(() => {
  8787. reactDomFlushSyncImpl(() => {
  8788. setRenderDfd(void 0);
  8789. setTransition(void 0);
  8790. setPendingState(void 0);
  8791. setVtContext({ isTransitioning: false });
  8792. });
  8793. });
  8794. reactDomFlushSyncImpl(() => setTransition(t));
  8795. return;
  8796. }
  8797. if (transition) {
  8798. _optionalChain([renderDfd, 'optionalAccess', _131 => _131.resolve, 'call', _132 => _132()]);
  8799. transition.skipTransition();
  8800. setInterruption({
  8801. state: newState,
  8802. currentLocation: viewTransitionOpts.currentLocation,
  8803. nextLocation: viewTransitionOpts.nextLocation
  8804. });
  8805. } else {
  8806. setPendingState(newState);
  8807. setVtContext({
  8808. isTransitioning: true,
  8809. flushSync: false,
  8810. currentLocation: viewTransitionOpts.currentLocation,
  8811. nextLocation: viewTransitionOpts.nextLocation
  8812. });
  8813. }
  8814. },
  8815. [
  8816. router.window,
  8817. reactDomFlushSyncImpl,
  8818. transition,
  8819. renderDfd,
  8820. unstable_useTransitions,
  8821. setOptimisticState,
  8822. unstable_onError
  8823. ]
  8824. );
  8825. React9.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
  8826. React9.useEffect(() => {
  8827. if (vtContext.isTransitioning && !vtContext.flushSync) {
  8828. setRenderDfd(new Deferred2());
  8829. }
  8830. }, [vtContext]);
  8831. React9.useEffect(() => {
  8832. if (renderDfd && pendingState && router.window) {
  8833. let newState = pendingState;
  8834. let renderPromise = renderDfd.promise;
  8835. let transition2 = router.window.document.startViewTransition(async () => {
  8836. if (unstable_useTransitions === false) {
  8837. setStateImpl(newState);
  8838. } else {
  8839. React9.startTransition(() => {
  8840. if (unstable_useTransitions === true) {
  8841. setOptimisticState((s) => getOptimisticRouterState(s, newState));
  8842. }
  8843. setStateImpl(newState);
  8844. });
  8845. }
  8846. await renderPromise;
  8847. });
  8848. transition2.finished.finally(() => {
  8849. setRenderDfd(void 0);
  8850. setTransition(void 0);
  8851. setPendingState(void 0);
  8852. setVtContext({ isTransitioning: false });
  8853. });
  8854. setTransition(transition2);
  8855. }
  8856. }, [
  8857. pendingState,
  8858. renderDfd,
  8859. router.window,
  8860. unstable_useTransitions,
  8861. setOptimisticState
  8862. ]);
  8863. React9.useEffect(() => {
  8864. if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
  8865. renderDfd.resolve();
  8866. }
  8867. }, [renderDfd, transition, state.location, pendingState]);
  8868. React9.useEffect(() => {
  8869. if (!vtContext.isTransitioning && interruption) {
  8870. setPendingState(interruption.state);
  8871. setVtContext({
  8872. isTransitioning: true,
  8873. flushSync: false,
  8874. currentLocation: interruption.currentLocation,
  8875. nextLocation: interruption.nextLocation
  8876. });
  8877. setInterruption(void 0);
  8878. }
  8879. }, [vtContext.isTransitioning, interruption]);
  8880. let navigator = React9.useMemo(() => {
  8881. return {
  8882. createHref: router.createHref,
  8883. encodeLocation: router.encodeLocation,
  8884. go: (n) => router.navigate(n),
  8885. push: (to, state2, opts) => router.navigate(to, {
  8886. state: state2,
  8887. preventScrollReset: _optionalChain([opts, 'optionalAccess', _133 => _133.preventScrollReset])
  8888. }),
  8889. replace: (to, state2, opts) => router.navigate(to, {
  8890. replace: true,
  8891. state: state2,
  8892. preventScrollReset: _optionalChain([opts, 'optionalAccess', _134 => _134.preventScrollReset])
  8893. })
  8894. };
  8895. }, [router]);
  8896. let basename = router.basename || "/";
  8897. let dataRouterContext = React9.useMemo(
  8898. () => ({
  8899. router,
  8900. navigator,
  8901. static: false,
  8902. basename,
  8903. unstable_onError
  8904. }),
  8905. [router, navigator, basename, unstable_onError]
  8906. );
  8907. return /* @__PURE__ */ React9.createElement(React9.Fragment, null, /* @__PURE__ */ React9.createElement(DataRouterContext.Provider, { value: dataRouterContext }, /* @__PURE__ */ React9.createElement(DataRouterStateContext.Provider, { value: state }, /* @__PURE__ */ React9.createElement(FetchersContext.Provider, { value: fetcherData.current }, /* @__PURE__ */ React9.createElement(ViewTransitionContext.Provider, { value: vtContext }, /* @__PURE__ */ React9.createElement(
  8908. Router,
  8909. {
  8910. basename,
  8911. location: state.location,
  8912. navigationType: state.historyAction,
  8913. navigator,
  8914. unstable_useTransitions: unstable_useTransitions === true
  8915. },
  8916. /* @__PURE__ */ React9.createElement(
  8917. MemoizedDataRoutes,
  8918. {
  8919. routes: router.routes,
  8920. future: router.future,
  8921. state,
  8922. unstable_onError
  8923. }
  8924. )
  8925. ))))), null);
  8926. }
  8927. function getOptimisticRouterState(currentState, newState) {
  8928. return {
  8929. // Don't surface "current location specific" stuff mid-navigation
  8930. // (historyAction, location, matches, loaderData, errors, initialized,
  8931. // restoreScroll, preventScrollReset, blockers, etc.)
  8932. ...currentState,
  8933. // Only surface "pending/in-flight stuff"
  8934. // (navigation, revalidation, actionData, fetchers, )
  8935. navigation: newState.navigation.state !== "idle" ? newState.navigation : currentState.navigation,
  8936. revalidation: newState.revalidation !== "idle" ? newState.revalidation : currentState.revalidation,
  8937. actionData: newState.navigation.state !== "submitting" ? newState.actionData : currentState.actionData,
  8938. fetchers: newState.fetchers
  8939. };
  8940. }
  8941. var MemoizedDataRoutes = React9.memo(DataRoutes);
  8942. function DataRoutes({
  8943. routes,
  8944. future,
  8945. state,
  8946. unstable_onError
  8947. }) {
  8948. return useRoutesImpl(routes, void 0, state, unstable_onError, future);
  8949. }
  8950. function MemoryRouter({
  8951. basename,
  8952. children,
  8953. initialEntries,
  8954. initialIndex,
  8955. unstable_useTransitions
  8956. }) {
  8957. let historyRef = React9.useRef();
  8958. if (historyRef.current == null) {
  8959. historyRef.current = createMemoryHistory({
  8960. initialEntries,
  8961. initialIndex,
  8962. v5Compat: true
  8963. });
  8964. }
  8965. let history = historyRef.current;
  8966. let [state, setStateImpl] = React9.useState({
  8967. action: history.action,
  8968. location: history.location
  8969. });
  8970. let setState = React9.useCallback(
  8971. (newState) => {
  8972. if (unstable_useTransitions === false) {
  8973. setStateImpl(newState);
  8974. } else {
  8975. React9.startTransition(() => setStateImpl(newState));
  8976. }
  8977. },
  8978. [unstable_useTransitions]
  8979. );
  8980. React9.useLayoutEffect(() => history.listen(setState), [history, setState]);
  8981. return /* @__PURE__ */ React9.createElement(
  8982. Router,
  8983. {
  8984. basename,
  8985. children,
  8986. location: state.location,
  8987. navigationType: state.action,
  8988. navigator: history,
  8989. unstable_useTransitions: unstable_useTransitions === true
  8990. }
  8991. );
  8992. }
  8993. function Navigate({
  8994. to,
  8995. replace: replace2,
  8996. state,
  8997. relative
  8998. }) {
  8999. invariant(
  9000. useInRouterContext(),
  9001. // TODO: This error is probably because they somehow have 2 versions of
  9002. // the router loaded. We can help them understand how to avoid that.
  9003. `<Navigate> may be used only in the context of a <Router> component.`
  9004. );
  9005. let { static: isStatic } = React9.useContext(NavigationContext);
  9006. warning(
  9007. !isStatic,
  9008. `<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`
  9009. );
  9010. let { matches } = React9.useContext(RouteContext);
  9011. let { pathname: locationPathname } = useLocation();
  9012. let navigate = useNavigate();
  9013. let path = resolveTo(
  9014. to,
  9015. getResolveToMatches(matches),
  9016. locationPathname,
  9017. relative === "path"
  9018. );
  9019. let jsonPath = JSON.stringify(path);
  9020. React9.useEffect(() => {
  9021. navigate(JSON.parse(jsonPath), { replace: replace2, state, relative });
  9022. }, [navigate, jsonPath, relative, replace2, state]);
  9023. return null;
  9024. }
  9025. function Outlet(props) {
  9026. return useOutlet(props.context);
  9027. }
  9028. function Route(props) {
  9029. invariant(
  9030. false,
  9031. `A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`
  9032. );
  9033. }
  9034. function Router({
  9035. basename: basenameProp = "/",
  9036. children = null,
  9037. location: locationProp,
  9038. navigationType = "POP" /* Pop */,
  9039. navigator,
  9040. static: staticProp = false,
  9041. unstable_useTransitions
  9042. }) {
  9043. invariant(
  9044. !useInRouterContext(),
  9045. `You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`
  9046. );
  9047. let basename = basenameProp.replace(/^\/*/, "/");
  9048. let navigationContext = React9.useMemo(
  9049. () => ({
  9050. basename,
  9051. navigator,
  9052. static: staticProp,
  9053. unstable_useTransitions,
  9054. future: {}
  9055. }),
  9056. [basename, navigator, staticProp, unstable_useTransitions]
  9057. );
  9058. if (typeof locationProp === "string") {
  9059. locationProp = parsePath(locationProp);
  9060. }
  9061. let {
  9062. pathname = "/",
  9063. search = "",
  9064. hash = "",
  9065. state = null,
  9066. key = "default"
  9067. } = locationProp;
  9068. let locationContext = React9.useMemo(() => {
  9069. let trailingPathname = stripBasename(pathname, basename);
  9070. if (trailingPathname == null) {
  9071. return null;
  9072. }
  9073. return {
  9074. location: {
  9075. pathname: trailingPathname,
  9076. search,
  9077. hash,
  9078. state,
  9079. key
  9080. },
  9081. navigationType
  9082. };
  9083. }, [basename, pathname, search, hash, state, key, navigationType]);
  9084. warning(
  9085. locationContext != null,
  9086. `<Router basename="${basename}"> is not able to match the URL "${pathname}${search}${hash}" because it does not start with the basename, so the <Router> won't render anything.`
  9087. );
  9088. if (locationContext == null) {
  9089. return null;
  9090. }
  9091. return /* @__PURE__ */ React9.createElement(NavigationContext.Provider, { value: navigationContext }, /* @__PURE__ */ React9.createElement(LocationContext.Provider, { children, value: locationContext }));
  9092. }
  9093. function Routes({
  9094. children,
  9095. location
  9096. }) {
  9097. return useRoutes(createRoutesFromChildren(children), location);
  9098. }
  9099. function Await({
  9100. children,
  9101. errorElement,
  9102. resolve
  9103. }) {
  9104. let dataRouterContext = React9.useContext(DataRouterContext);
  9105. let dataRouterStateContext = React9.useContext(DataRouterStateContext);
  9106. let onError = React9.useCallback(
  9107. (error, errorInfo) => {
  9108. if (dataRouterContext && dataRouterContext.unstable_onError && dataRouterStateContext) {
  9109. dataRouterContext.unstable_onError(error, {
  9110. location: dataRouterStateContext.location,
  9111. params: _optionalChain([dataRouterStateContext, 'access', _135 => _135.matches, 'access', _136 => _136[0], 'optionalAccess', _137 => _137.params]) || {},
  9112. unstable_pattern: getRoutePattern(dataRouterStateContext.matches),
  9113. errorInfo
  9114. });
  9115. }
  9116. },
  9117. [dataRouterContext, dataRouterStateContext]
  9118. );
  9119. return /* @__PURE__ */ React9.createElement(
  9120. AwaitErrorBoundary,
  9121. {
  9122. resolve,
  9123. errorElement,
  9124. onError
  9125. },
  9126. /* @__PURE__ */ React9.createElement(ResolveAwait, null, children)
  9127. );
  9128. }
  9129. var AwaitErrorBoundary = class extends React9.Component {
  9130. constructor(props) {
  9131. super(props);
  9132. this.state = { error: null };
  9133. }
  9134. static getDerivedStateFromError(error) {
  9135. return { error };
  9136. }
  9137. componentDidCatch(error, errorInfo) {
  9138. if (this.props.onError) {
  9139. this.props.onError(error, errorInfo);
  9140. } else {
  9141. console.error(
  9142. "<Await> caught the following error during render",
  9143. error,
  9144. errorInfo
  9145. );
  9146. }
  9147. }
  9148. render() {
  9149. let { children, errorElement, resolve } = this.props;
  9150. let promise = null;
  9151. let status = 0 /* pending */;
  9152. if (!(resolve instanceof Promise)) {
  9153. status = 1 /* success */;
  9154. promise = Promise.resolve();
  9155. Object.defineProperty(promise, "_tracked", { get: () => true });
  9156. Object.defineProperty(promise, "_data", { get: () => resolve });
  9157. } else if (this.state.error) {
  9158. status = 2 /* error */;
  9159. let renderError = this.state.error;
  9160. promise = Promise.reject().catch(() => {
  9161. });
  9162. Object.defineProperty(promise, "_tracked", { get: () => true });
  9163. Object.defineProperty(promise, "_error", { get: () => renderError });
  9164. } else if (resolve._tracked) {
  9165. promise = resolve;
  9166. status = "_error" in promise ? 2 /* error */ : "_data" in promise ? 1 /* success */ : 0 /* pending */;
  9167. } else {
  9168. status = 0 /* pending */;
  9169. Object.defineProperty(resolve, "_tracked", { get: () => true });
  9170. promise = resolve.then(
  9171. (data2) => Object.defineProperty(resolve, "_data", { get: () => data2 }),
  9172. (error) => {
  9173. _optionalChain([this, 'access', _138 => _138.props, 'access', _139 => _139.onError, 'optionalCall', _140 => _140(error)]);
  9174. Object.defineProperty(resolve, "_error", { get: () => error });
  9175. }
  9176. );
  9177. }
  9178. if (status === 2 /* error */ && !errorElement) {
  9179. throw promise._error;
  9180. }
  9181. if (status === 2 /* error */) {
  9182. return /* @__PURE__ */ React9.createElement(AwaitContext.Provider, { value: promise, children: errorElement });
  9183. }
  9184. if (status === 1 /* success */) {
  9185. return /* @__PURE__ */ React9.createElement(AwaitContext.Provider, { value: promise, children });
  9186. }
  9187. throw promise;
  9188. }
  9189. };
  9190. function ResolveAwait({
  9191. children
  9192. }) {
  9193. let data2 = useAsyncValue();
  9194. let toRender = typeof children === "function" ? children(data2) : children;
  9195. return /* @__PURE__ */ React9.createElement(React9.Fragment, null, toRender);
  9196. }
  9197. function createRoutesFromChildren(children, parentPath = []) {
  9198. let routes = [];
  9199. React9.Children.forEach(children, (element, index) => {
  9200. if (!React9.isValidElement(element)) {
  9201. return;
  9202. }
  9203. let treePath = [...parentPath, index];
  9204. if (element.type === React9.Fragment) {
  9205. routes.push.apply(
  9206. routes,
  9207. createRoutesFromChildren(element.props.children, treePath)
  9208. );
  9209. return;
  9210. }
  9211. invariant(
  9212. element.type === Route,
  9213. `[${typeof element.type === "string" ? element.type : element.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`
  9214. );
  9215. invariant(
  9216. !element.props.index || !element.props.children,
  9217. "An index route cannot have child routes."
  9218. );
  9219. let route = {
  9220. id: element.props.id || treePath.join("-"),
  9221. caseSensitive: element.props.caseSensitive,
  9222. element: element.props.element,
  9223. Component: element.props.Component,
  9224. index: element.props.index,
  9225. path: element.props.path,
  9226. middleware: element.props.middleware,
  9227. loader: element.props.loader,
  9228. action: element.props.action,
  9229. hydrateFallbackElement: element.props.hydrateFallbackElement,
  9230. HydrateFallback: element.props.HydrateFallback,
  9231. errorElement: element.props.errorElement,
  9232. ErrorBoundary: element.props.ErrorBoundary,
  9233. hasErrorBoundary: element.props.hasErrorBoundary === true || element.props.ErrorBoundary != null || element.props.errorElement != null,
  9234. shouldRevalidate: element.props.shouldRevalidate,
  9235. handle: element.props.handle,
  9236. lazy: element.props.lazy
  9237. };
  9238. if (element.props.children) {
  9239. route.children = createRoutesFromChildren(
  9240. element.props.children,
  9241. treePath
  9242. );
  9243. }
  9244. routes.push(route);
  9245. });
  9246. return routes;
  9247. }
  9248. var createRoutesFromElements = createRoutesFromChildren;
  9249. function renderMatches(matches) {
  9250. return _renderMatches(matches);
  9251. }
  9252. function useRouteComponentProps() {
  9253. return {
  9254. params: useParams(),
  9255. loaderData: useLoaderData(),
  9256. actionData: useActionData(),
  9257. matches: useMatches()
  9258. };
  9259. }
  9260. function WithComponentProps({
  9261. children
  9262. }) {
  9263. const props = useRouteComponentProps();
  9264. return React9.cloneElement(children, props);
  9265. }
  9266. function withComponentProps(Component4) {
  9267. return function WithComponentProps2() {
  9268. const props = useRouteComponentProps();
  9269. return React9.createElement(Component4, props);
  9270. };
  9271. }
  9272. function useHydrateFallbackProps() {
  9273. return {
  9274. params: useParams(),
  9275. loaderData: useLoaderData(),
  9276. actionData: useActionData()
  9277. };
  9278. }
  9279. function WithHydrateFallbackProps({
  9280. children
  9281. }) {
  9282. const props = useHydrateFallbackProps();
  9283. return React9.cloneElement(children, props);
  9284. }
  9285. function withHydrateFallbackProps(HydrateFallback) {
  9286. return function WithHydrateFallbackProps2() {
  9287. const props = useHydrateFallbackProps();
  9288. return React9.createElement(HydrateFallback, props);
  9289. };
  9290. }
  9291. function useErrorBoundaryProps() {
  9292. return {
  9293. params: useParams(),
  9294. loaderData: useLoaderData(),
  9295. actionData: useActionData(),
  9296. error: useRouteError()
  9297. };
  9298. }
  9299. function WithErrorBoundaryProps({
  9300. children
  9301. }) {
  9302. const props = useErrorBoundaryProps();
  9303. return React9.cloneElement(children, props);
  9304. }
  9305. function withErrorBoundaryProps(ErrorBoundary) {
  9306. return function WithErrorBoundaryProps2() {
  9307. const props = useErrorBoundaryProps();
  9308. return React9.createElement(ErrorBoundary, props);
  9309. };
  9310. }
  9311. exports.Action = Action; exports.createBrowserHistory = createBrowserHistory; exports.createHashHistory = createHashHistory; exports.invariant = invariant; exports.warning = warning; exports.createPath = createPath; exports.parsePath = parsePath; exports.createContext = createContext; exports.RouterContextProvider = RouterContextProvider; exports.convertRoutesToDataRoutes = convertRoutesToDataRoutes; exports.matchRoutes = matchRoutes; exports.generatePath = generatePath; exports.matchPath = matchPath; exports.stripBasename = stripBasename; exports.resolvePath = resolvePath; exports.joinPaths = joinPaths; exports.data = data; exports.redirect = redirect; exports.redirectDocument = redirectDocument; exports.replace = replace; exports.ErrorResponseImpl = ErrorResponseImpl; exports.isRouteErrorResponse = isRouteErrorResponse; exports.escapeHtml = escapeHtml; exports.encode = encode; exports.instrumentHandler = instrumentHandler; exports.IDLE_NAVIGATION = IDLE_NAVIGATION; exports.IDLE_FETCHER = IDLE_FETCHER; exports.IDLE_BLOCKER = IDLE_BLOCKER; exports.createRouter = createRouter; exports.createStaticHandler = createStaticHandler; exports.getStaticContextFromError = getStaticContextFromError; exports.isDataWithResponseInit = isDataWithResponseInit; exports.isResponse = isResponse; exports.isRedirectStatusCode = isRedirectStatusCode; exports.isRedirectResponse = isRedirectResponse; exports.isMutationMethod = isMutationMethod; exports.createRequestInit = createRequestInit; exports.SingleFetchRedirectSymbol = SingleFetchRedirectSymbol; exports.SINGLE_FETCH_REDIRECT_STATUS = SINGLE_FETCH_REDIRECT_STATUS; exports.NO_BODY_STATUS_CODES = NO_BODY_STATUS_CODES; exports.StreamTransfer = StreamTransfer; exports.getTurboStreamSingleFetchDataStrategy = getTurboStreamSingleFetchDataStrategy; exports.getSingleFetchDataStrategyImpl = getSingleFetchDataStrategyImpl; exports.stripIndexParam = stripIndexParam; exports.singleFetchUrl = singleFetchUrl; exports.decodeViaTurboStream = decodeViaTurboStream; exports.DataRouterContext = DataRouterContext; exports.DataRouterStateContext = DataRouterStateContext; exports.RSCRouterContext = RSCRouterContext; exports.ViewTransitionContext = ViewTransitionContext; exports.FetchersContext = FetchersContext; exports.AwaitContextProvider = AwaitContextProvider; exports.NavigationContext = NavigationContext; exports.LocationContext = LocationContext; exports.RouteContext = RouteContext; exports.ENABLE_DEV_WARNINGS = ENABLE_DEV_WARNINGS; exports.warnOnce = warnOnce; exports.useHref = useHref; exports.useInRouterContext = useInRouterContext; exports.useLocation = useLocation; exports.useNavigationType = useNavigationType; exports.useMatch = useMatch; exports.useNavigate = useNavigate; exports.useOutletContext = useOutletContext; exports.useOutlet = useOutlet; exports.useParams = useParams; exports.useResolvedPath = useResolvedPath; exports.useRoutes = useRoutes; exports.useRoutesImpl = useRoutesImpl; exports.useRouteId = useRouteId; exports.useNavigation = useNavigation; exports.useRevalidator = useRevalidator; exports.useMatches = useMatches; exports.useLoaderData = useLoaderData; exports.useRouteLoaderData = useRouteLoaderData; exports.useActionData = useActionData; exports.useRouteError = useRouteError; exports.useAsyncValue = useAsyncValue; exports.useAsyncError = useAsyncError; exports.useBlocker = useBlocker; exports.useRoute = useRoute; exports.RemixErrorBoundary = RemixErrorBoundary; exports.createServerRoutes = createServerRoutes; exports.createClientRoutesWithHMRRevalidationOptOut = createClientRoutesWithHMRRevalidationOptOut; exports.noActionDefinedError = noActionDefinedError; exports.createClientRoutes = createClientRoutes; exports.shouldHydrateRouteLoader = shouldHydrateRouteLoader; exports.getPatchRoutesOnNavigationFunction = getPatchRoutesOnNavigationFunction; exports.useFogOFWarDiscovery = useFogOFWarDiscovery; exports.getManifestPath = getManifestPath; exports.FrameworkContext = FrameworkContext; exports.usePrefetchBehavior = usePrefetchBehavior; exports.CRITICAL_CSS_DATA_ATTRIBUTE = CRITICAL_CSS_DATA_ATTRIBUTE; exports.Links = Links; exports.PrefetchPageLinks = PrefetchPageLinks; exports.Meta = Meta; exports.setIsHydrated = setIsHydrated; exports.Scripts = Scripts; exports.mergeRefs = mergeRefs; exports.mapRouteProperties = mapRouteProperties; exports.hydrationRouteProperties = hydrationRouteProperties; exports.createMemoryRouter = createMemoryRouter; exports.RouterProvider = RouterProvider; exports.MemoryRouter = MemoryRouter; exports.Navigate = Navigate; exports.Outlet = Outlet; exports.Route = Route; exports.Router = Router; exports.Routes = Routes; exports.Await = Await; exports.createRoutesFromChildren = createRoutesFromChildren; exports.createRoutesFromElements = createRoutesFromElements; exports.renderMatches = renderMatches; exports.WithComponentProps = WithComponentProps; exports.withComponentProps = withComponentProps; exports.WithHydrateFallbackProps = WithHydrateFallbackProps; exports.withHydrateFallbackProps = withHydrateFallbackProps; exports.WithErrorBoundaryProps = WithErrorBoundaryProps; exports.withErrorBoundaryProps = withErrorBoundaryProps;