router.umd.js 214 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647
  1. /**
  2. * @remix-run/router v1.23.2
  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. (function (global, factory) {
  12. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  13. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  14. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.RemixRouter = {}));
  15. })(this, (function (exports) { 'use strict';
  16. function _extends() {
  17. _extends = Object.assign ? Object.assign.bind() : function (target) {
  18. for (var i = 1; i < arguments.length; i++) {
  19. var source = arguments[i];
  20. for (var key in source) {
  21. if (Object.prototype.hasOwnProperty.call(source, key)) {
  22. target[key] = source[key];
  23. }
  24. }
  25. }
  26. return target;
  27. };
  28. return _extends.apply(this, arguments);
  29. }
  30. ////////////////////////////////////////////////////////////////////////////////
  31. //#region Types and Constants
  32. ////////////////////////////////////////////////////////////////////////////////
  33. /**
  34. * Actions represent the type of change to a location value.
  35. */
  36. let Action = /*#__PURE__*/function (Action) {
  37. Action["Pop"] = "POP";
  38. Action["Push"] = "PUSH";
  39. Action["Replace"] = "REPLACE";
  40. return Action;
  41. }({});
  42. /**
  43. * The pathname, search, and hash values of a URL.
  44. */
  45. // TODO: (v7) Change the Location generic default from `any` to `unknown` and
  46. // remove Remix `useLocation` wrapper.
  47. /**
  48. * An entry in a history stack. A location contains information about the
  49. * URL path, as well as possibly some arbitrary state and a key.
  50. */
  51. /**
  52. * A change to the current location.
  53. */
  54. /**
  55. * A function that receives notifications about location changes.
  56. */
  57. /**
  58. * Describes a location that is the destination of some navigation, either via
  59. * `history.push` or `history.replace`. This may be either a URL or the pieces
  60. * of a URL path.
  61. */
  62. /**
  63. * A history is an interface to the navigation stack. The history serves as the
  64. * source of truth for the current location, as well as provides a set of
  65. * methods that may be used to change it.
  66. *
  67. * It is similar to the DOM's `window.history` object, but with a smaller, more
  68. * focused API.
  69. */
  70. const PopStateEventType = "popstate";
  71. //#endregion
  72. ////////////////////////////////////////////////////////////////////////////////
  73. //#region Memory History
  74. ////////////////////////////////////////////////////////////////////////////////
  75. /**
  76. * A user-supplied object that describes a location. Used when providing
  77. * entries to `createMemoryHistory` via its `initialEntries` option.
  78. */
  79. /**
  80. * A memory history stores locations in memory. This is useful in stateful
  81. * environments where there is no web browser, such as node tests or React
  82. * Native.
  83. */
  84. /**
  85. * Memory history stores the current location in memory. It is designed for use
  86. * in stateful non-browser environments like tests and React Native.
  87. */
  88. function createMemoryHistory(options) {
  89. if (options === void 0) {
  90. options = {};
  91. }
  92. let {
  93. initialEntries = ["/"],
  94. initialIndex,
  95. v5Compat = false
  96. } = options;
  97. let entries; // Declare so we can access from createMemoryLocation
  98. entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
  99. let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
  100. let action = Action.Pop;
  101. let listener = null;
  102. function clampIndex(n) {
  103. return Math.min(Math.max(n, 0), entries.length - 1);
  104. }
  105. function getCurrentLocation() {
  106. return entries[index];
  107. }
  108. function createMemoryLocation(to, state, key) {
  109. if (state === void 0) {
  110. state = null;
  111. }
  112. let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
  113. warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
  114. return location;
  115. }
  116. function createHref(to) {
  117. return typeof to === "string" ? to : createPath(to);
  118. }
  119. let history = {
  120. get index() {
  121. return index;
  122. },
  123. get action() {
  124. return action;
  125. },
  126. get location() {
  127. return getCurrentLocation();
  128. },
  129. createHref,
  130. createURL(to) {
  131. return new URL(createHref(to), "http://localhost");
  132. },
  133. encodeLocation(to) {
  134. let path = typeof to === "string" ? parsePath(to) : to;
  135. return {
  136. pathname: path.pathname || "",
  137. search: path.search || "",
  138. hash: path.hash || ""
  139. };
  140. },
  141. push(to, state) {
  142. action = Action.Push;
  143. let nextLocation = createMemoryLocation(to, state);
  144. index += 1;
  145. entries.splice(index, entries.length, nextLocation);
  146. if (v5Compat && listener) {
  147. listener({
  148. action,
  149. location: nextLocation,
  150. delta: 1
  151. });
  152. }
  153. },
  154. replace(to, state) {
  155. action = Action.Replace;
  156. let nextLocation = createMemoryLocation(to, state);
  157. entries[index] = nextLocation;
  158. if (v5Compat && listener) {
  159. listener({
  160. action,
  161. location: nextLocation,
  162. delta: 0
  163. });
  164. }
  165. },
  166. go(delta) {
  167. action = Action.Pop;
  168. let nextIndex = clampIndex(index + delta);
  169. let nextLocation = entries[nextIndex];
  170. index = nextIndex;
  171. if (listener) {
  172. listener({
  173. action,
  174. location: nextLocation,
  175. delta
  176. });
  177. }
  178. },
  179. listen(fn) {
  180. listener = fn;
  181. return () => {
  182. listener = null;
  183. };
  184. }
  185. };
  186. return history;
  187. }
  188. //#endregion
  189. ////////////////////////////////////////////////////////////////////////////////
  190. //#region Browser History
  191. ////////////////////////////////////////////////////////////////////////////////
  192. /**
  193. * A browser history stores the current location in regular URLs in a web
  194. * browser environment. This is the standard for most web apps and provides the
  195. * cleanest URLs the browser's address bar.
  196. *
  197. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
  198. */
  199. /**
  200. * Browser history stores the location in regular URLs. This is the standard for
  201. * most web apps, but it requires some configuration on the server to ensure you
  202. * serve the same app at multiple URLs.
  203. *
  204. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
  205. */
  206. function createBrowserHistory(options) {
  207. if (options === void 0) {
  208. options = {};
  209. }
  210. function createBrowserLocation(window, globalHistory) {
  211. let {
  212. pathname,
  213. search,
  214. hash
  215. } = window.location;
  216. return createLocation("", {
  217. pathname,
  218. search,
  219. hash
  220. },
  221. // state defaults to `null` because `window.history.state` does
  222. globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
  223. }
  224. function createBrowserHref(window, to) {
  225. return typeof to === "string" ? to : createPath(to);
  226. }
  227. return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
  228. }
  229. //#endregion
  230. ////////////////////////////////////////////////////////////////////////////////
  231. //#region Hash History
  232. ////////////////////////////////////////////////////////////////////////////////
  233. /**
  234. * A hash history stores the current location in the fragment identifier portion
  235. * of the URL in a web browser environment.
  236. *
  237. * This is ideal for apps that do not control the server for some reason
  238. * (because the fragment identifier is never sent to the server), including some
  239. * shared hosting environments that do not provide fine-grained controls over
  240. * which pages are served at which URLs.
  241. *
  242. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
  243. */
  244. /**
  245. * Hash history stores the location in window.location.hash. This makes it ideal
  246. * for situations where you don't want to send the location to the server for
  247. * some reason, either because you do cannot configure it or the URL space is
  248. * reserved for something else.
  249. *
  250. * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
  251. */
  252. function createHashHistory(options) {
  253. if (options === void 0) {
  254. options = {};
  255. }
  256. function createHashLocation(window, globalHistory) {
  257. let {
  258. pathname = "/",
  259. search = "",
  260. hash = ""
  261. } = parsePath(window.location.hash.substr(1));
  262. // Hash URL should always have a leading / just like window.location.pathname
  263. // does, so if an app ends up at a route like /#something then we add a
  264. // leading slash so all of our path-matching behaves the same as if it would
  265. // in a browser router. This is particularly important when there exists a
  266. // root splat route (<Route path="*">) since that matches internally against
  267. // "/*" and we'd expect /#something to 404 in a hash router app.
  268. if (!pathname.startsWith("/") && !pathname.startsWith(".")) {
  269. pathname = "/" + pathname;
  270. }
  271. return createLocation("", {
  272. pathname,
  273. search,
  274. hash
  275. },
  276. // state defaults to `null` because `window.history.state` does
  277. globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
  278. }
  279. function createHashHref(window, to) {
  280. let base = window.document.querySelector("base");
  281. let href = "";
  282. if (base && base.getAttribute("href")) {
  283. let url = window.location.href;
  284. let hashIndex = url.indexOf("#");
  285. href = hashIndex === -1 ? url : url.slice(0, hashIndex);
  286. }
  287. return href + "#" + (typeof to === "string" ? to : createPath(to));
  288. }
  289. function validateHashLocation(location, to) {
  290. warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
  291. }
  292. return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
  293. }
  294. //#endregion
  295. ////////////////////////////////////////////////////////////////////////////////
  296. //#region UTILS
  297. ////////////////////////////////////////////////////////////////////////////////
  298. /**
  299. * @private
  300. */
  301. function invariant(value, message) {
  302. if (value === false || value === null || typeof value === "undefined") {
  303. throw new Error(message);
  304. }
  305. }
  306. function warning(cond, message) {
  307. if (!cond) {
  308. // eslint-disable-next-line no-console
  309. if (typeof console !== "undefined") console.warn(message);
  310. try {
  311. // Welcome to debugging history!
  312. //
  313. // This error is thrown as a convenience, so you can more easily
  314. // find the source for a warning that appears in the console by
  315. // enabling "pause on exceptions" in your JavaScript debugger.
  316. throw new Error(message);
  317. // eslint-disable-next-line no-empty
  318. } catch (e) {}
  319. }
  320. }
  321. function createKey() {
  322. return Math.random().toString(36).substr(2, 8);
  323. }
  324. /**
  325. * For browser-based histories, we combine the state and key into an object
  326. */
  327. function getHistoryState(location, index) {
  328. return {
  329. usr: location.state,
  330. key: location.key,
  331. idx: index
  332. };
  333. }
  334. /**
  335. * Creates a Location object with a unique key from the given Path
  336. */
  337. function createLocation(current, to, state, key) {
  338. if (state === void 0) {
  339. state = null;
  340. }
  341. let location = _extends({
  342. pathname: typeof current === "string" ? current : current.pathname,
  343. search: "",
  344. hash: ""
  345. }, typeof to === "string" ? parsePath(to) : to, {
  346. state,
  347. // TODO: This could be cleaned up. push/replace should probably just take
  348. // full Locations now and avoid the need to run through this flow at all
  349. // But that's a pretty big refactor to the current test suite so going to
  350. // keep as is for the time being and just let any incoming keys take precedence
  351. key: to && to.key || key || createKey()
  352. });
  353. return location;
  354. }
  355. /**
  356. * Creates a string URL path from the given pathname, search, and hash components.
  357. */
  358. function createPath(_ref) {
  359. let {
  360. pathname = "/",
  361. search = "",
  362. hash = ""
  363. } = _ref;
  364. if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
  365. if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  366. return pathname;
  367. }
  368. /**
  369. * Parses a string URL path into its separate pathname, search, and hash components.
  370. */
  371. function parsePath(path) {
  372. let parsedPath = {};
  373. if (path) {
  374. let hashIndex = path.indexOf("#");
  375. if (hashIndex >= 0) {
  376. parsedPath.hash = path.substr(hashIndex);
  377. path = path.substr(0, hashIndex);
  378. }
  379. let searchIndex = path.indexOf("?");
  380. if (searchIndex >= 0) {
  381. parsedPath.search = path.substr(searchIndex);
  382. path = path.substr(0, searchIndex);
  383. }
  384. if (path) {
  385. parsedPath.pathname = path;
  386. }
  387. }
  388. return parsedPath;
  389. }
  390. function getUrlBasedHistory(getLocation, createHref, validateLocation, options) {
  391. if (options === void 0) {
  392. options = {};
  393. }
  394. let {
  395. window = document.defaultView,
  396. v5Compat = false
  397. } = options;
  398. let globalHistory = window.history;
  399. let action = Action.Pop;
  400. let listener = null;
  401. let index = getIndex();
  402. // Index should only be null when we initialize. If not, it's because the
  403. // user called history.pushState or history.replaceState directly, in which
  404. // case we should log a warning as it will result in bugs.
  405. if (index == null) {
  406. index = 0;
  407. globalHistory.replaceState(_extends({}, globalHistory.state, {
  408. idx: index
  409. }), "");
  410. }
  411. function getIndex() {
  412. let state = globalHistory.state || {
  413. idx: null
  414. };
  415. return state.idx;
  416. }
  417. function handlePop() {
  418. action = Action.Pop;
  419. let nextIndex = getIndex();
  420. let delta = nextIndex == null ? null : nextIndex - index;
  421. index = nextIndex;
  422. if (listener) {
  423. listener({
  424. action,
  425. location: history.location,
  426. delta
  427. });
  428. }
  429. }
  430. function push(to, state) {
  431. action = Action.Push;
  432. let location = createLocation(history.location, to, state);
  433. if (validateLocation) validateLocation(location, to);
  434. index = getIndex() + 1;
  435. let historyState = getHistoryState(location, index);
  436. let url = history.createHref(location);
  437. // try...catch because iOS limits us to 100 pushState calls :/
  438. try {
  439. globalHistory.pushState(historyState, "", url);
  440. } catch (error) {
  441. // If the exception is because `state` can't be serialized, let that throw
  442. // outwards just like a replace call would so the dev knows the cause
  443. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps
  444. // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal
  445. if (error instanceof DOMException && error.name === "DataCloneError") {
  446. throw error;
  447. }
  448. // They are going to lose state here, but there is no real
  449. // way to warn them about it since the page will refresh...
  450. window.location.assign(url);
  451. }
  452. if (v5Compat && listener) {
  453. listener({
  454. action,
  455. location: history.location,
  456. delta: 1
  457. });
  458. }
  459. }
  460. function replace(to, state) {
  461. action = Action.Replace;
  462. let location = createLocation(history.location, to, state);
  463. if (validateLocation) validateLocation(location, to);
  464. index = getIndex();
  465. let historyState = getHistoryState(location, index);
  466. let url = history.createHref(location);
  467. globalHistory.replaceState(historyState, "", url);
  468. if (v5Compat && listener) {
  469. listener({
  470. action,
  471. location: history.location,
  472. delta: 0
  473. });
  474. }
  475. }
  476. function createURL(to) {
  477. // window.location.origin is "null" (the literal string value) in Firefox
  478. // under certain conditions, notably when serving from a local HTML file
  479. // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
  480. let base = window.location.origin !== "null" ? window.location.origin : window.location.href;
  481. let href = typeof to === "string" ? to : createPath(to);
  482. // Treating this as a full URL will strip any trailing spaces so we need to
  483. // pre-encode them since they might be part of a matching splat param from
  484. // an ancestor route
  485. href = href.replace(/ $/, "%20");
  486. invariant(base, "No window.location.(origin|href) available to create URL for href: " + href);
  487. return new URL(href, base);
  488. }
  489. let history = {
  490. get action() {
  491. return action;
  492. },
  493. get location() {
  494. return getLocation(window, globalHistory);
  495. },
  496. listen(fn) {
  497. if (listener) {
  498. throw new Error("A history only accepts one active listener");
  499. }
  500. window.addEventListener(PopStateEventType, handlePop);
  501. listener = fn;
  502. return () => {
  503. window.removeEventListener(PopStateEventType, handlePop);
  504. listener = null;
  505. };
  506. },
  507. createHref(to) {
  508. return createHref(window, to);
  509. },
  510. createURL,
  511. encodeLocation(to) {
  512. // Encode a Location the same way window.location would
  513. let url = createURL(to);
  514. return {
  515. pathname: url.pathname,
  516. search: url.search,
  517. hash: url.hash
  518. };
  519. },
  520. push,
  521. replace,
  522. go(n) {
  523. return globalHistory.go(n);
  524. }
  525. };
  526. return history;
  527. }
  528. //#endregion
  529. /**
  530. * Map of routeId -> data returned from a loader/action/error
  531. */
  532. let ResultType = /*#__PURE__*/function (ResultType) {
  533. ResultType["data"] = "data";
  534. ResultType["deferred"] = "deferred";
  535. ResultType["redirect"] = "redirect";
  536. ResultType["error"] = "error";
  537. return ResultType;
  538. }({});
  539. /**
  540. * Successful result from a loader or action
  541. */
  542. /**
  543. * Successful defer() result from a loader or action
  544. */
  545. /**
  546. * Redirect result from a loader or action
  547. */
  548. /**
  549. * Unsuccessful result from a loader or action
  550. */
  551. /**
  552. * Result from a loader or action - potentially successful or unsuccessful
  553. */
  554. /**
  555. * Users can specify either lowercase or uppercase form methods on `<Form>`,
  556. * useSubmit(), `<fetcher.Form>`, etc.
  557. */
  558. /**
  559. * Active navigation/fetcher form methods are exposed in lowercase on the
  560. * RouterState
  561. */
  562. /**
  563. * In v7, active navigation/fetcher form methods are exposed in uppercase on the
  564. * RouterState. This is to align with the normalization done via fetch().
  565. */
  566. // Thanks https://github.com/sindresorhus/type-fest!
  567. /**
  568. * @private
  569. * Internal interface to pass around for action submissions, not intended for
  570. * external consumption
  571. */
  572. /**
  573. * @private
  574. * Arguments passed to route loader/action functions. Same for now but we keep
  575. * this as a private implementation detail in case they diverge in the future.
  576. */
  577. // TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:
  578. // ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs
  579. // Also, make them a type alias instead of an interface
  580. /**
  581. * Arguments passed to loader functions
  582. */
  583. /**
  584. * Arguments passed to action functions
  585. */
  586. /**
  587. * Loaders and actions can return anything except `undefined` (`null` is a
  588. * valid return value if there is no data to return). Responses are preferred
  589. * and will ease any future migration to Remix
  590. */
  591. /**
  592. * Route loader function signature
  593. */
  594. /**
  595. * Route action function signature
  596. */
  597. /**
  598. * Arguments passed to shouldRevalidate function
  599. */
  600. /**
  601. * Route shouldRevalidate function signature. This runs after any submission
  602. * (navigation or fetcher), so we flatten the navigation/fetcher submission
  603. * onto the arguments. It shouldn't matter whether it came from a navigation
  604. * or a fetcher, what really matters is the URLs and the formData since loaders
  605. * have to re-run based on the data models that were potentially mutated.
  606. */
  607. /**
  608. * Function provided by the framework-aware layers to set `hasErrorBoundary`
  609. * from the framework-aware `errorElement` prop
  610. *
  611. * @deprecated Use `mapRouteProperties` instead
  612. */
  613. /**
  614. * Result from a loader or action called via dataStrategy
  615. */
  616. /**
  617. * Function provided by the framework-aware layers to set any framework-specific
  618. * properties from framework-agnostic properties
  619. */
  620. /**
  621. * Keys we cannot change from within a lazy() function. We spread all other keys
  622. * onto the route. Either they're meaningful to the router, or they'll get
  623. * ignored.
  624. */
  625. const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);
  626. /**
  627. * lazy() function to load a route definition, which can add non-matching
  628. * related properties to a route
  629. */
  630. /**
  631. * Base RouteObject with common props shared by all types of routes
  632. */
  633. /**
  634. * Index routes must not have children
  635. */
  636. /**
  637. * Non-index routes may have children, but cannot have index
  638. */
  639. /**
  640. * A route object represents a logical route, with (optionally) its child
  641. * routes organized in a tree-like structure.
  642. */
  643. /**
  644. * A data route object, which is just a RouteObject with a required unique ID
  645. */
  646. // Recursive helper for finding path parameters in the absence of wildcards
  647. /**
  648. * Examples:
  649. * "/a/b/*" -> "*"
  650. * ":a" -> "a"
  651. * "/a/:b" -> "b"
  652. * "/a/blahblahblah:b" -> "b"
  653. * "/:a/:b" -> "a" | "b"
  654. * "/:a/b/:c/*" -> "a" | "c" | "*"
  655. */
  656. // Attempt to parse the given string segment. If it fails, then just return the
  657. // plain string type as a default fallback. Otherwise, return the union of the
  658. // parsed string literals that were referenced as dynamic segments in the route.
  659. /**
  660. * The parameters that were parsed from the URL path.
  661. */
  662. /**
  663. * A RouteMatch contains info about how a route matched a URL.
  664. */
  665. function isIndexRoute(route) {
  666. return route.index === true;
  667. }
  668. // Walk the route tree generating unique IDs where necessary, so we are working
  669. // solely with AgnosticDataRouteObject's within the Router
  670. function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {
  671. if (parentPath === void 0) {
  672. parentPath = [];
  673. }
  674. if (manifest === void 0) {
  675. manifest = {};
  676. }
  677. return routes.map((route, index) => {
  678. let treePath = [...parentPath, String(index)];
  679. let id = typeof route.id === "string" ? route.id : treePath.join("-");
  680. invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
  681. invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages");
  682. if (isIndexRoute(route)) {
  683. let indexRoute = _extends({}, route, mapRouteProperties(route), {
  684. id
  685. });
  686. manifest[id] = indexRoute;
  687. return indexRoute;
  688. } else {
  689. let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {
  690. id,
  691. children: undefined
  692. });
  693. manifest[id] = pathOrLayoutRoute;
  694. if (route.children) {
  695. pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);
  696. }
  697. return pathOrLayoutRoute;
  698. }
  699. });
  700. }
  701. /**
  702. * Matches the given routes to a location and returns the match data.
  703. *
  704. * @see https://reactrouter.com/v6/utils/match-routes
  705. */
  706. function matchRoutes(routes, locationArg, basename) {
  707. if (basename === void 0) {
  708. basename = "/";
  709. }
  710. return matchRoutesImpl(routes, locationArg, basename, false);
  711. }
  712. function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
  713. let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  714. let pathname = stripBasename(location.pathname || "/", basename);
  715. if (pathname == null) {
  716. return null;
  717. }
  718. let branches = flattenRoutes(routes);
  719. rankRouteBranches(branches);
  720. let matches = null;
  721. for (let i = 0; matches == null && i < branches.length; ++i) {
  722. // Incoming pathnames are generally encoded from either window.location
  723. // or from router.navigate, but we want to match against the unencoded
  724. // paths in the route definitions. Memory router locations won't be
  725. // encoded here but there also shouldn't be anything to decode so this
  726. // should be a safe operation. This avoids needing matchRoutes to be
  727. // history-aware.
  728. let decoded = decodePath(pathname);
  729. matches = matchRouteBranch(branches[i], decoded, allowPartial);
  730. }
  731. return matches;
  732. }
  733. function convertRouteMatchToUiMatch(match, loaderData) {
  734. let {
  735. route,
  736. pathname,
  737. params
  738. } = match;
  739. return {
  740. id: route.id,
  741. pathname,
  742. params,
  743. data: loaderData[route.id],
  744. handle: route.handle
  745. };
  746. }
  747. function flattenRoutes(routes, branches, parentsMeta, parentPath) {
  748. if (branches === void 0) {
  749. branches = [];
  750. }
  751. if (parentsMeta === void 0) {
  752. parentsMeta = [];
  753. }
  754. if (parentPath === void 0) {
  755. parentPath = "";
  756. }
  757. let flattenRoute = (route, index, relativePath) => {
  758. let meta = {
  759. relativePath: relativePath === undefined ? route.path || "" : relativePath,
  760. caseSensitive: route.caseSensitive === true,
  761. childrenIndex: index,
  762. route
  763. };
  764. if (meta.relativePath.startsWith("/")) {
  765. invariant(meta.relativePath.startsWith(parentPath), "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.");
  766. meta.relativePath = meta.relativePath.slice(parentPath.length);
  767. }
  768. let path = joinPaths([parentPath, meta.relativePath]);
  769. let routesMeta = parentsMeta.concat(meta);
  770. // Add the children before adding this route to the array, so we traverse the
  771. // route tree depth-first and child routes appear before their parents in
  772. // the "flattened" version.
  773. if (route.children && route.children.length > 0) {
  774. invariant(
  775. // Our types know better, but runtime JS may not!
  776. // @ts-expect-error
  777. route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\"."));
  778. flattenRoutes(route.children, branches, routesMeta, path);
  779. }
  780. // Routes without a path shouldn't ever match by themselves unless they are
  781. // index routes, so don't add them to the list of possible branches.
  782. if (route.path == null && !route.index) {
  783. return;
  784. }
  785. branches.push({
  786. path,
  787. score: computeScore(path, route.index),
  788. routesMeta
  789. });
  790. };
  791. routes.forEach((route, index) => {
  792. var _route$path;
  793. // coarse-grain check for optional params
  794. if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) {
  795. flattenRoute(route, index);
  796. } else {
  797. for (let exploded of explodeOptionalSegments(route.path)) {
  798. flattenRoute(route, index, exploded);
  799. }
  800. }
  801. });
  802. return branches;
  803. }
  804. /**
  805. * Computes all combinations of optional path segments for a given path,
  806. * excluding combinations that are ambiguous and of lower priority.
  807. *
  808. * For example, `/one/:two?/three/:four?/:five?` explodes to:
  809. * - `/one/three`
  810. * - `/one/:two/three`
  811. * - `/one/three/:four`
  812. * - `/one/three/:five`
  813. * - `/one/:two/three/:four`
  814. * - `/one/:two/three/:five`
  815. * - `/one/three/:four/:five`
  816. * - `/one/:two/three/:four/:five`
  817. */
  818. function explodeOptionalSegments(path) {
  819. let segments = path.split("/");
  820. if (segments.length === 0) return [];
  821. let [first, ...rest] = segments;
  822. // Optional path segments are denoted by a trailing `?`
  823. let isOptional = first.endsWith("?");
  824. // Compute the corresponding required segment: `foo?` -> `foo`
  825. let required = first.replace(/\?$/, "");
  826. if (rest.length === 0) {
  827. // Intepret empty string as omitting an optional segment
  828. // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
  829. return isOptional ? [required, ""] : [required];
  830. }
  831. let restExploded = explodeOptionalSegments(rest.join("/"));
  832. let result = [];
  833. // All child paths with the prefix. Do this for all children before the
  834. // optional version for all children, so we get consistent ordering where the
  835. // parent optional aspect is preferred as required. Otherwise, we can get
  836. // child sections interspersed where deeper optional segments are higher than
  837. // parent optional segments, where for example, /:two would explode _earlier_
  838. // then /:one. By always including the parent as required _for all children_
  839. // first, we avoid this issue
  840. result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/")));
  841. // Then, if this is an optional value, add all child versions without
  842. if (isOptional) {
  843. result.push(...restExploded);
  844. }
  845. // for absolute paths, ensure `/` instead of empty segment
  846. return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded);
  847. }
  848. function rankRouteBranches(branches) {
  849. branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
  850. : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
  851. }
  852. const paramRe = /^:[\w-]+$/;
  853. const dynamicSegmentValue = 3;
  854. const indexRouteValue = 2;
  855. const emptySegmentValue = 1;
  856. const staticSegmentValue = 10;
  857. const splatPenalty = -2;
  858. const isSplat = s => s === "*";
  859. function computeScore(path, index) {
  860. let segments = path.split("/");
  861. let initialScore = segments.length;
  862. if (segments.some(isSplat)) {
  863. initialScore += splatPenalty;
  864. }
  865. if (index) {
  866. initialScore += indexRouteValue;
  867. }
  868. return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
  869. }
  870. function compareIndexes(a, b) {
  871. let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
  872. return siblings ?
  873. // If two routes are siblings, we should try to match the earlier sibling
  874. // first. This allows people to have fine-grained control over the matching
  875. // behavior by simply putting routes with identical paths in the order they
  876. // want them tried.
  877. a[a.length - 1] - b[b.length - 1] :
  878. // Otherwise, it doesn't really make sense to rank non-siblings by index,
  879. // so they sort equally.
  880. 0;
  881. }
  882. function matchRouteBranch(branch, pathname, allowPartial) {
  883. if (allowPartial === void 0) {
  884. allowPartial = false;
  885. }
  886. let {
  887. routesMeta
  888. } = branch;
  889. let matchedParams = {};
  890. let matchedPathname = "/";
  891. let matches = [];
  892. for (let i = 0; i < routesMeta.length; ++i) {
  893. let meta = routesMeta[i];
  894. let end = i === routesMeta.length - 1;
  895. let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
  896. let match = matchPath({
  897. path: meta.relativePath,
  898. caseSensitive: meta.caseSensitive,
  899. end
  900. }, remainingPathname);
  901. let route = meta.route;
  902. if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
  903. match = matchPath({
  904. path: meta.relativePath,
  905. caseSensitive: meta.caseSensitive,
  906. end: false
  907. }, remainingPathname);
  908. }
  909. if (!match) {
  910. return null;
  911. }
  912. Object.assign(matchedParams, match.params);
  913. matches.push({
  914. // TODO: Can this as be avoided?
  915. params: matchedParams,
  916. pathname: joinPaths([matchedPathname, match.pathname]),
  917. pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
  918. route
  919. });
  920. if (match.pathnameBase !== "/") {
  921. matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
  922. }
  923. }
  924. return matches;
  925. }
  926. /**
  927. * Returns a path with params interpolated.
  928. *
  929. * @see https://reactrouter.com/v6/utils/generate-path
  930. */
  931. function generatePath(originalPath, params) {
  932. if (params === void 0) {
  933. params = {};
  934. }
  935. let path = originalPath;
  936. if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
  937. warning(false, "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(/\*$/, "/*") + "\"."));
  938. path = path.replace(/\*$/, "/*");
  939. }
  940. // ensure `/` is added at the beginning if the path is absolute
  941. const prefix = path.startsWith("/") ? "/" : "";
  942. const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p);
  943. const segments = path.split(/\/+/).map((segment, index, array) => {
  944. const isLastSegment = index === array.length - 1;
  945. // only apply the splat if it's the last segment
  946. if (isLastSegment && segment === "*") {
  947. const star = "*";
  948. // Apply the splat
  949. return stringify(params[star]);
  950. }
  951. const keyMatch = segment.match(/^:([\w-]+)(\??)$/);
  952. if (keyMatch) {
  953. const [, key, optional] = keyMatch;
  954. let param = params[key];
  955. invariant(optional === "?" || param != null, "Missing \":" + key + "\" param");
  956. return stringify(param);
  957. }
  958. // Remove any optional markers from optional static segments
  959. return segment.replace(/\?$/g, "");
  960. })
  961. // Remove empty segments
  962. .filter(segment => !!segment);
  963. return prefix + segments.join("/");
  964. }
  965. /**
  966. * A PathPattern is used to match on some portion of a URL pathname.
  967. */
  968. /**
  969. * A PathMatch contains info about how a PathPattern matched on a URL pathname.
  970. */
  971. /**
  972. * Performs pattern matching on a URL pathname and returns information about
  973. * the match.
  974. *
  975. * @see https://reactrouter.com/v6/utils/match-path
  976. */
  977. function matchPath(pattern, pathname) {
  978. if (typeof pattern === "string") {
  979. pattern = {
  980. path: pattern,
  981. caseSensitive: false,
  982. end: true
  983. };
  984. }
  985. let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
  986. let match = pathname.match(matcher);
  987. if (!match) return null;
  988. let matchedPathname = match[0];
  989. let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  990. let captureGroups = match.slice(1);
  991. let params = compiledParams.reduce((memo, _ref, index) => {
  992. let {
  993. paramName,
  994. isOptional
  995. } = _ref;
  996. // We need to compute the pathnameBase here using the raw splat value
  997. // instead of using params["*"] later because it will be decoded then
  998. if (paramName === "*") {
  999. let splatValue = captureGroups[index] || "";
  1000. pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
  1001. }
  1002. const value = captureGroups[index];
  1003. if (isOptional && !value) {
  1004. memo[paramName] = undefined;
  1005. } else {
  1006. memo[paramName] = (value || "").replace(/%2F/g, "/");
  1007. }
  1008. return memo;
  1009. }, {});
  1010. return {
  1011. params,
  1012. pathname: matchedPathname,
  1013. pathnameBase,
  1014. pattern
  1015. };
  1016. }
  1017. function compilePath(path, caseSensitive, end) {
  1018. if (caseSensitive === void 0) {
  1019. caseSensitive = false;
  1020. }
  1021. if (end === void 0) {
  1022. end = true;
  1023. }
  1024. warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "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(/\*$/, "/*") + "\"."));
  1025. let params = [];
  1026. let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
  1027. .replace(/^\/*/, "/") // Make sure it has a leading /
  1028. .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars
  1029. .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => {
  1030. params.push({
  1031. paramName,
  1032. isOptional: isOptional != null
  1033. });
  1034. return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  1035. });
  1036. if (path.endsWith("*")) {
  1037. params.push({
  1038. paramName: "*"
  1039. });
  1040. regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
  1041. : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
  1042. } else if (end) {
  1043. // When matching to the end, ignore trailing slashes
  1044. regexpSource += "\\/*$";
  1045. } else if (path !== "" && path !== "/") {
  1046. // If our path is non-empty and contains anything beyond an initial slash,
  1047. // then we have _some_ form of path in our regex, so we should expect to
  1048. // match only if we find the end of this path segment. Look for an optional
  1049. // non-captured trailing slash (to match a portion of the URL) or the end
  1050. // of the path (if we've matched to the end). We used to do this with a
  1051. // word boundary but that gives false positives on routes like
  1052. // /user-preferences since `-` counts as a word boundary.
  1053. regexpSource += "(?:(?=\\/|$))";
  1054. } else ;
  1055. let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
  1056. return [matcher, params];
  1057. }
  1058. function decodePath(value) {
  1059. try {
  1060. return value.split("/").map(v => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
  1061. } catch (error) {
  1062. warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ")."));
  1063. return value;
  1064. }
  1065. }
  1066. /**
  1067. * @private
  1068. */
  1069. function stripBasename(pathname, basename) {
  1070. if (basename === "/") return pathname;
  1071. if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
  1072. return null;
  1073. }
  1074. // We want to leave trailing slash behavior in the user's control, so if they
  1075. // specify a basename with a trailing slash, we should support it
  1076. let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  1077. let nextChar = pathname.charAt(startIndex);
  1078. if (nextChar && nextChar !== "/") {
  1079. // pathname does not start with basename/
  1080. return null;
  1081. }
  1082. return pathname.slice(startIndex) || "/";
  1083. }
  1084. const ABSOLUTE_URL_REGEX$1 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  1085. const isAbsoluteUrl = url => ABSOLUTE_URL_REGEX$1.test(url);
  1086. /**
  1087. * Returns a resolved path object relative to the given pathname.
  1088. *
  1089. * @see https://reactrouter.com/v6/utils/resolve-path
  1090. */
  1091. function resolvePath(to, fromPathname) {
  1092. if (fromPathname === void 0) {
  1093. fromPathname = "/";
  1094. }
  1095. let {
  1096. pathname: toPathname,
  1097. search = "",
  1098. hash = ""
  1099. } = typeof to === "string" ? parsePath(to) : to;
  1100. let pathname;
  1101. if (toPathname) {
  1102. if (isAbsoluteUrl(toPathname)) {
  1103. pathname = toPathname;
  1104. } else {
  1105. if (toPathname.includes("//")) {
  1106. let oldPathname = toPathname;
  1107. toPathname = toPathname.replace(/\/\/+/g, "/");
  1108. warning(false, "Pathnames cannot have embedded double slashes - normalizing " + (oldPathname + " -> " + toPathname));
  1109. }
  1110. if (toPathname.startsWith("/")) {
  1111. pathname = resolvePathname(toPathname.substring(1), "/");
  1112. } else {
  1113. pathname = resolvePathname(toPathname, fromPathname);
  1114. }
  1115. }
  1116. } else {
  1117. pathname = fromPathname;
  1118. }
  1119. return {
  1120. pathname,
  1121. search: normalizeSearch(search),
  1122. hash: normalizeHash(hash)
  1123. };
  1124. }
  1125. function resolvePathname(relativePath, fromPathname) {
  1126. let segments = fromPathname.replace(/\/+$/, "").split("/");
  1127. let relativeSegments = relativePath.split("/");
  1128. relativeSegments.forEach(segment => {
  1129. if (segment === "..") {
  1130. // Keep the root "" segment so the pathname starts at /
  1131. if (segments.length > 1) segments.pop();
  1132. } else if (segment !== ".") {
  1133. segments.push(segment);
  1134. }
  1135. });
  1136. return segments.length > 1 ? segments.join("/") : "/";
  1137. }
  1138. function getInvalidPathError(char, field, dest, path) {
  1139. return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. 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.";
  1140. }
  1141. /**
  1142. * @private
  1143. *
  1144. * When processing relative navigation we want to ignore ancestor routes that
  1145. * do not contribute to the path, such that index/pathless layout routes don't
  1146. * interfere.
  1147. *
  1148. * For example, when moving a route element into an index route and/or a
  1149. * pathless layout route, relative link behavior contained within should stay
  1150. * the same. Both of the following examples should link back to the root:
  1151. *
  1152. * <Route path="/">
  1153. * <Route path="accounts" element={<Link to=".."}>
  1154. * </Route>
  1155. *
  1156. * <Route path="/">
  1157. * <Route path="accounts">
  1158. * <Route element={<AccountsLayout />}> // <-- Does not contribute
  1159. * <Route index element={<Link to=".."} /> // <-- Does not contribute
  1160. * </Route
  1161. * </Route>
  1162. * </Route>
  1163. */
  1164. function getPathContributingMatches(matches) {
  1165. return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
  1166. }
  1167. // Return the array of pathnames for the current route matches - used to
  1168. // generate the routePathnames input for resolveTo()
  1169. function getResolveToMatches(matches, v7_relativeSplatPath) {
  1170. let pathMatches = getPathContributingMatches(matches);
  1171. // When v7_relativeSplatPath is enabled, use the full pathname for the leaf
  1172. // match so we include splat values for "." links. See:
  1173. // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329
  1174. if (v7_relativeSplatPath) {
  1175. return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);
  1176. }
  1177. return pathMatches.map(match => match.pathnameBase);
  1178. }
  1179. /**
  1180. * @private
  1181. */
  1182. function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
  1183. if (isPathRelative === void 0) {
  1184. isPathRelative = false;
  1185. }
  1186. let to;
  1187. if (typeof toArg === "string") {
  1188. to = parsePath(toArg);
  1189. } else {
  1190. to = _extends({}, toArg);
  1191. invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
  1192. invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
  1193. invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
  1194. }
  1195. let isEmptyPath = toArg === "" || to.pathname === "";
  1196. let toPathname = isEmptyPath ? "/" : to.pathname;
  1197. let from;
  1198. // Routing is relative to the current pathname if explicitly requested.
  1199. //
  1200. // If a pathname is explicitly provided in `to`, it should be relative to the
  1201. // route context. This is explained in `Note on `<Link to>` values` in our
  1202. // migration guide from v5 as a means of disambiguation between `to` values
  1203. // that begin with `/` and those that do not. However, this is problematic for
  1204. // `to` values that do not provide a pathname. `to` can simply be a search or
  1205. // hash string, in which case we should assume that the navigation is relative
  1206. // to the current location's pathname and *not* the route pathname.
  1207. if (toPathname == null) {
  1208. from = locationPathname;
  1209. } else {
  1210. let routePathnameIndex = routePathnames.length - 1;
  1211. // With relative="route" (the default), each leading .. segment means
  1212. // "go up one route" instead of "go up one URL segment". This is a key
  1213. // difference from how <a href> works and a major reason we call this a
  1214. // "to" value instead of a "href".
  1215. if (!isPathRelative && toPathname.startsWith("..")) {
  1216. let toSegments = toPathname.split("/");
  1217. while (toSegments[0] === "..") {
  1218. toSegments.shift();
  1219. routePathnameIndex -= 1;
  1220. }
  1221. to.pathname = toSegments.join("/");
  1222. }
  1223. from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  1224. }
  1225. let path = resolvePath(to, from);
  1226. // Ensure the pathname has a trailing slash if the original "to" had one
  1227. let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  1228. // Or if this was a link to the current path which has a trailing slash
  1229. let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  1230. if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
  1231. path.pathname += "/";
  1232. }
  1233. return path;
  1234. }
  1235. /**
  1236. * @private
  1237. */
  1238. function getToPathname(to) {
  1239. // Empty strings should be treated the same as / paths
  1240. return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
  1241. }
  1242. /**
  1243. * @private
  1244. */
  1245. const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
  1246. /**
  1247. * @private
  1248. */
  1249. const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
  1250. /**
  1251. * @private
  1252. */
  1253. const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
  1254. /**
  1255. * @private
  1256. */
  1257. const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
  1258. /**
  1259. * This is a shortcut for creating `application/json` responses. Converts `data`
  1260. * to JSON and sets the `Content-Type` header.
  1261. *
  1262. * @deprecated The `json` method is deprecated in favor of returning raw objects.
  1263. * This method will be removed in v7.
  1264. */
  1265. const json = function json(data, init) {
  1266. if (init === void 0) {
  1267. init = {};
  1268. }
  1269. let responseInit = typeof init === "number" ? {
  1270. status: init
  1271. } : init;
  1272. let headers = new Headers(responseInit.headers);
  1273. if (!headers.has("Content-Type")) {
  1274. headers.set("Content-Type", "application/json; charset=utf-8");
  1275. }
  1276. return new Response(JSON.stringify(data), _extends({}, responseInit, {
  1277. headers
  1278. }));
  1279. };
  1280. class DataWithResponseInit {
  1281. constructor(data, init) {
  1282. this.type = "DataWithResponseInit";
  1283. this.data = data;
  1284. this.init = init || null;
  1285. }
  1286. }
  1287. /**
  1288. * Create "responses" that contain `status`/`headers` without forcing
  1289. * serialization into an actual `Response` - used by Remix single fetch
  1290. */
  1291. function data(data, init) {
  1292. return new DataWithResponseInit(data, typeof init === "number" ? {
  1293. status: init
  1294. } : init);
  1295. }
  1296. class AbortedDeferredError extends Error {}
  1297. class DeferredData {
  1298. constructor(data, responseInit) {
  1299. this.pendingKeysSet = new Set();
  1300. this.subscribers = new Set();
  1301. this.deferredKeys = [];
  1302. invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects");
  1303. // Set up an AbortController + Promise we can race against to exit early
  1304. // cancellation
  1305. let reject;
  1306. this.abortPromise = new Promise((_, r) => reject = r);
  1307. this.controller = new AbortController();
  1308. let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
  1309. this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
  1310. this.controller.signal.addEventListener("abort", onAbort);
  1311. this.data = Object.entries(data).reduce((acc, _ref2) => {
  1312. let [key, value] = _ref2;
  1313. return Object.assign(acc, {
  1314. [key]: this.trackPromise(key, value)
  1315. });
  1316. }, {});
  1317. if (this.done) {
  1318. // All incoming values were resolved
  1319. this.unlistenAbortSignal();
  1320. }
  1321. this.init = responseInit;
  1322. }
  1323. trackPromise(key, value) {
  1324. if (!(value instanceof Promise)) {
  1325. return value;
  1326. }
  1327. this.deferredKeys.push(key);
  1328. this.pendingKeysSet.add(key);
  1329. // We store a little wrapper promise that will be extended with
  1330. // _data/_error props upon resolve/reject
  1331. let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));
  1332. // Register rejection listeners to avoid uncaught promise rejections on
  1333. // errors or aborted deferred values
  1334. promise.catch(() => {});
  1335. Object.defineProperty(promise, "_tracked", {
  1336. get: () => true
  1337. });
  1338. return promise;
  1339. }
  1340. onSettle(promise, key, error, data) {
  1341. if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
  1342. this.unlistenAbortSignal();
  1343. Object.defineProperty(promise, "_error", {
  1344. get: () => error
  1345. });
  1346. return Promise.reject(error);
  1347. }
  1348. this.pendingKeysSet.delete(key);
  1349. if (this.done) {
  1350. // Nothing left to abort!
  1351. this.unlistenAbortSignal();
  1352. }
  1353. // If the promise was resolved/rejected with undefined, we'll throw an error as you
  1354. // should always resolve with a value or null
  1355. if (error === undefined && data === undefined) {
  1356. let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`.");
  1357. Object.defineProperty(promise, "_error", {
  1358. get: () => undefinedError
  1359. });
  1360. this.emit(false, key);
  1361. return Promise.reject(undefinedError);
  1362. }
  1363. if (data === undefined) {
  1364. Object.defineProperty(promise, "_error", {
  1365. get: () => error
  1366. });
  1367. this.emit(false, key);
  1368. return Promise.reject(error);
  1369. }
  1370. Object.defineProperty(promise, "_data", {
  1371. get: () => data
  1372. });
  1373. this.emit(false, key);
  1374. return data;
  1375. }
  1376. emit(aborted, settledKey) {
  1377. this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));
  1378. }
  1379. subscribe(fn) {
  1380. this.subscribers.add(fn);
  1381. return () => this.subscribers.delete(fn);
  1382. }
  1383. cancel() {
  1384. this.controller.abort();
  1385. this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));
  1386. this.emit(true);
  1387. }
  1388. async resolveData(signal) {
  1389. let aborted = false;
  1390. if (!this.done) {
  1391. let onAbort = () => this.cancel();
  1392. signal.addEventListener("abort", onAbort);
  1393. aborted = await new Promise(resolve => {
  1394. this.subscribe(aborted => {
  1395. signal.removeEventListener("abort", onAbort);
  1396. if (aborted || this.done) {
  1397. resolve(aborted);
  1398. }
  1399. });
  1400. });
  1401. }
  1402. return aborted;
  1403. }
  1404. get done() {
  1405. return this.pendingKeysSet.size === 0;
  1406. }
  1407. get unwrappedData() {
  1408. invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
  1409. return Object.entries(this.data).reduce((acc, _ref3) => {
  1410. let [key, value] = _ref3;
  1411. return Object.assign(acc, {
  1412. [key]: unwrapTrackedPromise(value)
  1413. });
  1414. }, {});
  1415. }
  1416. get pendingKeys() {
  1417. return Array.from(this.pendingKeysSet);
  1418. }
  1419. }
  1420. function isTrackedPromise(value) {
  1421. return value instanceof Promise && value._tracked === true;
  1422. }
  1423. function unwrapTrackedPromise(value) {
  1424. if (!isTrackedPromise(value)) {
  1425. return value;
  1426. }
  1427. if (value._error) {
  1428. throw value._error;
  1429. }
  1430. return value._data;
  1431. }
  1432. /**
  1433. * @deprecated The `defer` method is deprecated in favor of returning raw
  1434. * objects. This method will be removed in v7.
  1435. */
  1436. const defer = function defer(data, init) {
  1437. if (init === void 0) {
  1438. init = {};
  1439. }
  1440. let responseInit = typeof init === "number" ? {
  1441. status: init
  1442. } : init;
  1443. return new DeferredData(data, responseInit);
  1444. };
  1445. /**
  1446. * A redirect response. Sets the status code and the `Location` header.
  1447. * Defaults to "302 Found".
  1448. */
  1449. const redirect = function redirect(url, init) {
  1450. if (init === void 0) {
  1451. init = 302;
  1452. }
  1453. let responseInit = init;
  1454. if (typeof responseInit === "number") {
  1455. responseInit = {
  1456. status: responseInit
  1457. };
  1458. } else if (typeof responseInit.status === "undefined") {
  1459. responseInit.status = 302;
  1460. }
  1461. let headers = new Headers(responseInit.headers);
  1462. headers.set("Location", url);
  1463. return new Response(null, _extends({}, responseInit, {
  1464. headers
  1465. }));
  1466. };
  1467. /**
  1468. * A redirect response that will force a document reload to the new location.
  1469. * Sets the status code and the `Location` header.
  1470. * Defaults to "302 Found".
  1471. */
  1472. const redirectDocument = (url, init) => {
  1473. let response = redirect(url, init);
  1474. response.headers.set("X-Remix-Reload-Document", "true");
  1475. return response;
  1476. };
  1477. /**
  1478. * A redirect response that will perform a `history.replaceState` instead of a
  1479. * `history.pushState` for client-side navigation redirects.
  1480. * Sets the status code and the `Location` header.
  1481. * Defaults to "302 Found".
  1482. */
  1483. const replace = (url, init) => {
  1484. let response = redirect(url, init);
  1485. response.headers.set("X-Remix-Replace", "true");
  1486. return response;
  1487. };
  1488. /**
  1489. * @private
  1490. * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
  1491. *
  1492. * We don't export the class for public use since it's an implementation
  1493. * detail, but we export the interface above so folks can build their own
  1494. * abstractions around instances via isRouteErrorResponse()
  1495. */
  1496. class ErrorResponseImpl {
  1497. constructor(status, statusText, data, internal) {
  1498. if (internal === void 0) {
  1499. internal = false;
  1500. }
  1501. this.status = status;
  1502. this.statusText = statusText || "";
  1503. this.internal = internal;
  1504. if (data instanceof Error) {
  1505. this.data = data.toString();
  1506. this.error = data;
  1507. } else {
  1508. this.data = data;
  1509. }
  1510. }
  1511. }
  1512. /**
  1513. * Check if the given error is an ErrorResponse generated from a 4xx/5xx
  1514. * Response thrown from an action/loader
  1515. */
  1516. function isRouteErrorResponse(error) {
  1517. return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
  1518. }
  1519. ////////////////////////////////////////////////////////////////////////////////
  1520. //#region Types and Constants
  1521. ////////////////////////////////////////////////////////////////////////////////
  1522. /**
  1523. * A Router instance manages all navigation and data loading/mutations
  1524. */
  1525. /**
  1526. * State maintained internally by the router. During a navigation, all states
  1527. * reflect the the "old" location unless otherwise noted.
  1528. */
  1529. /**
  1530. * Data that can be passed into hydrate a Router from SSR
  1531. */
  1532. /**
  1533. * Future flags to toggle new feature behavior
  1534. */
  1535. /**
  1536. * Initialization options for createRouter
  1537. */
  1538. /**
  1539. * State returned from a server-side query() call
  1540. */
  1541. /**
  1542. * A StaticHandler instance manages a singular SSR navigation/fetch event
  1543. */
  1544. /**
  1545. * Subscriber function signature for changes to router state
  1546. */
  1547. /**
  1548. * Function signature for determining the key to be used in scroll restoration
  1549. * for a given location
  1550. */
  1551. /**
  1552. * Function signature for determining the current scroll position
  1553. */
  1554. // Allowed for any navigation or fetch
  1555. // Only allowed for navigations
  1556. // Only allowed for submission navigations
  1557. /**
  1558. * Options for a navigate() call for a normal (non-submission) navigation
  1559. */
  1560. /**
  1561. * Options for a navigate() call for a submission navigation
  1562. */
  1563. /**
  1564. * Options to pass to navigate() for a navigation
  1565. */
  1566. /**
  1567. * Options for a fetch() load
  1568. */
  1569. /**
  1570. * Options for a fetch() submission
  1571. */
  1572. /**
  1573. * Options to pass to fetch()
  1574. */
  1575. /**
  1576. * Potential states for state.navigation
  1577. */
  1578. /**
  1579. * Potential states for fetchers
  1580. */
  1581. /**
  1582. * Cached info for active fetcher.load() instances so they can participate
  1583. * in revalidation
  1584. */
  1585. /**
  1586. * Identified fetcher.load() calls that need to be revalidated
  1587. */
  1588. const validMutationMethodsArr = ["post", "put", "patch", "delete"];
  1589. const validMutationMethods = new Set(validMutationMethodsArr);
  1590. const validRequestMethodsArr = ["get", ...validMutationMethodsArr];
  1591. const validRequestMethods = new Set(validRequestMethodsArr);
  1592. const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
  1593. const redirectPreserveMethodStatusCodes = new Set([307, 308]);
  1594. const IDLE_NAVIGATION = {
  1595. state: "idle",
  1596. location: undefined,
  1597. formMethod: undefined,
  1598. formAction: undefined,
  1599. formEncType: undefined,
  1600. formData: undefined,
  1601. json: undefined,
  1602. text: undefined
  1603. };
  1604. const IDLE_FETCHER = {
  1605. state: "idle",
  1606. data: undefined,
  1607. formMethod: undefined,
  1608. formAction: undefined,
  1609. formEncType: undefined,
  1610. formData: undefined,
  1611. json: undefined,
  1612. text: undefined
  1613. };
  1614. const IDLE_BLOCKER = {
  1615. state: "unblocked",
  1616. proceed: undefined,
  1617. reset: undefined,
  1618. location: undefined
  1619. };
  1620. const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  1621. const defaultMapRouteProperties = route => ({
  1622. hasErrorBoundary: Boolean(route.hasErrorBoundary)
  1623. });
  1624. const TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
  1625. //#endregion
  1626. ////////////////////////////////////////////////////////////////////////////////
  1627. //#region createRouter
  1628. ////////////////////////////////////////////////////////////////////////////////
  1629. /**
  1630. * Create a router and listen to history POP navigations
  1631. */
  1632. function createRouter(init) {
  1633. const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined;
  1634. const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
  1635. const isServer = !isBrowser;
  1636. invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
  1637. let mapRouteProperties;
  1638. if (init.mapRouteProperties) {
  1639. mapRouteProperties = init.mapRouteProperties;
  1640. } else if (init.detectErrorBoundary) {
  1641. // If they are still using the deprecated version, wrap it with the new API
  1642. let detectErrorBoundary = init.detectErrorBoundary;
  1643. mapRouteProperties = route => ({
  1644. hasErrorBoundary: detectErrorBoundary(route)
  1645. });
  1646. } else {
  1647. mapRouteProperties = defaultMapRouteProperties;
  1648. }
  1649. // Routes keyed by ID
  1650. let manifest = {};
  1651. // Routes in tree format for matching
  1652. let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);
  1653. let inFlightDataRoutes;
  1654. let basename = init.basename || "/";
  1655. let dataStrategyImpl = init.dataStrategy || defaultDataStrategy;
  1656. let patchRoutesOnNavigationImpl = init.patchRoutesOnNavigation;
  1657. // Config driven behavior flags
  1658. let future = _extends({
  1659. v7_fetcherPersist: false,
  1660. v7_normalizeFormMethod: false,
  1661. v7_partialHydration: false,
  1662. v7_prependBasename: false,
  1663. v7_relativeSplatPath: false,
  1664. v7_skipActionErrorRevalidation: false
  1665. }, init.future);
  1666. // Cleanup function for history
  1667. let unlistenHistory = null;
  1668. // Externally-provided functions to call on all state changes
  1669. let subscribers = new Set();
  1670. // Externally-provided object to hold scroll restoration locations during routing
  1671. let savedScrollPositions = null;
  1672. // Externally-provided function to get scroll restoration keys
  1673. let getScrollRestorationKey = null;
  1674. // Externally-provided function to get current scroll position
  1675. let getScrollPosition = null;
  1676. // One-time flag to control the initial hydration scroll restoration. Because
  1677. // we don't get the saved positions from <ScrollRestoration /> until _after_
  1678. // the initial render, we need to manually trigger a separate updateState to
  1679. // send along the restoreScrollPosition
  1680. // Set to true if we have `hydrationData` since we assume we were SSR'd and that
  1681. // SSR did the initial scroll restoration.
  1682. let initialScrollRestored = init.hydrationData != null;
  1683. let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);
  1684. let initialMatchesIsFOW = false;
  1685. let initialErrors = null;
  1686. if (initialMatches == null && !patchRoutesOnNavigationImpl) {
  1687. // If we do not match a user-provided-route, fall back to the root
  1688. // to allow the error boundary to take over
  1689. let error = getInternalRouterError(404, {
  1690. pathname: init.history.location.pathname
  1691. });
  1692. let {
  1693. matches,
  1694. route
  1695. } = getShortCircuitMatches(dataRoutes);
  1696. initialMatches = matches;
  1697. initialErrors = {
  1698. [route.id]: error
  1699. };
  1700. }
  1701. // In SPA apps, if the user provided a patchRoutesOnNavigation implementation and
  1702. // our initial match is a splat route, clear them out so we run through lazy
  1703. // discovery on hydration in case there's a more accurate lazy route match.
  1704. // In SSR apps (with `hydrationData`), we expect that the server will send
  1705. // up the proper matched routes so we don't want to run lazy discovery on
  1706. // initial hydration and want to hydrate into the splat route.
  1707. if (initialMatches && !init.hydrationData) {
  1708. let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname);
  1709. if (fogOfWar.active) {
  1710. initialMatches = null;
  1711. }
  1712. }
  1713. let initialized;
  1714. if (!initialMatches) {
  1715. initialized = false;
  1716. initialMatches = [];
  1717. // If partial hydration and fog of war is enabled, we will be running
  1718. // `patchRoutesOnNavigation` during hydration so include any partial matches as
  1719. // the initial matches so we can properly render `HydrateFallback`'s
  1720. if (future.v7_partialHydration) {
  1721. let fogOfWar = checkFogOfWar(null, dataRoutes, init.history.location.pathname);
  1722. if (fogOfWar.active && fogOfWar.matches) {
  1723. initialMatchesIsFOW = true;
  1724. initialMatches = fogOfWar.matches;
  1725. }
  1726. }
  1727. } else if (initialMatches.some(m => m.route.lazy)) {
  1728. // All initialMatches need to be loaded before we're ready. If we have lazy
  1729. // functions around still then we'll need to run them in initialize()
  1730. initialized = false;
  1731. } else if (!initialMatches.some(m => m.route.loader)) {
  1732. // If we've got no loaders to run, then we're good to go
  1733. initialized = true;
  1734. } else if (future.v7_partialHydration) {
  1735. // If partial hydration is enabled, we're initialized so long as we were
  1736. // provided with hydrationData for every route with a loader, and no loaders
  1737. // were marked for explicit hydration
  1738. let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
  1739. let errors = init.hydrationData ? init.hydrationData.errors : null;
  1740. // If errors exist, don't consider routes below the boundary
  1741. if (errors) {
  1742. let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);
  1743. initialized = initialMatches.slice(0, idx + 1).every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
  1744. } else {
  1745. initialized = initialMatches.every(m => !shouldLoadRouteOnHydration(m.route, loaderData, errors));
  1746. }
  1747. } else {
  1748. // Without partial hydration - we're initialized if we were provided any
  1749. // hydrationData - which is expected to be complete
  1750. initialized = init.hydrationData != null;
  1751. }
  1752. let router;
  1753. let state = {
  1754. historyAction: init.history.action,
  1755. location: init.history.location,
  1756. matches: initialMatches,
  1757. initialized,
  1758. navigation: IDLE_NAVIGATION,
  1759. // Don't restore on initial updateState() if we were SSR'd
  1760. restoreScrollPosition: init.hydrationData != null ? false : null,
  1761. preventScrollReset: false,
  1762. revalidation: "idle",
  1763. loaderData: init.hydrationData && init.hydrationData.loaderData || {},
  1764. actionData: init.hydrationData && init.hydrationData.actionData || null,
  1765. errors: init.hydrationData && init.hydrationData.errors || initialErrors,
  1766. fetchers: new Map(),
  1767. blockers: new Map()
  1768. };
  1769. // -- Stateful internal variables to manage navigations --
  1770. // Current navigation in progress (to be committed in completeNavigation)
  1771. let pendingAction = Action.Pop;
  1772. // Should the current navigation prevent the scroll reset if scroll cannot
  1773. // be restored?
  1774. let pendingPreventScrollReset = false;
  1775. // AbortController for the active navigation
  1776. let pendingNavigationController;
  1777. // Should the current navigation enable document.startViewTransition?
  1778. let pendingViewTransitionEnabled = false;
  1779. // Store applied view transitions so we can apply them on POP
  1780. let appliedViewTransitions = new Map();
  1781. // Cleanup function for persisting applied transitions to sessionStorage
  1782. let removePageHideEventListener = null;
  1783. // We use this to avoid touching history in completeNavigation if a
  1784. // revalidation is entirely uninterrupted
  1785. let isUninterruptedRevalidation = false;
  1786. // Use this internal flag to force revalidation of all loaders:
  1787. // - submissions (completed or interrupted)
  1788. // - useRevalidator()
  1789. // - X-Remix-Revalidate (from redirect)
  1790. let isRevalidationRequired = false;
  1791. // Use this internal array to capture routes that require revalidation due
  1792. // to a cancelled deferred on action submission
  1793. let cancelledDeferredRoutes = [];
  1794. // Use this internal array to capture fetcher loads that were cancelled by an
  1795. // action navigation and require revalidation
  1796. let cancelledFetcherLoads = new Set();
  1797. // AbortControllers for any in-flight fetchers
  1798. let fetchControllers = new Map();
  1799. // Track loads based on the order in which they started
  1800. let incrementingLoadId = 0;
  1801. // Track the outstanding pending navigation data load to be compared against
  1802. // the globally incrementing load when a fetcher load lands after a completed
  1803. // navigation
  1804. let pendingNavigationLoadId = -1;
  1805. // Fetchers that triggered data reloads as a result of their actions
  1806. let fetchReloadIds = new Map();
  1807. // Fetchers that triggered redirect navigations
  1808. let fetchRedirectIds = new Set();
  1809. // Most recent href/match for fetcher.load calls for fetchers
  1810. let fetchLoadMatches = new Map();
  1811. // Ref-count mounted fetchers so we know when it's ok to clean them up
  1812. let activeFetchers = new Map();
  1813. // Fetchers that have requested a delete when using v7_fetcherPersist,
  1814. // they'll be officially removed after they return to idle
  1815. let deletedFetchers = new Set();
  1816. // Store DeferredData instances for active route matches. When a
  1817. // route loader returns defer() we stick one in here. Then, when a nested
  1818. // promise resolves we update loaderData. If a new navigation starts we
  1819. // cancel active deferreds for eliminated routes.
  1820. let activeDeferreds = new Map();
  1821. // Store blocker functions in a separate Map outside of router state since
  1822. // we don't need to update UI state if they change
  1823. let blockerFunctions = new Map();
  1824. // Flag to ignore the next history update, so we can revert the URL change on
  1825. // a POP navigation that was blocked by the user without touching router state
  1826. let unblockBlockerHistoryUpdate = undefined;
  1827. // Initialize the router, all side effects should be kicked off from here.
  1828. // Implemented as a Fluent API for ease of:
  1829. // let router = createRouter(init).initialize();
  1830. function initialize() {
  1831. // If history informs us of a POP navigation, start the navigation but do not update
  1832. // state. We'll update our own state once the navigation completes
  1833. unlistenHistory = init.history.listen(_ref => {
  1834. let {
  1835. action: historyAction,
  1836. location,
  1837. delta
  1838. } = _ref;
  1839. // Ignore this event if it was just us resetting the URL from a
  1840. // blocked POP navigation
  1841. if (unblockBlockerHistoryUpdate) {
  1842. unblockBlockerHistoryUpdate();
  1843. unblockBlockerHistoryUpdate = undefined;
  1844. return;
  1845. }
  1846. warning(blockerFunctions.size === 0 || delta != null, "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.");
  1847. let blockerKey = shouldBlockNavigation({
  1848. currentLocation: state.location,
  1849. nextLocation: location,
  1850. historyAction
  1851. });
  1852. if (blockerKey && delta != null) {
  1853. // Restore the URL to match the current UI, but don't update router state
  1854. let nextHistoryUpdatePromise = new Promise(resolve => {
  1855. unblockBlockerHistoryUpdate = resolve;
  1856. });
  1857. init.history.go(delta * -1);
  1858. // Put the blocker into a blocked state
  1859. updateBlocker(blockerKey, {
  1860. state: "blocked",
  1861. location,
  1862. proceed() {
  1863. updateBlocker(blockerKey, {
  1864. state: "proceeding",
  1865. proceed: undefined,
  1866. reset: undefined,
  1867. location
  1868. });
  1869. // Re-do the same POP navigation we just blocked, after the url
  1870. // restoration is also complete. See:
  1871. // https://github.com/remix-run/react-router/issues/11613
  1872. nextHistoryUpdatePromise.then(() => init.history.go(delta));
  1873. },
  1874. reset() {
  1875. let blockers = new Map(state.blockers);
  1876. blockers.set(blockerKey, IDLE_BLOCKER);
  1877. updateState({
  1878. blockers
  1879. });
  1880. }
  1881. });
  1882. return;
  1883. }
  1884. return startNavigation(historyAction, location);
  1885. });
  1886. if (isBrowser) {
  1887. // FIXME: This feels gross. How can we cleanup the lines between
  1888. // scrollRestoration/appliedTransitions persistance?
  1889. restoreAppliedTransitions(routerWindow, appliedViewTransitions);
  1890. let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
  1891. routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
  1892. removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
  1893. }
  1894. // Kick off initial data load if needed. Use Pop to avoid modifying history
  1895. // Note we don't do any handling of lazy here. For SPA's it'll get handled
  1896. // in the normal navigation flow. For SSR it's expected that lazy modules are
  1897. // resolved prior to router creation since we can't go into a fallbackElement
  1898. // UI for SSR'd apps
  1899. if (!state.initialized) {
  1900. startNavigation(Action.Pop, state.location, {
  1901. initialHydration: true
  1902. });
  1903. }
  1904. return router;
  1905. }
  1906. // Clean up a router and it's side effects
  1907. function dispose() {
  1908. if (unlistenHistory) {
  1909. unlistenHistory();
  1910. }
  1911. if (removePageHideEventListener) {
  1912. removePageHideEventListener();
  1913. }
  1914. subscribers.clear();
  1915. pendingNavigationController && pendingNavigationController.abort();
  1916. state.fetchers.forEach((_, key) => deleteFetcher(key));
  1917. state.blockers.forEach((_, key) => deleteBlocker(key));
  1918. }
  1919. // Subscribe to state updates for the router
  1920. function subscribe(fn) {
  1921. subscribers.add(fn);
  1922. return () => subscribers.delete(fn);
  1923. }
  1924. // Update our state and notify the calling context of the change
  1925. function updateState(newState, opts) {
  1926. if (opts === void 0) {
  1927. opts = {};
  1928. }
  1929. state = _extends({}, state, newState);
  1930. // Prep fetcher cleanup so we can tell the UI which fetcher data entries
  1931. // can be removed
  1932. let completedFetchers = [];
  1933. let deletedFetchersKeys = [];
  1934. if (future.v7_fetcherPersist) {
  1935. state.fetchers.forEach((fetcher, key) => {
  1936. if (fetcher.state === "idle") {
  1937. if (deletedFetchers.has(key)) {
  1938. // Unmounted from the UI and can be totally removed
  1939. deletedFetchersKeys.push(key);
  1940. } else {
  1941. // Returned to idle but still mounted in the UI, so semi-remains for
  1942. // revalidations and such
  1943. completedFetchers.push(key);
  1944. }
  1945. }
  1946. });
  1947. }
  1948. // Remove any lingering deleted fetchers that have already been removed
  1949. // from state.fetchers
  1950. deletedFetchers.forEach(key => {
  1951. if (!state.fetchers.has(key) && !fetchControllers.has(key)) {
  1952. deletedFetchersKeys.push(key);
  1953. }
  1954. });
  1955. // Iterate over a local copy so that if flushSync is used and we end up
  1956. // removing and adding a new subscriber due to the useCallback dependencies,
  1957. // we don't get ourselves into a loop calling the new subscriber immediately
  1958. [...subscribers].forEach(subscriber => subscriber(state, {
  1959. deletedFetchers: deletedFetchersKeys,
  1960. viewTransitionOpts: opts.viewTransitionOpts,
  1961. flushSync: opts.flushSync === true
  1962. }));
  1963. // Remove idle fetchers from state since we only care about in-flight fetchers.
  1964. if (future.v7_fetcherPersist) {
  1965. completedFetchers.forEach(key => state.fetchers.delete(key));
  1966. deletedFetchersKeys.forEach(key => deleteFetcher(key));
  1967. } else {
  1968. // We already called deleteFetcher() on these, can remove them from this
  1969. // Set now that we've handed the keys off to the data layer
  1970. deletedFetchersKeys.forEach(key => deletedFetchers.delete(key));
  1971. }
  1972. }
  1973. // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
  1974. // and setting state.[historyAction/location/matches] to the new route.
  1975. // - Location is a required param
  1976. // - Navigation will always be set to IDLE_NAVIGATION
  1977. // - Can pass any other state in newState
  1978. function completeNavigation(location, newState, _temp) {
  1979. var _location$state, _location$state2;
  1980. let {
  1981. flushSync
  1982. } = _temp === void 0 ? {} : _temp;
  1983. // Deduce if we're in a loading/actionReload state:
  1984. // - We have committed actionData in the store
  1985. // - The current navigation was a mutation submission
  1986. // - We're past the submitting state and into the loading state
  1987. // - The location being loaded is not the result of a redirect
  1988. let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;
  1989. let actionData;
  1990. if (newState.actionData) {
  1991. if (Object.keys(newState.actionData).length > 0) {
  1992. actionData = newState.actionData;
  1993. } else {
  1994. // Empty actionData -> clear prior actionData due to an action error
  1995. actionData = null;
  1996. }
  1997. } else if (isActionReload) {
  1998. // Keep the current data if we're wrapping up the action reload
  1999. actionData = state.actionData;
  2000. } else {
  2001. // Clear actionData on any other completed navigations
  2002. actionData = null;
  2003. }
  2004. // Always preserve any existing loaderData from re-used routes
  2005. let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;
  2006. // On a successful navigation we can assume we got through all blockers
  2007. // so we can start fresh
  2008. let blockers = state.blockers;
  2009. if (blockers.size > 0) {
  2010. blockers = new Map(blockers);
  2011. blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
  2012. }
  2013. // Always respect the user flag. Otherwise don't reset on mutation
  2014. // submission navigations unless they redirect
  2015. let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;
  2016. // Commit any in-flight routes at the end of the HMR revalidation "navigation"
  2017. if (inFlightDataRoutes) {
  2018. dataRoutes = inFlightDataRoutes;
  2019. inFlightDataRoutes = undefined;
  2020. }
  2021. if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {
  2022. init.history.push(location, location.state);
  2023. } else if (pendingAction === Action.Replace) {
  2024. init.history.replace(location, location.state);
  2025. }
  2026. let viewTransitionOpts;
  2027. // On POP, enable transitions if they were enabled on the original navigation
  2028. if (pendingAction === Action.Pop) {
  2029. // Forward takes precedence so they behave like the original navigation
  2030. let priorPaths = appliedViewTransitions.get(state.location.pathname);
  2031. if (priorPaths && priorPaths.has(location.pathname)) {
  2032. viewTransitionOpts = {
  2033. currentLocation: state.location,
  2034. nextLocation: location
  2035. };
  2036. } else if (appliedViewTransitions.has(location.pathname)) {
  2037. // If we don't have a previous forward nav, assume we're popping back to
  2038. // the new location and enable if that location previously enabled
  2039. viewTransitionOpts = {
  2040. currentLocation: location,
  2041. nextLocation: state.location
  2042. };
  2043. }
  2044. } else if (pendingViewTransitionEnabled) {
  2045. // Store the applied transition on PUSH/REPLACE
  2046. let toPaths = appliedViewTransitions.get(state.location.pathname);
  2047. if (toPaths) {
  2048. toPaths.add(location.pathname);
  2049. } else {
  2050. toPaths = new Set([location.pathname]);
  2051. appliedViewTransitions.set(state.location.pathname, toPaths);
  2052. }
  2053. viewTransitionOpts = {
  2054. currentLocation: state.location,
  2055. nextLocation: location
  2056. };
  2057. }
  2058. updateState(_extends({}, newState, {
  2059. // matches, errors, fetchers go through as-is
  2060. actionData,
  2061. loaderData,
  2062. historyAction: pendingAction,
  2063. location,
  2064. initialized: true,
  2065. navigation: IDLE_NAVIGATION,
  2066. revalidation: "idle",
  2067. restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),
  2068. preventScrollReset,
  2069. blockers
  2070. }), {
  2071. viewTransitionOpts,
  2072. flushSync: flushSync === true
  2073. });
  2074. // Reset stateful navigation vars
  2075. pendingAction = Action.Pop;
  2076. pendingPreventScrollReset = false;
  2077. pendingViewTransitionEnabled = false;
  2078. isUninterruptedRevalidation = false;
  2079. isRevalidationRequired = false;
  2080. cancelledDeferredRoutes = [];
  2081. }
  2082. // Trigger a navigation event, which can either be a numerical POP or a PUSH
  2083. // replace with an optional submission
  2084. async function navigate(to, opts) {
  2085. if (typeof to === "number") {
  2086. init.history.go(to);
  2087. return;
  2088. }
  2089. let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);
  2090. let {
  2091. path,
  2092. submission,
  2093. error
  2094. } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);
  2095. let currentLocation = state.location;
  2096. let nextLocation = createLocation(state.location, path, opts && opts.state);
  2097. // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
  2098. // URL from window.location, so we need to encode it here so the behavior
  2099. // remains the same as POP and non-data-router usages. new URL() does all
  2100. // the same encoding we'd get from a history.pushState/window.location read
  2101. // without having to touch history
  2102. nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
  2103. let userReplace = opts && opts.replace != null ? opts.replace : undefined;
  2104. let historyAction = Action.Push;
  2105. if (userReplace === true) {
  2106. historyAction = Action.Replace;
  2107. } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
  2108. // By default on submissions to the current location we REPLACE so that
  2109. // users don't have to double-click the back button to get to the prior
  2110. // location. If the user redirects to a different location from the
  2111. // action/loader this will be ignored and the redirect will be a PUSH
  2112. historyAction = Action.Replace;
  2113. }
  2114. let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
  2115. let flushSync = (opts && opts.flushSync) === true;
  2116. let blockerKey = shouldBlockNavigation({
  2117. currentLocation,
  2118. nextLocation,
  2119. historyAction
  2120. });
  2121. if (blockerKey) {
  2122. // Put the blocker into a blocked state
  2123. updateBlocker(blockerKey, {
  2124. state: "blocked",
  2125. location: nextLocation,
  2126. proceed() {
  2127. updateBlocker(blockerKey, {
  2128. state: "proceeding",
  2129. proceed: undefined,
  2130. reset: undefined,
  2131. location: nextLocation
  2132. });
  2133. // Send the same navigation through
  2134. navigate(to, opts);
  2135. },
  2136. reset() {
  2137. let blockers = new Map(state.blockers);
  2138. blockers.set(blockerKey, IDLE_BLOCKER);
  2139. updateState({
  2140. blockers
  2141. });
  2142. }
  2143. });
  2144. return;
  2145. }
  2146. return await startNavigation(historyAction, nextLocation, {
  2147. submission,
  2148. // Send through the formData serialization error if we have one so we can
  2149. // render at the right error boundary after we match routes
  2150. pendingError: error,
  2151. preventScrollReset,
  2152. replace: opts && opts.replace,
  2153. enableViewTransition: opts && opts.viewTransition,
  2154. flushSync
  2155. });
  2156. }
  2157. // Revalidate all current loaders. If a navigation is in progress or if this
  2158. // is interrupted by a navigation, allow this to "succeed" by calling all
  2159. // loaders during the next loader round
  2160. function revalidate() {
  2161. interruptActiveLoads();
  2162. updateState({
  2163. revalidation: "loading"
  2164. });
  2165. // If we're currently submitting an action, we don't need to start a new
  2166. // navigation, we'll just let the follow up loader execution call all loaders
  2167. if (state.navigation.state === "submitting") {
  2168. return;
  2169. }
  2170. // If we're currently in an idle state, start a new navigation for the current
  2171. // action/location and mark it as uninterrupted, which will skip the history
  2172. // update in completeNavigation
  2173. if (state.navigation.state === "idle") {
  2174. startNavigation(state.historyAction, state.location, {
  2175. startUninterruptedRevalidation: true
  2176. });
  2177. return;
  2178. }
  2179. // Otherwise, if we're currently in a loading state, just start a new
  2180. // navigation to the navigation.location but do not trigger an uninterrupted
  2181. // revalidation so that history correctly updates once the navigation completes
  2182. startNavigation(pendingAction || state.historyAction, state.navigation.location, {
  2183. overrideNavigation: state.navigation,
  2184. // Proxy through any rending view transition
  2185. enableViewTransition: pendingViewTransitionEnabled === true
  2186. });
  2187. }
  2188. // Start a navigation to the given action/location. Can optionally provide a
  2189. // overrideNavigation which will override the normalLoad in the case of a redirect
  2190. // navigation
  2191. async function startNavigation(historyAction, location, opts) {
  2192. // Abort any in-progress navigations and start a new one. Unset any ongoing
  2193. // uninterrupted revalidations unless told otherwise, since we want this
  2194. // new navigation to update history normally
  2195. pendingNavigationController && pendingNavigationController.abort();
  2196. pendingNavigationController = null;
  2197. pendingAction = historyAction;
  2198. isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
  2199. // Save the current scroll position every time we start a new navigation,
  2200. // and track whether we should reset scroll on completion
  2201. saveScrollPosition(state.location, state.matches);
  2202. pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
  2203. pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
  2204. let routesToUse = inFlightDataRoutes || dataRoutes;
  2205. let loadingNavigation = opts && opts.overrideNavigation;
  2206. let matches = opts != null && opts.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ?
  2207. // `matchRoutes()` has already been called if we're in here via `router.initialize()`
  2208. state.matches : matchRoutes(routesToUse, location, basename);
  2209. let flushSync = (opts && opts.flushSync) === true;
  2210. // Short circuit if it's only a hash change and not a revalidation or
  2211. // mutation submission.
  2212. //
  2213. // Ignore on initial page loads because since the initial hydration will always
  2214. // be "same hash". For example, on /page#hash and submit a <Form method="post">
  2215. // which will default to a navigation to /page
  2216. if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
  2217. completeNavigation(location, {
  2218. matches
  2219. }, {
  2220. flushSync
  2221. });
  2222. return;
  2223. }
  2224. let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);
  2225. if (fogOfWar.active && fogOfWar.matches) {
  2226. matches = fogOfWar.matches;
  2227. }
  2228. // Short circuit with a 404 on the root error boundary if we match nothing
  2229. if (!matches) {
  2230. let {
  2231. error,
  2232. notFoundMatches,
  2233. route
  2234. } = handleNavigational404(location.pathname);
  2235. completeNavigation(location, {
  2236. matches: notFoundMatches,
  2237. loaderData: {},
  2238. errors: {
  2239. [route.id]: error
  2240. }
  2241. }, {
  2242. flushSync
  2243. });
  2244. return;
  2245. }
  2246. // Create a controller/Request for this navigation
  2247. pendingNavigationController = new AbortController();
  2248. let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
  2249. let pendingActionResult;
  2250. if (opts && opts.pendingError) {
  2251. // If we have a pendingError, it means the user attempted a GET submission
  2252. // with binary FormData so assign here and skip to handleLoaders. That
  2253. // way we handle calling loaders above the boundary etc. It's not really
  2254. // different from an actionError in that sense.
  2255. pendingActionResult = [findNearestBoundary(matches).route.id, {
  2256. type: ResultType.error,
  2257. error: opts.pendingError
  2258. }];
  2259. } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
  2260. // Call action if we received an action submission
  2261. let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, {
  2262. replace: opts.replace,
  2263. flushSync
  2264. });
  2265. if (actionResult.shortCircuited) {
  2266. return;
  2267. }
  2268. // If we received a 404 from handleAction, it's because we couldn't lazily
  2269. // discover the destination route so we don't want to call loaders
  2270. if (actionResult.pendingActionResult) {
  2271. let [routeId, result] = actionResult.pendingActionResult;
  2272. if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
  2273. pendingNavigationController = null;
  2274. completeNavigation(location, {
  2275. matches: actionResult.matches,
  2276. loaderData: {},
  2277. errors: {
  2278. [routeId]: result.error
  2279. }
  2280. });
  2281. return;
  2282. }
  2283. }
  2284. matches = actionResult.matches || matches;
  2285. pendingActionResult = actionResult.pendingActionResult;
  2286. loadingNavigation = getLoadingNavigation(location, opts.submission);
  2287. flushSync = false;
  2288. // No need to do fog of war matching again on loader execution
  2289. fogOfWar.active = false;
  2290. // Create a GET request for the loaders
  2291. request = createClientSideRequest(init.history, request.url, request.signal);
  2292. }
  2293. // Call loaders
  2294. let {
  2295. shortCircuited,
  2296. matches: updatedMatches,
  2297. loaderData,
  2298. errors
  2299. } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);
  2300. if (shortCircuited) {
  2301. return;
  2302. }
  2303. // Clean up now that the action/loaders have completed. Don't clean up if
  2304. // we short circuited because pendingNavigationController will have already
  2305. // been assigned to a new controller for the next navigation
  2306. pendingNavigationController = null;
  2307. completeNavigation(location, _extends({
  2308. matches: updatedMatches || matches
  2309. }, getActionDataForCommit(pendingActionResult), {
  2310. loaderData,
  2311. errors
  2312. }));
  2313. }
  2314. // Call the action matched by the leaf route for this navigation and handle
  2315. // redirects/errors
  2316. async function handleAction(request, location, submission, matches, isFogOfWar, opts) {
  2317. if (opts === void 0) {
  2318. opts = {};
  2319. }
  2320. interruptActiveLoads();
  2321. // Put us in a submitting state
  2322. let navigation = getSubmittingNavigation(location, submission);
  2323. updateState({
  2324. navigation
  2325. }, {
  2326. flushSync: opts.flushSync === true
  2327. });
  2328. if (isFogOfWar) {
  2329. let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
  2330. if (discoverResult.type === "aborted") {
  2331. return {
  2332. shortCircuited: true
  2333. };
  2334. } else if (discoverResult.type === "error") {
  2335. let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
  2336. return {
  2337. matches: discoverResult.partialMatches,
  2338. pendingActionResult: [boundaryId, {
  2339. type: ResultType.error,
  2340. error: discoverResult.error
  2341. }]
  2342. };
  2343. } else if (!discoverResult.matches) {
  2344. let {
  2345. notFoundMatches,
  2346. error,
  2347. route
  2348. } = handleNavigational404(location.pathname);
  2349. return {
  2350. matches: notFoundMatches,
  2351. pendingActionResult: [route.id, {
  2352. type: ResultType.error,
  2353. error
  2354. }]
  2355. };
  2356. } else {
  2357. matches = discoverResult.matches;
  2358. }
  2359. }
  2360. // Call our action and get the result
  2361. let result;
  2362. let actionMatch = getTargetMatch(matches, location);
  2363. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  2364. result = {
  2365. type: ResultType.error,
  2366. error: getInternalRouterError(405, {
  2367. method: request.method,
  2368. pathname: location.pathname,
  2369. routeId: actionMatch.route.id
  2370. })
  2371. };
  2372. } else {
  2373. let results = await callDataStrategy("action", state, request, [actionMatch], matches, null);
  2374. result = results[actionMatch.route.id];
  2375. if (request.signal.aborted) {
  2376. return {
  2377. shortCircuited: true
  2378. };
  2379. }
  2380. }
  2381. if (isRedirectResult(result)) {
  2382. let replace;
  2383. if (opts && opts.replace != null) {
  2384. replace = opts.replace;
  2385. } else {
  2386. // If the user didn't explicity indicate replace behavior, replace if
  2387. // we redirected to the exact same location we're currently at to avoid
  2388. // double back-buttons
  2389. let location = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename, init.history);
  2390. replace = location === state.location.pathname + state.location.search;
  2391. }
  2392. await startRedirectNavigation(request, result, true, {
  2393. submission,
  2394. replace
  2395. });
  2396. return {
  2397. shortCircuited: true
  2398. };
  2399. }
  2400. if (isDeferredResult(result)) {
  2401. throw getInternalRouterError(400, {
  2402. type: "defer-action"
  2403. });
  2404. }
  2405. if (isErrorResult(result)) {
  2406. // Store off the pending error - we use it to determine which loaders
  2407. // to call and will commit it when we complete the navigation
  2408. let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
  2409. // By default, all submissions to the current location are REPLACE
  2410. // navigations, but if the action threw an error that'll be rendered in
  2411. // an errorElement, we fall back to PUSH so that the user can use the
  2412. // back button to get back to the pre-submission form location to try
  2413. // again
  2414. if ((opts && opts.replace) !== true) {
  2415. pendingAction = Action.Push;
  2416. }
  2417. return {
  2418. matches,
  2419. pendingActionResult: [boundaryMatch.route.id, result]
  2420. };
  2421. }
  2422. return {
  2423. matches,
  2424. pendingActionResult: [actionMatch.route.id, result]
  2425. };
  2426. }
  2427. // Call all applicable loaders for the given matches, handling redirects,
  2428. // errors, etc.
  2429. async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) {
  2430. // Figure out the right navigation we want to use for data loading
  2431. let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);
  2432. // If this was a redirect from an action we don't have a "submission" but
  2433. // we have it on the loading navigation so use that if available
  2434. let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
  2435. // If this is an uninterrupted revalidation, we remain in our current idle
  2436. // state. If not, we need to switch to our loading state and load data,
  2437. // preserving any new action data or existing action data (in the case of
  2438. // a revalidation interrupting an actionReload)
  2439. // If we have partialHydration enabled, then don't update the state for the
  2440. // initial data load since it's not a "navigation"
  2441. let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration);
  2442. // When fog of war is enabled, we enter our `loading` state earlier so we
  2443. // can discover new routes during the `loading` state. We skip this if
  2444. // we've already run actions since we would have done our matching already.
  2445. // If the children() function threw then, we want to proceed with the
  2446. // partial matches it discovered.
  2447. if (isFogOfWar) {
  2448. if (shouldUpdateNavigationState) {
  2449. let actionData = getUpdatedActionData(pendingActionResult);
  2450. updateState(_extends({
  2451. navigation: loadingNavigation
  2452. }, actionData !== undefined ? {
  2453. actionData
  2454. } : {}), {
  2455. flushSync
  2456. });
  2457. }
  2458. let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
  2459. if (discoverResult.type === "aborted") {
  2460. return {
  2461. shortCircuited: true
  2462. };
  2463. } else if (discoverResult.type === "error") {
  2464. let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
  2465. return {
  2466. matches: discoverResult.partialMatches,
  2467. loaderData: {},
  2468. errors: {
  2469. [boundaryId]: discoverResult.error
  2470. }
  2471. };
  2472. } else if (!discoverResult.matches) {
  2473. let {
  2474. error,
  2475. notFoundMatches,
  2476. route
  2477. } = handleNavigational404(location.pathname);
  2478. return {
  2479. matches: notFoundMatches,
  2480. loaderData: {},
  2481. errors: {
  2482. [route.id]: error
  2483. }
  2484. };
  2485. } else {
  2486. matches = discoverResult.matches;
  2487. }
  2488. }
  2489. let routesToUse = inFlightDataRoutes || dataRoutes;
  2490. let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult);
  2491. // Cancel pending deferreds for no-longer-matched routes or routes we're
  2492. // about to reload. Note that if this is an action reload we would have
  2493. // already cancelled all pending deferreds so this would be a no-op
  2494. cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));
  2495. pendingNavigationLoadId = ++incrementingLoadId;
  2496. // Short circuit if we have no loaders to run
  2497. if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
  2498. let updatedFetchers = markFetchRedirectsDone();
  2499. completeNavigation(location, _extends({
  2500. matches,
  2501. loaderData: {},
  2502. // Commit pending error if we're short circuiting
  2503. errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
  2504. [pendingActionResult[0]]: pendingActionResult[1].error
  2505. } : null
  2506. }, getActionDataForCommit(pendingActionResult), updatedFetchers ? {
  2507. fetchers: new Map(state.fetchers)
  2508. } : {}), {
  2509. flushSync
  2510. });
  2511. return {
  2512. shortCircuited: true
  2513. };
  2514. }
  2515. if (shouldUpdateNavigationState) {
  2516. let updates = {};
  2517. if (!isFogOfWar) {
  2518. // Only update navigation/actionNData if we didn't already do it above
  2519. updates.navigation = loadingNavigation;
  2520. let actionData = getUpdatedActionData(pendingActionResult);
  2521. if (actionData !== undefined) {
  2522. updates.actionData = actionData;
  2523. }
  2524. }
  2525. if (revalidatingFetchers.length > 0) {
  2526. updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
  2527. }
  2528. updateState(updates, {
  2529. flushSync
  2530. });
  2531. }
  2532. revalidatingFetchers.forEach(rf => {
  2533. abortFetcher(rf.key);
  2534. if (rf.controller) {
  2535. // Fetchers use an independent AbortController so that aborting a fetcher
  2536. // (via deleteFetcher) does not abort the triggering navigation that
  2537. // triggered the revalidation
  2538. fetchControllers.set(rf.key, rf.controller);
  2539. }
  2540. });
  2541. // Proxy navigation abort through to revalidation fetchers
  2542. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));
  2543. if (pendingNavigationController) {
  2544. pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations);
  2545. }
  2546. let {
  2547. loaderResults,
  2548. fetcherResults
  2549. } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, request);
  2550. if (request.signal.aborted) {
  2551. return {
  2552. shortCircuited: true
  2553. };
  2554. }
  2555. // Clean up _after_ loaders have completed. Don't clean up if we short
  2556. // circuited because fetchControllers would have been aborted and
  2557. // reassigned to new controllers for the next navigation
  2558. if (pendingNavigationController) {
  2559. pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
  2560. }
  2561. revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));
  2562. // If any loaders returned a redirect Response, start a new REPLACE navigation
  2563. let redirect = findRedirect(loaderResults);
  2564. if (redirect) {
  2565. await startRedirectNavigation(request, redirect.result, true, {
  2566. replace
  2567. });
  2568. return {
  2569. shortCircuited: true
  2570. };
  2571. }
  2572. redirect = findRedirect(fetcherResults);
  2573. if (redirect) {
  2574. // If this redirect came from a fetcher make sure we mark it in
  2575. // fetchRedirectIds so it doesn't get revalidated on the next set of
  2576. // loader executions
  2577. fetchRedirectIds.add(redirect.key);
  2578. await startRedirectNavigation(request, redirect.result, true, {
  2579. replace
  2580. });
  2581. return {
  2582. shortCircuited: true
  2583. };
  2584. }
  2585. // Process and commit output from loaders
  2586. let {
  2587. loaderData,
  2588. errors
  2589. } = processLoaderData(state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);
  2590. // Wire up subscribers to update loaderData as promises settle
  2591. activeDeferreds.forEach((deferredData, routeId) => {
  2592. deferredData.subscribe(aborted => {
  2593. // Note: No need to updateState here since the TrackedPromise on
  2594. // loaderData is stable across resolve/reject
  2595. // Remove this instance if we were aborted or if promises have settled
  2596. if (aborted || deferredData.done) {
  2597. activeDeferreds.delete(routeId);
  2598. }
  2599. });
  2600. });
  2601. // Preserve SSR errors during partial hydration
  2602. if (future.v7_partialHydration && initialHydration && state.errors) {
  2603. errors = _extends({}, state.errors, errors);
  2604. }
  2605. let updatedFetchers = markFetchRedirectsDone();
  2606. let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
  2607. let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;
  2608. return _extends({
  2609. matches,
  2610. loaderData,
  2611. errors
  2612. }, shouldUpdateFetchers ? {
  2613. fetchers: new Map(state.fetchers)
  2614. } : {});
  2615. }
  2616. function getUpdatedActionData(pendingActionResult) {
  2617. if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {
  2618. // This is cast to `any` currently because `RouteData`uses any and it
  2619. // would be a breaking change to use any.
  2620. // TODO: v7 - change `RouteData` to use `unknown` instead of `any`
  2621. return {
  2622. [pendingActionResult[0]]: pendingActionResult[1].data
  2623. };
  2624. } else if (state.actionData) {
  2625. if (Object.keys(state.actionData).length === 0) {
  2626. return null;
  2627. } else {
  2628. return state.actionData;
  2629. }
  2630. }
  2631. }
  2632. function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
  2633. revalidatingFetchers.forEach(rf => {
  2634. let fetcher = state.fetchers.get(rf.key);
  2635. let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);
  2636. state.fetchers.set(rf.key, revalidatingFetcher);
  2637. });
  2638. return new Map(state.fetchers);
  2639. }
  2640. // Trigger a fetcher load/submit for the given fetcher key
  2641. function fetch(key, routeId, href, opts) {
  2642. if (isServer) {
  2643. throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback.");
  2644. }
  2645. abortFetcher(key);
  2646. let flushSync = (opts && opts.flushSync) === true;
  2647. let routesToUse = inFlightDataRoutes || dataRoutes;
  2648. let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative);
  2649. let matches = matchRoutes(routesToUse, normalizedPath, basename);
  2650. let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);
  2651. if (fogOfWar.active && fogOfWar.matches) {
  2652. matches = fogOfWar.matches;
  2653. }
  2654. if (!matches) {
  2655. setFetcherError(key, routeId, getInternalRouterError(404, {
  2656. pathname: normalizedPath
  2657. }), {
  2658. flushSync
  2659. });
  2660. return;
  2661. }
  2662. let {
  2663. path,
  2664. submission,
  2665. error
  2666. } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);
  2667. if (error) {
  2668. setFetcherError(key, routeId, error, {
  2669. flushSync
  2670. });
  2671. return;
  2672. }
  2673. let match = getTargetMatch(matches, path);
  2674. let preventScrollReset = (opts && opts.preventScrollReset) === true;
  2675. if (submission && isMutationMethod(submission.formMethod)) {
  2676. handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
  2677. return;
  2678. }
  2679. // Store off the match so we can call it's shouldRevalidate on subsequent
  2680. // revalidations
  2681. fetchLoadMatches.set(key, {
  2682. routeId,
  2683. path
  2684. });
  2685. handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, preventScrollReset, submission);
  2686. }
  2687. // Call the action for the matched fetcher.submit(), and then handle redirects,
  2688. // errors, and revalidation
  2689. async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, preventScrollReset, submission) {
  2690. interruptActiveLoads();
  2691. fetchLoadMatches.delete(key);
  2692. function detectAndHandle405Error(m) {
  2693. if (!m.route.action && !m.route.lazy) {
  2694. let error = getInternalRouterError(405, {
  2695. method: submission.formMethod,
  2696. pathname: path,
  2697. routeId: routeId
  2698. });
  2699. setFetcherError(key, routeId, error, {
  2700. flushSync
  2701. });
  2702. return true;
  2703. }
  2704. return false;
  2705. }
  2706. if (!isFogOfWar && detectAndHandle405Error(match)) {
  2707. return;
  2708. }
  2709. // Put this fetcher into it's submitting state
  2710. let existingFetcher = state.fetchers.get(key);
  2711. updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {
  2712. flushSync
  2713. });
  2714. let abortController = new AbortController();
  2715. let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
  2716. if (isFogOfWar) {
  2717. let discoverResult = await discoverRoutes(requestMatches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
  2718. if (discoverResult.type === "aborted") {
  2719. return;
  2720. } else if (discoverResult.type === "error") {
  2721. setFetcherError(key, routeId, discoverResult.error, {
  2722. flushSync
  2723. });
  2724. return;
  2725. } else if (!discoverResult.matches) {
  2726. setFetcherError(key, routeId, getInternalRouterError(404, {
  2727. pathname: path
  2728. }), {
  2729. flushSync
  2730. });
  2731. return;
  2732. } else {
  2733. requestMatches = discoverResult.matches;
  2734. match = getTargetMatch(requestMatches, path);
  2735. if (detectAndHandle405Error(match)) {
  2736. return;
  2737. }
  2738. }
  2739. }
  2740. // Call the action for the fetcher
  2741. fetchControllers.set(key, abortController);
  2742. let originatingLoadId = incrementingLoadId;
  2743. let actionResults = await callDataStrategy("action", state, fetchRequest, [match], requestMatches, key);
  2744. let actionResult = actionResults[match.route.id];
  2745. if (fetchRequest.signal.aborted) {
  2746. // We can delete this so long as we weren't aborted by our own fetcher
  2747. // re-submit which would have put _new_ controller is in fetchControllers
  2748. if (fetchControllers.get(key) === abortController) {
  2749. fetchControllers.delete(key);
  2750. }
  2751. return;
  2752. }
  2753. // When using v7_fetcherPersist, we don't want errors bubbling up to the UI
  2754. // or redirects processed for unmounted fetchers so we just revert them to
  2755. // idle
  2756. if (future.v7_fetcherPersist && deletedFetchers.has(key)) {
  2757. if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {
  2758. updateFetcherState(key, getDoneFetcher(undefined));
  2759. return;
  2760. }
  2761. // Let SuccessResult's fall through for revalidation
  2762. } else {
  2763. if (isRedirectResult(actionResult)) {
  2764. fetchControllers.delete(key);
  2765. if (pendingNavigationLoadId > originatingLoadId) {
  2766. // A new navigation was kicked off after our action started, so that
  2767. // should take precedence over this redirect navigation. We already
  2768. // set isRevalidationRequired so all loaders for the new route should
  2769. // fire unless opted out via shouldRevalidate
  2770. updateFetcherState(key, getDoneFetcher(undefined));
  2771. return;
  2772. } else {
  2773. fetchRedirectIds.add(key);
  2774. updateFetcherState(key, getLoadingFetcher(submission));
  2775. return startRedirectNavigation(fetchRequest, actionResult, false, {
  2776. fetcherSubmission: submission,
  2777. preventScrollReset
  2778. });
  2779. }
  2780. }
  2781. // Process any non-redirect errors thrown
  2782. if (isErrorResult(actionResult)) {
  2783. setFetcherError(key, routeId, actionResult.error);
  2784. return;
  2785. }
  2786. }
  2787. if (isDeferredResult(actionResult)) {
  2788. throw getInternalRouterError(400, {
  2789. type: "defer-action"
  2790. });
  2791. }
  2792. // Start the data load for current matches, or the next location if we're
  2793. // in the middle of a navigation
  2794. let nextLocation = state.navigation.location || state.location;
  2795. let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);
  2796. let routesToUse = inFlightDataRoutes || dataRoutes;
  2797. let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;
  2798. invariant(matches, "Didn't find any matches after fetcher action");
  2799. let loadId = ++incrementingLoadId;
  2800. fetchReloadIds.set(key, loadId);
  2801. let loadFetcher = getLoadingFetcher(submission, actionResult.data);
  2802. state.fetchers.set(key, loadFetcher);
  2803. let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]);
  2804. // Put all revalidating fetchers into the loading state, except for the
  2805. // current fetcher which we want to keep in it's current loading state which
  2806. // contains it's action submission info + action data
  2807. revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {
  2808. let staleKey = rf.key;
  2809. let existingFetcher = state.fetchers.get(staleKey);
  2810. let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);
  2811. state.fetchers.set(staleKey, revalidatingFetcher);
  2812. abortFetcher(staleKey);
  2813. if (rf.controller) {
  2814. fetchControllers.set(staleKey, rf.controller);
  2815. }
  2816. });
  2817. updateState({
  2818. fetchers: new Map(state.fetchers)
  2819. });
  2820. let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));
  2821. abortController.signal.addEventListener("abort", abortPendingFetchRevalidations);
  2822. let {
  2823. loaderResults,
  2824. fetcherResults
  2825. } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
  2826. if (abortController.signal.aborted) {
  2827. return;
  2828. }
  2829. abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
  2830. fetchReloadIds.delete(key);
  2831. fetchControllers.delete(key);
  2832. revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));
  2833. let redirect = findRedirect(loaderResults);
  2834. if (redirect) {
  2835. return startRedirectNavigation(revalidationRequest, redirect.result, false, {
  2836. preventScrollReset
  2837. });
  2838. }
  2839. redirect = findRedirect(fetcherResults);
  2840. if (redirect) {
  2841. // If this redirect came from a fetcher make sure we mark it in
  2842. // fetchRedirectIds so it doesn't get revalidated on the next set of
  2843. // loader executions
  2844. fetchRedirectIds.add(redirect.key);
  2845. return startRedirectNavigation(revalidationRequest, redirect.result, false, {
  2846. preventScrollReset
  2847. });
  2848. }
  2849. // Process and commit output from loaders
  2850. let {
  2851. loaderData,
  2852. errors
  2853. } = processLoaderData(state, matches, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);
  2854. // Since we let revalidations complete even if the submitting fetcher was
  2855. // deleted, only put it back to idle if it hasn't been deleted
  2856. if (state.fetchers.has(key)) {
  2857. let doneFetcher = getDoneFetcher(actionResult.data);
  2858. state.fetchers.set(key, doneFetcher);
  2859. }
  2860. abortStaleFetchLoads(loadId);
  2861. // If we are currently in a navigation loading state and this fetcher is
  2862. // more recent than the navigation, we want the newer data so abort the
  2863. // navigation and complete it with the fetcher data
  2864. if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
  2865. invariant(pendingAction, "Expected pending action");
  2866. pendingNavigationController && pendingNavigationController.abort();
  2867. completeNavigation(state.navigation.location, {
  2868. matches,
  2869. loaderData,
  2870. errors,
  2871. fetchers: new Map(state.fetchers)
  2872. });
  2873. } else {
  2874. // otherwise just update with the fetcher data, preserving any existing
  2875. // loaderData for loaders that did not need to reload. We have to
  2876. // manually merge here since we aren't going through completeNavigation
  2877. updateState({
  2878. errors,
  2879. loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),
  2880. fetchers: new Map(state.fetchers)
  2881. });
  2882. isRevalidationRequired = false;
  2883. }
  2884. }
  2885. // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
  2886. async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, preventScrollReset, submission) {
  2887. let existingFetcher = state.fetchers.get(key);
  2888. updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {
  2889. flushSync
  2890. });
  2891. let abortController = new AbortController();
  2892. let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
  2893. if (isFogOfWar) {
  2894. let discoverResult = await discoverRoutes(matches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
  2895. if (discoverResult.type === "aborted") {
  2896. return;
  2897. } else if (discoverResult.type === "error") {
  2898. setFetcherError(key, routeId, discoverResult.error, {
  2899. flushSync
  2900. });
  2901. return;
  2902. } else if (!discoverResult.matches) {
  2903. setFetcherError(key, routeId, getInternalRouterError(404, {
  2904. pathname: path
  2905. }), {
  2906. flushSync
  2907. });
  2908. return;
  2909. } else {
  2910. matches = discoverResult.matches;
  2911. match = getTargetMatch(matches, path);
  2912. }
  2913. }
  2914. // Call the loader for this fetcher route match
  2915. fetchControllers.set(key, abortController);
  2916. let originatingLoadId = incrementingLoadId;
  2917. let results = await callDataStrategy("loader", state, fetchRequest, [match], matches, key);
  2918. let result = results[match.route.id];
  2919. // Deferred isn't supported for fetcher loads, await everything and treat it
  2920. // as a normal load. resolveDeferredData will return undefined if this
  2921. // fetcher gets aborted, so we just leave result untouched and short circuit
  2922. // below if that happens
  2923. if (isDeferredResult(result)) {
  2924. result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
  2925. }
  2926. // We can delete this so long as we weren't aborted by our our own fetcher
  2927. // re-load which would have put _new_ controller is in fetchControllers
  2928. if (fetchControllers.get(key) === abortController) {
  2929. fetchControllers.delete(key);
  2930. }
  2931. if (fetchRequest.signal.aborted) {
  2932. return;
  2933. }
  2934. // We don't want errors bubbling up or redirects followed for unmounted
  2935. // fetchers, so short circuit here if it was removed from the UI
  2936. if (deletedFetchers.has(key)) {
  2937. updateFetcherState(key, getDoneFetcher(undefined));
  2938. return;
  2939. }
  2940. // If the loader threw a redirect Response, start a new REPLACE navigation
  2941. if (isRedirectResult(result)) {
  2942. if (pendingNavigationLoadId > originatingLoadId) {
  2943. // A new navigation was kicked off after our loader started, so that
  2944. // should take precedence over this redirect navigation
  2945. updateFetcherState(key, getDoneFetcher(undefined));
  2946. return;
  2947. } else {
  2948. fetchRedirectIds.add(key);
  2949. await startRedirectNavigation(fetchRequest, result, false, {
  2950. preventScrollReset
  2951. });
  2952. return;
  2953. }
  2954. }
  2955. // Process any non-redirect errors thrown
  2956. if (isErrorResult(result)) {
  2957. setFetcherError(key, routeId, result.error);
  2958. return;
  2959. }
  2960. invariant(!isDeferredResult(result), "Unhandled fetcher deferred data");
  2961. // Put the fetcher back into an idle state
  2962. updateFetcherState(key, getDoneFetcher(result.data));
  2963. }
  2964. /**
  2965. * Utility function to handle redirects returned from an action or loader.
  2966. * Normally, a redirect "replaces" the navigation that triggered it. So, for
  2967. * example:
  2968. *
  2969. * - user is on /a
  2970. * - user clicks a link to /b
  2971. * - loader for /b redirects to /c
  2972. *
  2973. * In a non-JS app the browser would track the in-flight navigation to /b and
  2974. * then replace it with /c when it encountered the redirect response. In
  2975. * the end it would only ever update the URL bar with /c.
  2976. *
  2977. * In client-side routing using pushState/replaceState, we aim to emulate
  2978. * this behavior and we also do not update history until the end of the
  2979. * navigation (including processed redirects). This means that we never
  2980. * actually touch history until we've processed redirects, so we just use
  2981. * the history action from the original navigation (PUSH or REPLACE).
  2982. */
  2983. async function startRedirectNavigation(request, redirect, isNavigation, _temp2) {
  2984. let {
  2985. submission,
  2986. fetcherSubmission,
  2987. preventScrollReset,
  2988. replace
  2989. } = _temp2 === void 0 ? {} : _temp2;
  2990. if (redirect.response.headers.has("X-Remix-Revalidate")) {
  2991. isRevalidationRequired = true;
  2992. }
  2993. let location = redirect.response.headers.get("Location");
  2994. invariant(location, "Expected a Location header on the redirect Response");
  2995. location = normalizeRedirectLocation(location, new URL(request.url), basename, init.history);
  2996. let redirectLocation = createLocation(state.location, location, {
  2997. _isRedirect: true
  2998. });
  2999. if (isBrowser) {
  3000. let isDocumentReload = false;
  3001. if (redirect.response.headers.has("X-Remix-Reload-Document")) {
  3002. // Hard reload if the response contained X-Remix-Reload-Document
  3003. isDocumentReload = true;
  3004. } else if (ABSOLUTE_URL_REGEX.test(location)) {
  3005. const url = init.history.createURL(location);
  3006. isDocumentReload =
  3007. // Hard reload if it's an absolute URL to a new origin
  3008. url.origin !== routerWindow.location.origin ||
  3009. // Hard reload if it's an absolute URL that does not match our basename
  3010. stripBasename(url.pathname, basename) == null;
  3011. }
  3012. if (isDocumentReload) {
  3013. if (replace) {
  3014. routerWindow.location.replace(location);
  3015. } else {
  3016. routerWindow.location.assign(location);
  3017. }
  3018. return;
  3019. }
  3020. }
  3021. // There's no need to abort on redirects, since we don't detect the
  3022. // redirect until the action/loaders have settled
  3023. pendingNavigationController = null;
  3024. let redirectHistoryAction = replace === true || redirect.response.headers.has("X-Remix-Replace") ? Action.Replace : Action.Push;
  3025. // Use the incoming submission if provided, fallback on the active one in
  3026. // state.navigation
  3027. let {
  3028. formMethod,
  3029. formAction,
  3030. formEncType
  3031. } = state.navigation;
  3032. if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {
  3033. submission = getSubmissionFromNavigation(state.navigation);
  3034. }
  3035. // If this was a 307/308 submission we want to preserve the HTTP method and
  3036. // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the
  3037. // redirected location
  3038. let activeSubmission = submission || fetcherSubmission;
  3039. if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {
  3040. await startNavigation(redirectHistoryAction, redirectLocation, {
  3041. submission: _extends({}, activeSubmission, {
  3042. formAction: location
  3043. }),
  3044. // Preserve these flags across redirects
  3045. preventScrollReset: preventScrollReset || pendingPreventScrollReset,
  3046. enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
  3047. });
  3048. } else {
  3049. // If we have a navigation submission, we will preserve it through the
  3050. // redirect navigation
  3051. let overrideNavigation = getLoadingNavigation(redirectLocation, submission);
  3052. await startNavigation(redirectHistoryAction, redirectLocation, {
  3053. overrideNavigation,
  3054. // Send fetcher submissions through for shouldRevalidate
  3055. fetcherSubmission,
  3056. // Preserve these flags across redirects
  3057. preventScrollReset: preventScrollReset || pendingPreventScrollReset,
  3058. enableViewTransition: isNavigation ? pendingViewTransitionEnabled : undefined
  3059. });
  3060. }
  3061. }
  3062. // Utility wrapper for calling dataStrategy client-side without having to
  3063. // pass around the manifest, mapRouteProperties, etc.
  3064. async function callDataStrategy(type, state, request, matchesToLoad, matches, fetcherKey) {
  3065. let results;
  3066. let dataResults = {};
  3067. try {
  3068. results = await callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties);
  3069. } catch (e) {
  3070. // If the outer dataStrategy method throws, just return the error for all
  3071. // matches - and it'll naturally bubble to the root
  3072. matchesToLoad.forEach(m => {
  3073. dataResults[m.route.id] = {
  3074. type: ResultType.error,
  3075. error: e
  3076. };
  3077. });
  3078. return dataResults;
  3079. }
  3080. for (let [routeId, result] of Object.entries(results)) {
  3081. if (isRedirectDataStrategyResultResult(result)) {
  3082. let response = result.result;
  3083. dataResults[routeId] = {
  3084. type: ResultType.redirect,
  3085. response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, future.v7_relativeSplatPath)
  3086. };
  3087. } else {
  3088. dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
  3089. }
  3090. }
  3091. return dataResults;
  3092. }
  3093. async function callLoadersAndMaybeResolveData(state, matches, matchesToLoad, fetchersToLoad, request) {
  3094. let currentMatches = state.matches;
  3095. // Kick off loaders and fetchers in parallel
  3096. let loaderResultsPromise = callDataStrategy("loader", state, request, matchesToLoad, matches, null);
  3097. let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async f => {
  3098. if (f.matches && f.match && f.controller) {
  3099. let results = await callDataStrategy("loader", state, createClientSideRequest(init.history, f.path, f.controller.signal), [f.match], f.matches, f.key);
  3100. let result = results[f.match.route.id];
  3101. // Fetcher results are keyed by fetcher key from here on out, not routeId
  3102. return {
  3103. [f.key]: result
  3104. };
  3105. } else {
  3106. return Promise.resolve({
  3107. [f.key]: {
  3108. type: ResultType.error,
  3109. error: getInternalRouterError(404, {
  3110. pathname: f.path
  3111. })
  3112. }
  3113. });
  3114. }
  3115. }));
  3116. let loaderResults = await loaderResultsPromise;
  3117. let fetcherResults = (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {});
  3118. await Promise.all([resolveNavigationDeferredResults(matches, loaderResults, request.signal, currentMatches, state.loaderData), resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad)]);
  3119. return {
  3120. loaderResults,
  3121. fetcherResults
  3122. };
  3123. }
  3124. function interruptActiveLoads() {
  3125. // Every interruption triggers a revalidation
  3126. isRevalidationRequired = true;
  3127. // Cancel pending route-level deferreds and mark cancelled routes for
  3128. // revalidation
  3129. cancelledDeferredRoutes.push(...cancelActiveDeferreds());
  3130. // Abort in-flight fetcher loads
  3131. fetchLoadMatches.forEach((_, key) => {
  3132. if (fetchControllers.has(key)) {
  3133. cancelledFetcherLoads.add(key);
  3134. }
  3135. abortFetcher(key);
  3136. });
  3137. }
  3138. function updateFetcherState(key, fetcher, opts) {
  3139. if (opts === void 0) {
  3140. opts = {};
  3141. }
  3142. state.fetchers.set(key, fetcher);
  3143. updateState({
  3144. fetchers: new Map(state.fetchers)
  3145. }, {
  3146. flushSync: (opts && opts.flushSync) === true
  3147. });
  3148. }
  3149. function setFetcherError(key, routeId, error, opts) {
  3150. if (opts === void 0) {
  3151. opts = {};
  3152. }
  3153. let boundaryMatch = findNearestBoundary(state.matches, routeId);
  3154. deleteFetcher(key);
  3155. updateState({
  3156. errors: {
  3157. [boundaryMatch.route.id]: error
  3158. },
  3159. fetchers: new Map(state.fetchers)
  3160. }, {
  3161. flushSync: (opts && opts.flushSync) === true
  3162. });
  3163. }
  3164. function getFetcher(key) {
  3165. activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
  3166. // If this fetcher was previously marked for deletion, unmark it since we
  3167. // have a new instance
  3168. if (deletedFetchers.has(key)) {
  3169. deletedFetchers.delete(key);
  3170. }
  3171. return state.fetchers.get(key) || IDLE_FETCHER;
  3172. }
  3173. function deleteFetcher(key) {
  3174. let fetcher = state.fetchers.get(key);
  3175. // Don't abort the controller if this is a deletion of a fetcher.submit()
  3176. // in it's loading phase since - we don't want to abort the corresponding
  3177. // revalidation and want them to complete and land
  3178. if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) {
  3179. abortFetcher(key);
  3180. }
  3181. fetchLoadMatches.delete(key);
  3182. fetchReloadIds.delete(key);
  3183. fetchRedirectIds.delete(key);
  3184. // If we opted into the flag we can clear this now since we're calling
  3185. // deleteFetcher() at the end of updateState() and we've already handed the
  3186. // deleted fetcher keys off to the data layer.
  3187. // If not, we're eagerly calling deleteFetcher() and we need to keep this
  3188. // Set populated until the next updateState call, and we'll clear
  3189. // `deletedFetchers` then
  3190. if (future.v7_fetcherPersist) {
  3191. deletedFetchers.delete(key);
  3192. }
  3193. cancelledFetcherLoads.delete(key);
  3194. state.fetchers.delete(key);
  3195. }
  3196. function deleteFetcherAndUpdateState(key) {
  3197. let count = (activeFetchers.get(key) || 0) - 1;
  3198. if (count <= 0) {
  3199. activeFetchers.delete(key);
  3200. deletedFetchers.add(key);
  3201. if (!future.v7_fetcherPersist) {
  3202. deleteFetcher(key);
  3203. }
  3204. } else {
  3205. activeFetchers.set(key, count);
  3206. }
  3207. updateState({
  3208. fetchers: new Map(state.fetchers)
  3209. });
  3210. }
  3211. function abortFetcher(key) {
  3212. let controller = fetchControllers.get(key);
  3213. if (controller) {
  3214. controller.abort();
  3215. fetchControllers.delete(key);
  3216. }
  3217. }
  3218. function markFetchersDone(keys) {
  3219. for (let key of keys) {
  3220. let fetcher = getFetcher(key);
  3221. let doneFetcher = getDoneFetcher(fetcher.data);
  3222. state.fetchers.set(key, doneFetcher);
  3223. }
  3224. }
  3225. function markFetchRedirectsDone() {
  3226. let doneKeys = [];
  3227. let updatedFetchers = false;
  3228. for (let key of fetchRedirectIds) {
  3229. let fetcher = state.fetchers.get(key);
  3230. invariant(fetcher, "Expected fetcher: " + key);
  3231. if (fetcher.state === "loading") {
  3232. fetchRedirectIds.delete(key);
  3233. doneKeys.push(key);
  3234. updatedFetchers = true;
  3235. }
  3236. }
  3237. markFetchersDone(doneKeys);
  3238. return updatedFetchers;
  3239. }
  3240. function abortStaleFetchLoads(landedId) {
  3241. let yeetedKeys = [];
  3242. for (let [key, id] of fetchReloadIds) {
  3243. if (id < landedId) {
  3244. let fetcher = state.fetchers.get(key);
  3245. invariant(fetcher, "Expected fetcher: " + key);
  3246. if (fetcher.state === "loading") {
  3247. abortFetcher(key);
  3248. fetchReloadIds.delete(key);
  3249. yeetedKeys.push(key);
  3250. }
  3251. }
  3252. }
  3253. markFetchersDone(yeetedKeys);
  3254. return yeetedKeys.length > 0;
  3255. }
  3256. function getBlocker(key, fn) {
  3257. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  3258. if (blockerFunctions.get(key) !== fn) {
  3259. blockerFunctions.set(key, fn);
  3260. }
  3261. return blocker;
  3262. }
  3263. function deleteBlocker(key) {
  3264. state.blockers.delete(key);
  3265. blockerFunctions.delete(key);
  3266. }
  3267. // Utility function to update blockers, ensuring valid state transitions
  3268. function updateBlocker(key, newBlocker) {
  3269. let blocker = state.blockers.get(key) || IDLE_BLOCKER;
  3270. // Poor mans state machine :)
  3271. // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM
  3272. invariant(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", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state);
  3273. let blockers = new Map(state.blockers);
  3274. blockers.set(key, newBlocker);
  3275. updateState({
  3276. blockers
  3277. });
  3278. }
  3279. function shouldBlockNavigation(_ref2) {
  3280. let {
  3281. currentLocation,
  3282. nextLocation,
  3283. historyAction
  3284. } = _ref2;
  3285. if (blockerFunctions.size === 0) {
  3286. return;
  3287. }
  3288. // We ony support a single active blocker at the moment since we don't have
  3289. // any compelling use cases for multi-blocker yet
  3290. if (blockerFunctions.size > 1) {
  3291. warning(false, "A router only supports one blocker at a time");
  3292. }
  3293. let entries = Array.from(blockerFunctions.entries());
  3294. let [blockerKey, blockerFunction] = entries[entries.length - 1];
  3295. let blocker = state.blockers.get(blockerKey);
  3296. if (blocker && blocker.state === "proceeding") {
  3297. // If the blocker is currently proceeding, we don't need to re-check
  3298. // it and can let this navigation continue
  3299. return;
  3300. }
  3301. // At this point, we know we're unblocked/blocked so we need to check the
  3302. // user-provided blocker function
  3303. if (blockerFunction({
  3304. currentLocation,
  3305. nextLocation,
  3306. historyAction
  3307. })) {
  3308. return blockerKey;
  3309. }
  3310. }
  3311. function handleNavigational404(pathname) {
  3312. let error = getInternalRouterError(404, {
  3313. pathname
  3314. });
  3315. let routesToUse = inFlightDataRoutes || dataRoutes;
  3316. let {
  3317. matches,
  3318. route
  3319. } = getShortCircuitMatches(routesToUse);
  3320. // Cancel all pending deferred on 404s since we don't keep any routes
  3321. cancelActiveDeferreds();
  3322. return {
  3323. notFoundMatches: matches,
  3324. route,
  3325. error
  3326. };
  3327. }
  3328. function cancelActiveDeferreds(predicate) {
  3329. let cancelledRouteIds = [];
  3330. activeDeferreds.forEach((dfd, routeId) => {
  3331. if (!predicate || predicate(routeId)) {
  3332. // Cancel the deferred - but do not remove from activeDeferreds here -
  3333. // we rely on the subscribers to do that so our tests can assert proper
  3334. // cleanup via _internalActiveDeferreds
  3335. dfd.cancel();
  3336. cancelledRouteIds.push(routeId);
  3337. activeDeferreds.delete(routeId);
  3338. }
  3339. });
  3340. return cancelledRouteIds;
  3341. }
  3342. // Opt in to capturing and reporting scroll positions during navigations,
  3343. // used by the <ScrollRestoration> component
  3344. function enableScrollRestoration(positions, getPosition, getKey) {
  3345. savedScrollPositions = positions;
  3346. getScrollPosition = getPosition;
  3347. getScrollRestorationKey = getKey || null;
  3348. // Perform initial hydration scroll restoration, since we miss the boat on
  3349. // the initial updateState() because we've not yet rendered <ScrollRestoration/>
  3350. // and therefore have no savedScrollPositions available
  3351. if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
  3352. initialScrollRestored = true;
  3353. let y = getSavedScrollPosition(state.location, state.matches);
  3354. if (y != null) {
  3355. updateState({
  3356. restoreScrollPosition: y
  3357. });
  3358. }
  3359. }
  3360. return () => {
  3361. savedScrollPositions = null;
  3362. getScrollPosition = null;
  3363. getScrollRestorationKey = null;
  3364. };
  3365. }
  3366. function getScrollKey(location, matches) {
  3367. if (getScrollRestorationKey) {
  3368. let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData)));
  3369. return key || location.key;
  3370. }
  3371. return location.key;
  3372. }
  3373. function saveScrollPosition(location, matches) {
  3374. if (savedScrollPositions && getScrollPosition) {
  3375. let key = getScrollKey(location, matches);
  3376. savedScrollPositions[key] = getScrollPosition();
  3377. }
  3378. }
  3379. function getSavedScrollPosition(location, matches) {
  3380. if (savedScrollPositions) {
  3381. let key = getScrollKey(location, matches);
  3382. let y = savedScrollPositions[key];
  3383. if (typeof y === "number") {
  3384. return y;
  3385. }
  3386. }
  3387. return null;
  3388. }
  3389. function checkFogOfWar(matches, routesToUse, pathname) {
  3390. if (patchRoutesOnNavigationImpl) {
  3391. if (!matches) {
  3392. let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
  3393. return {
  3394. active: true,
  3395. matches: fogMatches || []
  3396. };
  3397. } else {
  3398. if (Object.keys(matches[0].params).length > 0) {
  3399. // If we matched a dynamic param or a splat, it might only be because
  3400. // we haven't yet discovered other routes that would match with a
  3401. // higher score. Call patchRoutesOnNavigation just to be sure
  3402. let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
  3403. return {
  3404. active: true,
  3405. matches: partialMatches
  3406. };
  3407. }
  3408. }
  3409. }
  3410. return {
  3411. active: false,
  3412. matches: null
  3413. };
  3414. }
  3415. async function discoverRoutes(matches, pathname, signal, fetcherKey) {
  3416. if (!patchRoutesOnNavigationImpl) {
  3417. return {
  3418. type: "success",
  3419. matches
  3420. };
  3421. }
  3422. let partialMatches = matches;
  3423. while (true) {
  3424. let isNonHMR = inFlightDataRoutes == null;
  3425. let routesToUse = inFlightDataRoutes || dataRoutes;
  3426. let localManifest = manifest;
  3427. try {
  3428. await patchRoutesOnNavigationImpl({
  3429. signal,
  3430. path: pathname,
  3431. matches: partialMatches,
  3432. fetcherKey,
  3433. patch: (routeId, children) => {
  3434. if (signal.aborted) return;
  3435. patchRoutesImpl(routeId, children, routesToUse, localManifest, mapRouteProperties);
  3436. }
  3437. });
  3438. } catch (e) {
  3439. return {
  3440. type: "error",
  3441. error: e,
  3442. partialMatches
  3443. };
  3444. } finally {
  3445. // If we are not in the middle of an HMR revalidation and we changed the
  3446. // routes, provide a new identity so when we `updateState` at the end of
  3447. // this navigation/fetch `router.routes` will be a new identity and
  3448. // trigger a re-run of memoized `router.routes` dependencies.
  3449. // HMR will already update the identity and reflow when it lands
  3450. // `inFlightDataRoutes` in `completeNavigation`
  3451. if (isNonHMR && !signal.aborted) {
  3452. dataRoutes = [...dataRoutes];
  3453. }
  3454. }
  3455. if (signal.aborted) {
  3456. return {
  3457. type: "aborted"
  3458. };
  3459. }
  3460. let newMatches = matchRoutes(routesToUse, pathname, basename);
  3461. if (newMatches) {
  3462. return {
  3463. type: "success",
  3464. matches: newMatches
  3465. };
  3466. }
  3467. let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);
  3468. // Avoid loops if the second pass results in the same partial matches
  3469. if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every((m, i) => m.route.id === newPartialMatches[i].route.id)) {
  3470. return {
  3471. type: "success",
  3472. matches: null
  3473. };
  3474. }
  3475. partialMatches = newPartialMatches;
  3476. }
  3477. }
  3478. function _internalSetRoutes(newRoutes) {
  3479. manifest = {};
  3480. inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);
  3481. }
  3482. function patchRoutes(routeId, children) {
  3483. let isNonHMR = inFlightDataRoutes == null;
  3484. let routesToUse = inFlightDataRoutes || dataRoutes;
  3485. patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties);
  3486. // If we are not in the middle of an HMR revalidation and we changed the
  3487. // routes, provide a new identity and trigger a reflow via `updateState`
  3488. // to re-run memoized `router.routes` dependencies.
  3489. // HMR will already update the identity and reflow when it lands
  3490. // `inFlightDataRoutes` in `completeNavigation`
  3491. if (isNonHMR) {
  3492. dataRoutes = [...dataRoutes];
  3493. updateState({});
  3494. }
  3495. }
  3496. router = {
  3497. get basename() {
  3498. return basename;
  3499. },
  3500. get future() {
  3501. return future;
  3502. },
  3503. get state() {
  3504. return state;
  3505. },
  3506. get routes() {
  3507. return dataRoutes;
  3508. },
  3509. get window() {
  3510. return routerWindow;
  3511. },
  3512. initialize,
  3513. subscribe,
  3514. enableScrollRestoration,
  3515. navigate,
  3516. fetch,
  3517. revalidate,
  3518. // Passthrough to history-aware createHref used by useHref so we get proper
  3519. // hash-aware URLs in DOM paths
  3520. createHref: to => init.history.createHref(to),
  3521. encodeLocation: to => init.history.encodeLocation(to),
  3522. getFetcher,
  3523. deleteFetcher: deleteFetcherAndUpdateState,
  3524. dispose,
  3525. getBlocker,
  3526. deleteBlocker,
  3527. patchRoutes,
  3528. _internalFetchControllers: fetchControllers,
  3529. _internalActiveDeferreds: activeDeferreds,
  3530. // TODO: Remove setRoutes, it's temporary to avoid dealing with
  3531. // updating the tree while validating the update algorithm.
  3532. _internalSetRoutes
  3533. };
  3534. return router;
  3535. }
  3536. //#endregion
  3537. ////////////////////////////////////////////////////////////////////////////////
  3538. //#region createStaticHandler
  3539. ////////////////////////////////////////////////////////////////////////////////
  3540. const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
  3541. /**
  3542. * Future flags to toggle new feature behavior
  3543. */
  3544. function createStaticHandler(routes, opts) {
  3545. invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
  3546. let manifest = {};
  3547. let basename = (opts ? opts.basename : null) || "/";
  3548. let mapRouteProperties;
  3549. if (opts != null && opts.mapRouteProperties) {
  3550. mapRouteProperties = opts.mapRouteProperties;
  3551. } else if (opts != null && opts.detectErrorBoundary) {
  3552. // If they are still using the deprecated version, wrap it with the new API
  3553. let detectErrorBoundary = opts.detectErrorBoundary;
  3554. mapRouteProperties = route => ({
  3555. hasErrorBoundary: detectErrorBoundary(route)
  3556. });
  3557. } else {
  3558. mapRouteProperties = defaultMapRouteProperties;
  3559. }
  3560. // Config driven behavior flags
  3561. let future = _extends({
  3562. v7_relativeSplatPath: false,
  3563. v7_throwAbortReason: false
  3564. }, opts ? opts.future : null);
  3565. let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);
  3566. /**
  3567. * The query() method is intended for document requests, in which we want to
  3568. * call an optional action and potentially multiple loaders for all nested
  3569. * routes. It returns a StaticHandlerContext object, which is very similar
  3570. * to the router state (location, loaderData, actionData, errors, etc.) and
  3571. * also adds SSR-specific information such as the statusCode and headers
  3572. * from action/loaders Responses.
  3573. *
  3574. * It _should_ never throw and should report all errors through the
  3575. * returned context.errors object, properly associating errors to their error
  3576. * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be
  3577. * used to emulate React error boundaries during SSr by performing a second
  3578. * pass only down to the boundaryId.
  3579. *
  3580. * The one exception where we do not return a StaticHandlerContext is when a
  3581. * redirect response is returned or thrown from any action/loader. We
  3582. * propagate that out and return the raw Response so the HTTP server can
  3583. * return it directly.
  3584. *
  3585. * - `opts.requestContext` is an optional server context that will be passed
  3586. * to actions/loaders in the `context` parameter
  3587. * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent
  3588. * the bubbling of errors which allows single-fetch-type implementations
  3589. * where the client will handle the bubbling and we may need to return data
  3590. * for the handling route
  3591. */
  3592. async function query(request, _temp3) {
  3593. let {
  3594. requestContext,
  3595. skipLoaderErrorBubbling,
  3596. dataStrategy
  3597. } = _temp3 === void 0 ? {} : _temp3;
  3598. let url = new URL(request.url);
  3599. let method = request.method;
  3600. let location = createLocation("", createPath(url), null, "default");
  3601. let matches = matchRoutes(dataRoutes, location, basename);
  3602. // SSR supports HEAD requests while SPA doesn't
  3603. if (!isValidMethod(method) && method !== "HEAD") {
  3604. let error = getInternalRouterError(405, {
  3605. method
  3606. });
  3607. let {
  3608. matches: methodNotAllowedMatches,
  3609. route
  3610. } = getShortCircuitMatches(dataRoutes);
  3611. return {
  3612. basename,
  3613. location,
  3614. matches: methodNotAllowedMatches,
  3615. loaderData: {},
  3616. actionData: null,
  3617. errors: {
  3618. [route.id]: error
  3619. },
  3620. statusCode: error.status,
  3621. loaderHeaders: {},
  3622. actionHeaders: {},
  3623. activeDeferreds: null
  3624. };
  3625. } else if (!matches) {
  3626. let error = getInternalRouterError(404, {
  3627. pathname: location.pathname
  3628. });
  3629. let {
  3630. matches: notFoundMatches,
  3631. route
  3632. } = getShortCircuitMatches(dataRoutes);
  3633. return {
  3634. basename,
  3635. location,
  3636. matches: notFoundMatches,
  3637. loaderData: {},
  3638. actionData: null,
  3639. errors: {
  3640. [route.id]: error
  3641. },
  3642. statusCode: error.status,
  3643. loaderHeaders: {},
  3644. actionHeaders: {},
  3645. activeDeferreds: null
  3646. };
  3647. }
  3648. let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null);
  3649. if (isResponse(result)) {
  3650. return result;
  3651. }
  3652. // When returning StaticHandlerContext, we patch back in the location here
  3653. // since we need it for React Context. But this helps keep our submit and
  3654. // loadRouteData operating on a Request instead of a Location
  3655. return _extends({
  3656. location,
  3657. basename
  3658. }, result);
  3659. }
  3660. /**
  3661. * The queryRoute() method is intended for targeted route requests, either
  3662. * for fetch ?_data requests or resource route requests. In this case, we
  3663. * are only ever calling a single action or loader, and we are returning the
  3664. * returned value directly. In most cases, this will be a Response returned
  3665. * from the action/loader, but it may be a primitive or other value as well -
  3666. * and in such cases the calling context should handle that accordingly.
  3667. *
  3668. * We do respect the throw/return differentiation, so if an action/loader
  3669. * throws, then this method will throw the value. This is important so we
  3670. * can do proper boundary identification in Remix where a thrown Response
  3671. * must go to the Catch Boundary but a returned Response is happy-path.
  3672. *
  3673. * One thing to note is that any Router-initiated Errors that make sense
  3674. * to associate with a status code will be thrown as an ErrorResponse
  3675. * instance which include the raw Error, such that the calling context can
  3676. * serialize the error as they see fit while including the proper response
  3677. * code. Examples here are 404 and 405 errors that occur prior to reaching
  3678. * any user-defined loaders.
  3679. *
  3680. * - `opts.routeId` allows you to specify the specific route handler to call.
  3681. * If not provided the handler will determine the proper route by matching
  3682. * against `request.url`
  3683. * - `opts.requestContext` is an optional server context that will be passed
  3684. * to actions/loaders in the `context` parameter
  3685. */
  3686. async function queryRoute(request, _temp4) {
  3687. let {
  3688. routeId,
  3689. requestContext,
  3690. dataStrategy
  3691. } = _temp4 === void 0 ? {} : _temp4;
  3692. let url = new URL(request.url);
  3693. let method = request.method;
  3694. let location = createLocation("", createPath(url), null, "default");
  3695. let matches = matchRoutes(dataRoutes, location, basename);
  3696. // SSR supports HEAD requests while SPA doesn't
  3697. if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
  3698. throw getInternalRouterError(405, {
  3699. method
  3700. });
  3701. } else if (!matches) {
  3702. throw getInternalRouterError(404, {
  3703. pathname: location.pathname
  3704. });
  3705. }
  3706. let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);
  3707. if (routeId && !match) {
  3708. throw getInternalRouterError(403, {
  3709. pathname: location.pathname,
  3710. routeId
  3711. });
  3712. } else if (!match) {
  3713. // This should never hit I don't think?
  3714. throw getInternalRouterError(404, {
  3715. pathname: location.pathname
  3716. });
  3717. }
  3718. let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match);
  3719. if (isResponse(result)) {
  3720. return result;
  3721. }
  3722. let error = result.errors ? Object.values(result.errors)[0] : undefined;
  3723. if (error !== undefined) {
  3724. // If we got back result.errors, that means the loader/action threw
  3725. // _something_ that wasn't a Response, but it's not guaranteed/required
  3726. // to be an `instanceof Error` either, so we have to use throw here to
  3727. // preserve the "error" state outside of queryImpl.
  3728. throw error;
  3729. }
  3730. // Pick off the right state value to return
  3731. if (result.actionData) {
  3732. return Object.values(result.actionData)[0];
  3733. }
  3734. if (result.loaderData) {
  3735. var _result$activeDeferre;
  3736. let data = Object.values(result.loaderData)[0];
  3737. if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {
  3738. data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];
  3739. }
  3740. return data;
  3741. }
  3742. return undefined;
  3743. }
  3744. async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {
  3745. invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
  3746. try {
  3747. if (isMutationMethod(request.method.toLowerCase())) {
  3748. let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null);
  3749. return result;
  3750. }
  3751. let result = await loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch);
  3752. return isResponse(result) ? result : _extends({}, result, {
  3753. actionData: null,
  3754. actionHeaders: {}
  3755. });
  3756. } catch (e) {
  3757. // If the user threw/returned a Response in callLoaderOrAction for a
  3758. // `queryRoute` call, we throw the `DataStrategyResult` to bail out early
  3759. // and then return or throw the raw Response here accordingly
  3760. if (isDataStrategyResult(e) && isResponse(e.result)) {
  3761. if (e.type === ResultType.error) {
  3762. throw e.result;
  3763. }
  3764. return e.result;
  3765. }
  3766. // Redirects are always returned since they don't propagate to catch
  3767. // boundaries
  3768. if (isRedirectResponse(e)) {
  3769. return e;
  3770. }
  3771. throw e;
  3772. }
  3773. }
  3774. async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {
  3775. let result;
  3776. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  3777. let error = getInternalRouterError(405, {
  3778. method: request.method,
  3779. pathname: new URL(request.url).pathname,
  3780. routeId: actionMatch.route.id
  3781. });
  3782. if (isRouteRequest) {
  3783. throw error;
  3784. }
  3785. result = {
  3786. type: ResultType.error,
  3787. error
  3788. };
  3789. } else {
  3790. let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, dataStrategy);
  3791. result = results[actionMatch.route.id];
  3792. if (request.signal.aborted) {
  3793. throwStaticHandlerAbortedError(request, isRouteRequest, future);
  3794. }
  3795. }
  3796. if (isRedirectResult(result)) {
  3797. // Uhhhh - this should never happen, we should always throw these from
  3798. // callLoaderOrAction, but the type narrowing here keeps TS happy and we
  3799. // can get back on the "throw all redirect responses" train here should
  3800. // this ever happen :/
  3801. throw new Response(null, {
  3802. status: result.response.status,
  3803. headers: {
  3804. Location: result.response.headers.get("Location")
  3805. }
  3806. });
  3807. }
  3808. if (isDeferredResult(result)) {
  3809. let error = getInternalRouterError(400, {
  3810. type: "defer-action"
  3811. });
  3812. if (isRouteRequest) {
  3813. throw error;
  3814. }
  3815. result = {
  3816. type: ResultType.error,
  3817. error
  3818. };
  3819. }
  3820. if (isRouteRequest) {
  3821. // Note: This should only be non-Response values if we get here, since
  3822. // isRouteRequest should throw any Response received in callLoaderOrAction
  3823. if (isErrorResult(result)) {
  3824. throw result.error;
  3825. }
  3826. return {
  3827. matches: [actionMatch],
  3828. loaderData: {},
  3829. actionData: {
  3830. [actionMatch.route.id]: result.data
  3831. },
  3832. errors: null,
  3833. // Note: statusCode + headers are unused here since queryRoute will
  3834. // return the raw Response or value
  3835. statusCode: 200,
  3836. loaderHeaders: {},
  3837. actionHeaders: {},
  3838. activeDeferreds: null
  3839. };
  3840. }
  3841. // Create a GET request for the loaders
  3842. let loaderRequest = new Request(request.url, {
  3843. headers: request.headers,
  3844. redirect: request.redirect,
  3845. signal: request.signal
  3846. });
  3847. if (isErrorResult(result)) {
  3848. // Store off the pending error - we use it to determine which loaders
  3849. // to call and will commit it when we complete the navigation
  3850. let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
  3851. let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);
  3852. // action status codes take precedence over loader status codes
  3853. return _extends({}, context, {
  3854. statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
  3855. actionData: null,
  3856. actionHeaders: _extends({}, result.headers ? {
  3857. [actionMatch.route.id]: result.headers
  3858. } : {})
  3859. });
  3860. }
  3861. let context = await loadRouteData(loaderRequest, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null);
  3862. return _extends({}, context, {
  3863. actionData: {
  3864. [actionMatch.route.id]: result.data
  3865. }
  3866. }, result.statusCode ? {
  3867. statusCode: result.statusCode
  3868. } : {}, {
  3869. actionHeaders: result.headers ? {
  3870. [actionMatch.route.id]: result.headers
  3871. } : {}
  3872. });
  3873. }
  3874. async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {
  3875. let isRouteRequest = routeMatch != null;
  3876. // Short circuit if we have no loaders to run (queryRoute())
  3877. if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {
  3878. throw getInternalRouterError(400, {
  3879. method: request.method,
  3880. pathname: new URL(request.url).pathname,
  3881. routeId: routeMatch == null ? void 0 : routeMatch.route.id
  3882. });
  3883. }
  3884. let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;
  3885. let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);
  3886. // Short circuit if we have no loaders to run (query())
  3887. if (matchesToLoad.length === 0) {
  3888. return {
  3889. matches,
  3890. // Add a null for all matched routes for proper revalidation on the client
  3891. loaderData: matches.reduce((acc, m) => Object.assign(acc, {
  3892. [m.route.id]: null
  3893. }), {}),
  3894. errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
  3895. [pendingActionResult[0]]: pendingActionResult[1].error
  3896. } : null,
  3897. statusCode: 200,
  3898. loaderHeaders: {},
  3899. activeDeferreds: null
  3900. };
  3901. }
  3902. let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy);
  3903. if (request.signal.aborted) {
  3904. throwStaticHandlerAbortedError(request, isRouteRequest, future);
  3905. }
  3906. // Process and commit output from loaders
  3907. let activeDeferreds = new Map();
  3908. let context = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);
  3909. // Add a null for any non-loader matches for proper revalidation on the client
  3910. let executedLoaders = new Set(matchesToLoad.map(match => match.route.id));
  3911. matches.forEach(match => {
  3912. if (!executedLoaders.has(match.route.id)) {
  3913. context.loaderData[match.route.id] = null;
  3914. }
  3915. });
  3916. return _extends({}, context, {
  3917. matches,
  3918. activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null
  3919. });
  3920. }
  3921. // Utility wrapper for calling dataStrategy server-side without having to
  3922. // pass around the manifest, mapRouteProperties, etc.
  3923. async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {
  3924. let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, type, null, request, matchesToLoad, matches, null, manifest, mapRouteProperties, requestContext);
  3925. let dataResults = {};
  3926. await Promise.all(matches.map(async match => {
  3927. if (!(match.route.id in results)) {
  3928. return;
  3929. }
  3930. let result = results[match.route.id];
  3931. if (isRedirectDataStrategyResultResult(result)) {
  3932. let response = result.result;
  3933. // Throw redirects and let the server handle them with an HTTP redirect
  3934. throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename, future.v7_relativeSplatPath);
  3935. }
  3936. if (isResponse(result.result) && isRouteRequest) {
  3937. // For SSR single-route requests, we want to hand Responses back
  3938. // directly without unwrapping
  3939. throw result;
  3940. }
  3941. dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
  3942. }));
  3943. return dataResults;
  3944. }
  3945. return {
  3946. dataRoutes,
  3947. query,
  3948. queryRoute
  3949. };
  3950. }
  3951. //#endregion
  3952. ////////////////////////////////////////////////////////////////////////////////
  3953. //#region Helpers
  3954. ////////////////////////////////////////////////////////////////////////////////
  3955. /**
  3956. * Given an existing StaticHandlerContext and an error thrown at render time,
  3957. * provide an updated StaticHandlerContext suitable for a second SSR render
  3958. */
  3959. function getStaticContextFromError(routes, context, error) {
  3960. let newContext = _extends({}, context, {
  3961. statusCode: isRouteErrorResponse(error) ? error.status : 500,
  3962. errors: {
  3963. [context._deepestRenderedBoundaryId || routes[0].id]: error
  3964. }
  3965. });
  3966. return newContext;
  3967. }
  3968. function throwStaticHandlerAbortedError(request, isRouteRequest, future) {
  3969. if (future.v7_throwAbortReason && request.signal.reason !== undefined) {
  3970. throw request.signal.reason;
  3971. }
  3972. let method = isRouteRequest ? "queryRoute" : "query";
  3973. throw new Error(method + "() call aborted: " + request.method + " " + request.url);
  3974. }
  3975. function isSubmissionNavigation(opts) {
  3976. return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined);
  3977. }
  3978. function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {
  3979. let contextualMatches;
  3980. let activeRouteMatch;
  3981. if (fromRouteId) {
  3982. // Grab matches up to the calling route so our route-relative logic is
  3983. // relative to the correct source route
  3984. contextualMatches = [];
  3985. for (let match of matches) {
  3986. contextualMatches.push(match);
  3987. if (match.route.id === fromRouteId) {
  3988. activeRouteMatch = match;
  3989. break;
  3990. }
  3991. }
  3992. } else {
  3993. contextualMatches = matches;
  3994. activeRouteMatch = matches[matches.length - 1];
  3995. }
  3996. // Resolve the relative path
  3997. let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path");
  3998. // When `to` is not specified we inherit search/hash from the current
  3999. // location, unlike when to="." and we just inherit the path.
  4000. // See https://github.com/remix-run/remix/issues/927
  4001. if (to == null) {
  4002. path.search = location.search;
  4003. path.hash = location.hash;
  4004. }
  4005. // Account for `?index` params when routing to the current location
  4006. if ((to == null || to === "" || to === ".") && activeRouteMatch) {
  4007. let nakedIndex = hasNakedIndexQuery(path.search);
  4008. if (activeRouteMatch.route.index && !nakedIndex) {
  4009. // Add one when we're targeting an index route
  4010. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  4011. } else if (!activeRouteMatch.route.index && nakedIndex) {
  4012. // Remove existing ones when we're not
  4013. let params = new URLSearchParams(path.search);
  4014. let indexValues = params.getAll("index");
  4015. params.delete("index");
  4016. indexValues.filter(v => v).forEach(v => params.append("index", v));
  4017. let qs = params.toString();
  4018. path.search = qs ? "?" + qs : "";
  4019. }
  4020. }
  4021. // If we're operating within a basename, prepend it to the pathname. If
  4022. // this is a root navigation, then just use the raw basename which allows
  4023. // the basename to have full control over the presence of a trailing slash
  4024. // on root actions
  4025. if (prependBasename && basename !== "/") {
  4026. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  4027. }
  4028. return createPath(path);
  4029. }
  4030. // Normalize navigation options by converting formMethod=GET formData objects to
  4031. // URLSearchParams so they behave identically to links with query params
  4032. function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {
  4033. // Return location verbatim on non-submission navigations
  4034. if (!opts || !isSubmissionNavigation(opts)) {
  4035. return {
  4036. path
  4037. };
  4038. }
  4039. if (opts.formMethod && !isValidMethod(opts.formMethod)) {
  4040. return {
  4041. path,
  4042. error: getInternalRouterError(405, {
  4043. method: opts.formMethod
  4044. })
  4045. };
  4046. }
  4047. let getInvalidBodyError = () => ({
  4048. path,
  4049. error: getInternalRouterError(400, {
  4050. type: "invalid-body"
  4051. })
  4052. });
  4053. // Create a Submission on non-GET navigations
  4054. let rawFormMethod = opts.formMethod || "get";
  4055. let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();
  4056. let formAction = stripHashFromPath(path);
  4057. if (opts.body !== undefined) {
  4058. if (opts.formEncType === "text/plain") {
  4059. // text only support POST/PUT/PATCH/DELETE submissions
  4060. if (!isMutationMethod(formMethod)) {
  4061. return getInvalidBodyError();
  4062. }
  4063. let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ?
  4064. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data
  4065. Array.from(opts.body.entries()).reduce((acc, _ref3) => {
  4066. let [name, value] = _ref3;
  4067. return "" + acc + name + "=" + value + "\n";
  4068. }, "") : String(opts.body);
  4069. return {
  4070. path,
  4071. submission: {
  4072. formMethod,
  4073. formAction,
  4074. formEncType: opts.formEncType,
  4075. formData: undefined,
  4076. json: undefined,
  4077. text
  4078. }
  4079. };
  4080. } else if (opts.formEncType === "application/json") {
  4081. // json only supports POST/PUT/PATCH/DELETE submissions
  4082. if (!isMutationMethod(formMethod)) {
  4083. return getInvalidBodyError();
  4084. }
  4085. try {
  4086. let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
  4087. return {
  4088. path,
  4089. submission: {
  4090. formMethod,
  4091. formAction,
  4092. formEncType: opts.formEncType,
  4093. formData: undefined,
  4094. json,
  4095. text: undefined
  4096. }
  4097. };
  4098. } catch (e) {
  4099. return getInvalidBodyError();
  4100. }
  4101. }
  4102. }
  4103. invariant(typeof FormData === "function", "FormData is not available in this environment");
  4104. let searchParams;
  4105. let formData;
  4106. if (opts.formData) {
  4107. searchParams = convertFormDataToSearchParams(opts.formData);
  4108. formData = opts.formData;
  4109. } else if (opts.body instanceof FormData) {
  4110. searchParams = convertFormDataToSearchParams(opts.body);
  4111. formData = opts.body;
  4112. } else if (opts.body instanceof URLSearchParams) {
  4113. searchParams = opts.body;
  4114. formData = convertSearchParamsToFormData(searchParams);
  4115. } else if (opts.body == null) {
  4116. searchParams = new URLSearchParams();
  4117. formData = new FormData();
  4118. } else {
  4119. try {
  4120. searchParams = new URLSearchParams(opts.body);
  4121. formData = convertSearchParamsToFormData(searchParams);
  4122. } catch (e) {
  4123. return getInvalidBodyError();
  4124. }
  4125. }
  4126. let submission = {
  4127. formMethod,
  4128. formAction,
  4129. formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
  4130. formData,
  4131. json: undefined,
  4132. text: undefined
  4133. };
  4134. if (isMutationMethod(submission.formMethod)) {
  4135. return {
  4136. path,
  4137. submission
  4138. };
  4139. }
  4140. // Flatten submission onto URLSearchParams for GET submissions
  4141. let parsedPath = parsePath(path);
  4142. // On GET navigation submissions we can drop the ?index param from the
  4143. // resulting location since all loaders will run. But fetcher GET submissions
  4144. // only run a single loader so we need to preserve any incoming ?index params
  4145. if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
  4146. searchParams.append("index", "");
  4147. }
  4148. parsedPath.search = "?" + searchParams;
  4149. return {
  4150. path: createPath(parsedPath),
  4151. submission
  4152. };
  4153. }
  4154. // Filter out all routes at/below any caught error as they aren't going to
  4155. // render so we don't need to load them
  4156. function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary) {
  4157. if (includeBoundary === void 0) {
  4158. includeBoundary = false;
  4159. }
  4160. let index = matches.findIndex(m => m.route.id === boundaryId);
  4161. if (index >= 0) {
  4162. return matches.slice(0, includeBoundary ? index + 1 : index);
  4163. }
  4164. return matches;
  4165. }
  4166. function getMatchesToLoad(history, state, matches, submission, location, initialHydration, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {
  4167. let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined;
  4168. let currentUrl = history.createURL(state.location);
  4169. let nextUrl = history.createURL(location);
  4170. // Pick navigation matches that are net-new or qualify for revalidation
  4171. let boundaryMatches = matches;
  4172. if (initialHydration && state.errors) {
  4173. // On initial hydration, only consider matches up to _and including_ the boundary.
  4174. // This is inclusive to handle cases where a server loader ran successfully,
  4175. // a child server loader bubbled up to this route, but this route has
  4176. // `clientLoader.hydrate` so we want to still run the `clientLoader` so that
  4177. // we have a complete version of `loaderData`
  4178. boundaryMatches = getLoaderMatchesUntilBoundary(matches, Object.keys(state.errors)[0], true);
  4179. } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
  4180. // If an action threw an error, we call loaders up to, but not including the
  4181. // boundary
  4182. boundaryMatches = getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]);
  4183. }
  4184. // Don't revalidate loaders by default after action 4xx/5xx responses
  4185. // when the flag is enabled. They can still opt-into revalidation via
  4186. // `shouldRevalidate` via `actionResult`
  4187. let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined;
  4188. let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;
  4189. let navigationMatches = boundaryMatches.filter((match, index) => {
  4190. let {
  4191. route
  4192. } = match;
  4193. if (route.lazy) {
  4194. // We haven't loaded this route yet so we don't know if it's got a loader!
  4195. return true;
  4196. }
  4197. if (route.loader == null) {
  4198. return false;
  4199. }
  4200. if (initialHydration) {
  4201. return shouldLoadRouteOnHydration(route, state.loaderData, state.errors);
  4202. }
  4203. // Always call the loader on new route instances and pending defer cancellations
  4204. if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {
  4205. return true;
  4206. }
  4207. // This is the default implementation for when we revalidate. If the route
  4208. // provides it's own implementation, then we give them full control but
  4209. // provide this value so they can leverage it if needed after they check
  4210. // their own specific use cases
  4211. let currentRouteMatch = state.matches[index];
  4212. let nextRouteMatch = match;
  4213. return shouldRevalidateLoader(match, _extends({
  4214. currentUrl,
  4215. currentParams: currentRouteMatch.params,
  4216. nextUrl,
  4217. nextParams: nextRouteMatch.params
  4218. }, submission, {
  4219. actionResult,
  4220. actionStatus,
  4221. defaultShouldRevalidate: shouldSkipRevalidation ? false :
  4222. // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate
  4223. isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||
  4224. // Search params affect all loaders
  4225. currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
  4226. }));
  4227. });
  4228. // Pick fetcher.loads that need to be revalidated
  4229. let revalidatingFetchers = [];
  4230. fetchLoadMatches.forEach((f, key) => {
  4231. // Don't revalidate:
  4232. // - on initial hydration (shouldn't be any fetchers then anyway)
  4233. // - if fetcher won't be present in the subsequent render
  4234. // - no longer matches the URL (v7_fetcherPersist=false)
  4235. // - was unmounted but persisted due to v7_fetcherPersist=true
  4236. if (initialHydration || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {
  4237. return;
  4238. }
  4239. let fetcherMatches = matchRoutes(routesToUse, f.path, basename);
  4240. // If the fetcher path no longer matches, push it in with null matches so
  4241. // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is
  4242. // currently only a use-case for Remix HMR where the route tree can change
  4243. // at runtime and remove a route previously loaded via a fetcher
  4244. if (!fetcherMatches) {
  4245. revalidatingFetchers.push({
  4246. key,
  4247. routeId: f.routeId,
  4248. path: f.path,
  4249. matches: null,
  4250. match: null,
  4251. controller: null
  4252. });
  4253. return;
  4254. }
  4255. // Revalidating fetchers are decoupled from the route matches since they
  4256. // load from a static href. They revalidate based on explicit revalidation
  4257. // (submission, useRevalidator, or X-Remix-Revalidate)
  4258. let fetcher = state.fetchers.get(key);
  4259. let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
  4260. let shouldRevalidate = false;
  4261. if (fetchRedirectIds.has(key)) {
  4262. // Never trigger a revalidation of an actively redirecting fetcher
  4263. shouldRevalidate = false;
  4264. } else if (cancelledFetcherLoads.has(key)) {
  4265. // Always mark for revalidation if the fetcher was cancelled
  4266. cancelledFetcherLoads.delete(key);
  4267. shouldRevalidate = true;
  4268. } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) {
  4269. // If the fetcher hasn't ever completed loading yet, then this isn't a
  4270. // revalidation, it would just be a brand new load if an explicit
  4271. // revalidation is required
  4272. shouldRevalidate = isRevalidationRequired;
  4273. } else {
  4274. // Otherwise fall back on any user-defined shouldRevalidate, defaulting
  4275. // to explicit revalidations only
  4276. shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({
  4277. currentUrl,
  4278. currentParams: state.matches[state.matches.length - 1].params,
  4279. nextUrl,
  4280. nextParams: matches[matches.length - 1].params
  4281. }, submission, {
  4282. actionResult,
  4283. actionStatus,
  4284. defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired
  4285. }));
  4286. }
  4287. if (shouldRevalidate) {
  4288. revalidatingFetchers.push({
  4289. key,
  4290. routeId: f.routeId,
  4291. path: f.path,
  4292. matches: fetcherMatches,
  4293. match: fetcherMatch,
  4294. controller: new AbortController()
  4295. });
  4296. }
  4297. });
  4298. return [navigationMatches, revalidatingFetchers];
  4299. }
  4300. function shouldLoadRouteOnHydration(route, loaderData, errors) {
  4301. // We dunno if we have a loader - gotta find out!
  4302. if (route.lazy) {
  4303. return true;
  4304. }
  4305. // No loader, nothing to initialize
  4306. if (!route.loader) {
  4307. return false;
  4308. }
  4309. let hasData = loaderData != null && loaderData[route.id] !== undefined;
  4310. let hasError = errors != null && errors[route.id] !== undefined;
  4311. // Don't run if we error'd during SSR
  4312. if (!hasData && hasError) {
  4313. return false;
  4314. }
  4315. // Explicitly opting-in to running on hydration
  4316. if (typeof route.loader === "function" && route.loader.hydrate === true) {
  4317. return true;
  4318. }
  4319. // Otherwise, run if we're not yet initialized with anything
  4320. return !hasData && !hasError;
  4321. }
  4322. function isNewLoader(currentLoaderData, currentMatch, match) {
  4323. let isNew =
  4324. // [a] -> [a, b]
  4325. !currentMatch ||
  4326. // [a, b] -> [a, c]
  4327. match.route.id !== currentMatch.route.id;
  4328. // Handle the case that we don't have data for a re-used route, potentially
  4329. // from a prior error or from a cancelled pending deferred
  4330. let isMissingData = currentLoaderData[match.route.id] === undefined;
  4331. // Always load if this is a net-new route or we don't yet have data
  4332. return isNew || isMissingData;
  4333. }
  4334. function isNewRouteInstance(currentMatch, match) {
  4335. let currentPath = currentMatch.route.path;
  4336. return (
  4337. // param change for this match, /users/123 -> /users/456
  4338. currentMatch.pathname !== match.pathname ||
  4339. // splat param changed, which is not present in match.path
  4340. // e.g. /files/images/avatar.jpg -> files/finances.xls
  4341. currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
  4342. );
  4343. }
  4344. function shouldRevalidateLoader(loaderMatch, arg) {
  4345. if (loaderMatch.route.shouldRevalidate) {
  4346. let routeChoice = loaderMatch.route.shouldRevalidate(arg);
  4347. if (typeof routeChoice === "boolean") {
  4348. return routeChoice;
  4349. }
  4350. }
  4351. return arg.defaultShouldRevalidate;
  4352. }
  4353. function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties) {
  4354. var _childrenToPatch;
  4355. let childrenToPatch;
  4356. if (routeId) {
  4357. let route = manifest[routeId];
  4358. invariant(route, "No route found to patch children into: routeId = " + routeId);
  4359. if (!route.children) {
  4360. route.children = [];
  4361. }
  4362. childrenToPatch = route.children;
  4363. } else {
  4364. childrenToPatch = routesToUse;
  4365. }
  4366. // Don't patch in routes we already know about so that `patch` is idempotent
  4367. // to simplify user-land code. This is useful because we re-call the
  4368. // `patchRoutesOnNavigation` function for matched routes with params.
  4369. let uniqueChildren = children.filter(newRoute => !childrenToPatch.some(existingRoute => isSameRoute(newRoute, existingRoute)));
  4370. let newRoutes = convertRoutesToDataRoutes(uniqueChildren, mapRouteProperties, [routeId || "_", "patch", String(((_childrenToPatch = childrenToPatch) == null ? void 0 : _childrenToPatch.length) || "0")], manifest);
  4371. childrenToPatch.push(...newRoutes);
  4372. }
  4373. function isSameRoute(newRoute, existingRoute) {
  4374. // Most optimal check is by id
  4375. if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) {
  4376. return true;
  4377. }
  4378. // Second is by pathing differences
  4379. if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) {
  4380. return false;
  4381. }
  4382. // Pathless layout routes are trickier since we need to check children.
  4383. // If they have no children then they're the same as far as we can tell
  4384. if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) {
  4385. return true;
  4386. }
  4387. // Otherwise, we look to see if every child in the new route is already
  4388. // represented in the existing route's children
  4389. return newRoute.children.every((aChild, i) => {
  4390. var _existingRoute$childr;
  4391. return (_existingRoute$childr = existingRoute.children) == null ? void 0 : _existingRoute$childr.some(bChild => isSameRoute(aChild, bChild));
  4392. });
  4393. }
  4394. /**
  4395. * Execute route.lazy() methods to lazily load route modules (loader, action,
  4396. * shouldRevalidate) and update the routeManifest in place which shares objects
  4397. * with dataRoutes so those get updated as well.
  4398. */
  4399. async function loadLazyRouteModule(route, mapRouteProperties, manifest) {
  4400. if (!route.lazy) {
  4401. return;
  4402. }
  4403. let lazyRoute = await route.lazy();
  4404. // If the lazy route function was executed and removed by another parallel
  4405. // call then we can return - first lazy() to finish wins because the return
  4406. // value of lazy is expected to be static
  4407. if (!route.lazy) {
  4408. return;
  4409. }
  4410. let routeToUpdate = manifest[route.id];
  4411. invariant(routeToUpdate, "No route found in manifest");
  4412. // Update the route in place. This should be safe because there's no way
  4413. // we could yet be sitting on this route as we can't get there without
  4414. // resolving lazy() first.
  4415. //
  4416. // This is different than the HMR "update" use-case where we may actively be
  4417. // on the route being updated. The main concern boils down to "does this
  4418. // mutation affect any ongoing navigations or any current state.matches
  4419. // values?". If not, it should be safe to update in place.
  4420. let routeUpdates = {};
  4421. for (let lazyRouteProperty in lazyRoute) {
  4422. let staticRouteValue = routeToUpdate[lazyRouteProperty];
  4423. let isPropertyStaticallyDefined = staticRouteValue !== undefined &&
  4424. // This property isn't static since it should always be updated based
  4425. // on the route updates
  4426. lazyRouteProperty !== "hasErrorBoundary";
  4427. warning(!isPropertyStaticallyDefined, "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."));
  4428. if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
  4429. routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
  4430. }
  4431. }
  4432. // Mutate the route with the provided updates. Do this first so we pass
  4433. // the updated version to mapRouteProperties
  4434. Object.assign(routeToUpdate, routeUpdates);
  4435. // Mutate the `hasErrorBoundary` property on the route based on the route
  4436. // updates and remove the `lazy` function so we don't resolve the lazy
  4437. // route again.
  4438. Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {
  4439. lazy: undefined
  4440. }));
  4441. }
  4442. // Default implementation of `dataStrategy` which fetches all loaders in parallel
  4443. async function defaultDataStrategy(_ref4) {
  4444. let {
  4445. matches
  4446. } = _ref4;
  4447. let matchesToLoad = matches.filter(m => m.shouldLoad);
  4448. let results = await Promise.all(matchesToLoad.map(m => m.resolve()));
  4449. return results.reduce((acc, result, i) => Object.assign(acc, {
  4450. [matchesToLoad[i].route.id]: result
  4451. }), {});
  4452. }
  4453. async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties, requestContext) {
  4454. let loadRouteDefinitionsPromises = matches.map(m => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties, manifest) : undefined);
  4455. let dsMatches = matches.map((match, i) => {
  4456. let loadRoutePromise = loadRouteDefinitionsPromises[i];
  4457. let shouldLoad = matchesToLoad.some(m => m.route.id === match.route.id);
  4458. // `resolve` encapsulates route.lazy(), executing the loader/action,
  4459. // and mapping return values/thrown errors to a `DataStrategyResult`. Users
  4460. // can pass a callback to take fine-grained control over the execution
  4461. // of the loader/action
  4462. let resolve = async handlerOverride => {
  4463. if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
  4464. shouldLoad = true;
  4465. }
  4466. return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({
  4467. type: ResultType.data,
  4468. result: undefined
  4469. });
  4470. };
  4471. return _extends({}, match, {
  4472. shouldLoad,
  4473. resolve
  4474. });
  4475. });
  4476. // Send all matches here to allow for a middleware-type implementation.
  4477. // handler will be a no-op for unneeded routes and we filter those results
  4478. // back out below.
  4479. let results = await dataStrategyImpl({
  4480. matches: dsMatches,
  4481. request,
  4482. params: matches[0].params,
  4483. fetcherKey,
  4484. context: requestContext
  4485. });
  4486. // Wait for all routes to load here but 'swallow the error since we want
  4487. // it to bubble up from the `await loadRoutePromise` in `callLoaderOrAction` -
  4488. // called from `match.resolve()`
  4489. try {
  4490. await Promise.all(loadRouteDefinitionsPromises);
  4491. } catch (e) {
  4492. // No-op
  4493. }
  4494. return results;
  4495. }
  4496. // Default logic for calling a loader/action is the user has no specified a dataStrategy
  4497. async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
  4498. let result;
  4499. let onReject;
  4500. let runHandler = handler => {
  4501. // Setup a promise we can race against so that abort signals short circuit
  4502. let reject;
  4503. // This will never resolve so safe to type it as Promise<DataStrategyResult> to
  4504. // satisfy the function return value
  4505. let abortPromise = new Promise((_, r) => reject = r);
  4506. onReject = () => reject();
  4507. request.signal.addEventListener("abort", onReject);
  4508. let actualHandler = ctx => {
  4509. if (typeof handler !== "function") {
  4510. return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ("\"" + type + "\" [routeId: " + match.route.id + "]")));
  4511. }
  4512. return handler({
  4513. request,
  4514. params: match.params,
  4515. context: staticContext
  4516. }, ...(ctx !== undefined ? [ctx] : []));
  4517. };
  4518. let handlerPromise = (async () => {
  4519. try {
  4520. let val = await (handlerOverride ? handlerOverride(ctx => actualHandler(ctx)) : actualHandler());
  4521. return {
  4522. type: "data",
  4523. result: val
  4524. };
  4525. } catch (e) {
  4526. return {
  4527. type: "error",
  4528. result: e
  4529. };
  4530. }
  4531. })();
  4532. return Promise.race([handlerPromise, abortPromise]);
  4533. };
  4534. try {
  4535. let handler = match.route[type];
  4536. // If we have a route.lazy promise, await that first
  4537. if (loadRoutePromise) {
  4538. if (handler) {
  4539. // Run statically defined handler in parallel with lazy()
  4540. let handlerError;
  4541. let [value] = await Promise.all([
  4542. // If the handler throws, don't let it immediately bubble out,
  4543. // since we need to let the lazy() execution finish so we know if this
  4544. // route has a boundary that can handle the error
  4545. runHandler(handler).catch(e => {
  4546. handlerError = e;
  4547. }), loadRoutePromise]);
  4548. if (handlerError !== undefined) {
  4549. throw handlerError;
  4550. }
  4551. result = value;
  4552. } else {
  4553. // Load lazy route module, then run any returned handler
  4554. await loadRoutePromise;
  4555. handler = match.route[type];
  4556. if (handler) {
  4557. // Handler still runs even if we got interrupted to maintain consistency
  4558. // with un-abortable behavior of handler execution on non-lazy or
  4559. // previously-lazy-loaded routes
  4560. result = await runHandler(handler);
  4561. } else if (type === "action") {
  4562. let url = new URL(request.url);
  4563. let pathname = url.pathname + url.search;
  4564. throw getInternalRouterError(405, {
  4565. method: request.method,
  4566. pathname,
  4567. routeId: match.route.id
  4568. });
  4569. } else {
  4570. // lazy() route has no loader to run. Short circuit here so we don't
  4571. // hit the invariant below that errors on returning undefined.
  4572. return {
  4573. type: ResultType.data,
  4574. result: undefined
  4575. };
  4576. }
  4577. }
  4578. } else if (!handler) {
  4579. let url = new URL(request.url);
  4580. let pathname = url.pathname + url.search;
  4581. throw getInternalRouterError(404, {
  4582. pathname
  4583. });
  4584. } else {
  4585. result = await runHandler(handler);
  4586. }
  4587. invariant(result.result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`.");
  4588. } catch (e) {
  4589. // We should already be catching and converting normal handler executions to
  4590. // DataStrategyResults and returning them, so anything that throws here is an
  4591. // unexpected error we still need to wrap
  4592. return {
  4593. type: ResultType.error,
  4594. result: e
  4595. };
  4596. } finally {
  4597. if (onReject) {
  4598. request.signal.removeEventListener("abort", onReject);
  4599. }
  4600. }
  4601. return result;
  4602. }
  4603. async function convertDataStrategyResultToDataResult(dataStrategyResult) {
  4604. let {
  4605. result,
  4606. type
  4607. } = dataStrategyResult;
  4608. if (isResponse(result)) {
  4609. let data;
  4610. try {
  4611. let contentType = result.headers.get("Content-Type");
  4612. // Check between word boundaries instead of startsWith() due to the last
  4613. // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type
  4614. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  4615. if (result.body == null) {
  4616. data = null;
  4617. } else {
  4618. data = await result.json();
  4619. }
  4620. } else {
  4621. data = await result.text();
  4622. }
  4623. } catch (e) {
  4624. return {
  4625. type: ResultType.error,
  4626. error: e
  4627. };
  4628. }
  4629. if (type === ResultType.error) {
  4630. return {
  4631. type: ResultType.error,
  4632. error: new ErrorResponseImpl(result.status, result.statusText, data),
  4633. statusCode: result.status,
  4634. headers: result.headers
  4635. };
  4636. }
  4637. return {
  4638. type: ResultType.data,
  4639. data,
  4640. statusCode: result.status,
  4641. headers: result.headers
  4642. };
  4643. }
  4644. if (type === ResultType.error) {
  4645. if (isDataWithResponseInit(result)) {
  4646. var _result$init3, _result$init4;
  4647. if (result.data instanceof Error) {
  4648. var _result$init, _result$init2;
  4649. return {
  4650. type: ResultType.error,
  4651. error: result.data,
  4652. statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,
  4653. headers: (_result$init2 = result.init) != null && _result$init2.headers ? new Headers(result.init.headers) : undefined
  4654. };
  4655. }
  4656. // Convert thrown data() to ErrorResponse instances
  4657. return {
  4658. type: ResultType.error,
  4659. error: new ErrorResponseImpl(((_result$init3 = result.init) == null ? void 0 : _result$init3.status) || 500, undefined, result.data),
  4660. statusCode: isRouteErrorResponse(result) ? result.status : undefined,
  4661. headers: (_result$init4 = result.init) != null && _result$init4.headers ? new Headers(result.init.headers) : undefined
  4662. };
  4663. }
  4664. return {
  4665. type: ResultType.error,
  4666. error: result,
  4667. statusCode: isRouteErrorResponse(result) ? result.status : undefined
  4668. };
  4669. }
  4670. if (isDeferredData(result)) {
  4671. var _result$init5, _result$init6;
  4672. return {
  4673. type: ResultType.deferred,
  4674. deferredData: result,
  4675. statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status,
  4676. headers: ((_result$init6 = result.init) == null ? void 0 : _result$init6.headers) && new Headers(result.init.headers)
  4677. };
  4678. }
  4679. if (isDataWithResponseInit(result)) {
  4680. var _result$init7, _result$init8;
  4681. return {
  4682. type: ResultType.data,
  4683. data: result.data,
  4684. statusCode: (_result$init7 = result.init) == null ? void 0 : _result$init7.status,
  4685. headers: (_result$init8 = result.init) != null && _result$init8.headers ? new Headers(result.init.headers) : undefined
  4686. };
  4687. }
  4688. return {
  4689. type: ResultType.data,
  4690. data: result
  4691. };
  4692. }
  4693. // Support relative routing in internal redirects
  4694. function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {
  4695. let location = response.headers.get("Location");
  4696. invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header");
  4697. if (!ABSOLUTE_URL_REGEX.test(location)) {
  4698. let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1);
  4699. location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);
  4700. response.headers.set("Location", location);
  4701. }
  4702. return response;
  4703. }
  4704. function normalizeRedirectLocation(location, currentUrl, basename, historyInstance) {
  4705. // Match Chrome's behavior:
  4706. // https://github.com/chromium/chromium/blob/216dbeb61db0c667e62082e5f5400a32d6983df3/content/public/common/url_utils.cc#L82
  4707. let invalidProtocols = ["about:", "blob:", "chrome:", "chrome-untrusted:", "content:", "data:", "devtools:", "file:", "filesystem:",
  4708. // eslint-disable-next-line no-script-url
  4709. "javascript:"];
  4710. if (ABSOLUTE_URL_REGEX.test(location)) {
  4711. // Strip off the protocol+origin for same-origin + same-basename absolute redirects
  4712. let normalizedLocation = location;
  4713. let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);
  4714. if (invalidProtocols.includes(url.protocol)) {
  4715. throw new Error("Invalid redirect location");
  4716. }
  4717. let isSameBasename = stripBasename(url.pathname, basename) != null;
  4718. if (url.origin === currentUrl.origin && isSameBasename) {
  4719. return url.pathname + url.search + url.hash;
  4720. }
  4721. }
  4722. try {
  4723. let url = historyInstance.createURL(location);
  4724. if (invalidProtocols.includes(url.protocol)) {
  4725. throw new Error("Invalid redirect location");
  4726. }
  4727. } catch (e) {}
  4728. return location;
  4729. }
  4730. // Utility method for creating the Request instances for loaders/actions during
  4731. // client-side navigations and fetches. During SSR we will always have a
  4732. // Request instance from the static handler (query/queryRoute)
  4733. function createClientSideRequest(history, location, signal, submission) {
  4734. let url = history.createURL(stripHashFromPath(location)).toString();
  4735. let init = {
  4736. signal
  4737. };
  4738. if (submission && isMutationMethod(submission.formMethod)) {
  4739. let {
  4740. formMethod,
  4741. formEncType
  4742. } = submission;
  4743. // Didn't think we needed this but it turns out unlike other methods, patch
  4744. // won't be properly normalized to uppercase and results in a 405 error.
  4745. // See: https://fetch.spec.whatwg.org/#concept-method
  4746. init.method = formMethod.toUpperCase();
  4747. if (formEncType === "application/json") {
  4748. init.headers = new Headers({
  4749. "Content-Type": formEncType
  4750. });
  4751. init.body = JSON.stringify(submission.json);
  4752. } else if (formEncType === "text/plain") {
  4753. // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
  4754. init.body = submission.text;
  4755. } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) {
  4756. // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
  4757. init.body = convertFormDataToSearchParams(submission.formData);
  4758. } else {
  4759. // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
  4760. init.body = submission.formData;
  4761. }
  4762. }
  4763. return new Request(url, init);
  4764. }
  4765. function convertFormDataToSearchParams(formData) {
  4766. let searchParams = new URLSearchParams();
  4767. for (let [key, value] of formData.entries()) {
  4768. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
  4769. searchParams.append(key, typeof value === "string" ? value : value.name);
  4770. }
  4771. return searchParams;
  4772. }
  4773. function convertSearchParamsToFormData(searchParams) {
  4774. let formData = new FormData();
  4775. for (let [key, value] of searchParams.entries()) {
  4776. formData.append(key, value);
  4777. }
  4778. return formData;
  4779. }
  4780. function processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {
  4781. // Fill in loaderData/errors from our loaders
  4782. let loaderData = {};
  4783. let errors = null;
  4784. let statusCode;
  4785. let foundError = false;
  4786. let loaderHeaders = {};
  4787. let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined;
  4788. // Process loader results into state.loaderData/state.errors
  4789. matches.forEach(match => {
  4790. if (!(match.route.id in results)) {
  4791. return;
  4792. }
  4793. let id = match.route.id;
  4794. let result = results[id];
  4795. invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
  4796. if (isErrorResult(result)) {
  4797. let error = result.error;
  4798. // If we have a pending action error, we report it at the highest-route
  4799. // that throws a loader error, and then clear it out to indicate that
  4800. // it was consumed
  4801. if (pendingError !== undefined) {
  4802. error = pendingError;
  4803. pendingError = undefined;
  4804. }
  4805. errors = errors || {};
  4806. if (skipLoaderErrorBubbling) {
  4807. errors[id] = error;
  4808. } else {
  4809. // Look upwards from the matched route for the closest ancestor error
  4810. // boundary, defaulting to the root match. Prefer higher error values
  4811. // if lower errors bubble to the same boundary
  4812. let boundaryMatch = findNearestBoundary(matches, id);
  4813. if (errors[boundaryMatch.route.id] == null) {
  4814. errors[boundaryMatch.route.id] = error;
  4815. }
  4816. }
  4817. // Clear our any prior loaderData for the throwing route
  4818. loaderData[id] = undefined;
  4819. // Once we find our first (highest) error, we set the status code and
  4820. // prevent deeper status codes from overriding
  4821. if (!foundError) {
  4822. foundError = true;
  4823. statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
  4824. }
  4825. if (result.headers) {
  4826. loaderHeaders[id] = result.headers;
  4827. }
  4828. } else {
  4829. if (isDeferredResult(result)) {
  4830. activeDeferreds.set(id, result.deferredData);
  4831. loaderData[id] = result.deferredData.data;
  4832. // Error status codes always override success status codes, but if all
  4833. // loaders are successful we take the deepest status code.
  4834. if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
  4835. statusCode = result.statusCode;
  4836. }
  4837. if (result.headers) {
  4838. loaderHeaders[id] = result.headers;
  4839. }
  4840. } else {
  4841. loaderData[id] = result.data;
  4842. // Error status codes always override success status codes, but if all
  4843. // loaders are successful we take the deepest status code.
  4844. if (result.statusCode && result.statusCode !== 200 && !foundError) {
  4845. statusCode = result.statusCode;
  4846. }
  4847. if (result.headers) {
  4848. loaderHeaders[id] = result.headers;
  4849. }
  4850. }
  4851. }
  4852. });
  4853. // If we didn't consume the pending action error (i.e., all loaders
  4854. // resolved), then consume it here. Also clear out any loaderData for the
  4855. // throwing route
  4856. if (pendingError !== undefined && pendingActionResult) {
  4857. errors = {
  4858. [pendingActionResult[0]]: pendingError
  4859. };
  4860. loaderData[pendingActionResult[0]] = undefined;
  4861. }
  4862. return {
  4863. loaderData,
  4864. errors,
  4865. statusCode: statusCode || 200,
  4866. loaderHeaders
  4867. };
  4868. }
  4869. function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {
  4870. let {
  4871. loaderData,
  4872. errors
  4873. } = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble
  4874. );
  4875. // Process results from our revalidating fetchers
  4876. revalidatingFetchers.forEach(rf => {
  4877. let {
  4878. key,
  4879. match,
  4880. controller
  4881. } = rf;
  4882. let result = fetcherResults[key];
  4883. invariant(result, "Did not find corresponding fetcher result");
  4884. // Process fetcher non-redirect errors
  4885. if (controller && controller.signal.aborted) {
  4886. // Nothing to do for aborted fetchers
  4887. return;
  4888. } else if (isErrorResult(result)) {
  4889. let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);
  4890. if (!(errors && errors[boundaryMatch.route.id])) {
  4891. errors = _extends({}, errors, {
  4892. [boundaryMatch.route.id]: result.error
  4893. });
  4894. }
  4895. state.fetchers.delete(key);
  4896. } else if (isRedirectResult(result)) {
  4897. // Should never get here, redirects should get processed above, but we
  4898. // keep this to type narrow to a success result in the else
  4899. invariant(false, "Unhandled fetcher revalidation redirect");
  4900. } else if (isDeferredResult(result)) {
  4901. // Should never get here, deferred data should be awaited for fetchers
  4902. // in resolveDeferredResults
  4903. invariant(false, "Unhandled fetcher deferred data");
  4904. } else {
  4905. let doneFetcher = getDoneFetcher(result.data);
  4906. state.fetchers.set(key, doneFetcher);
  4907. }
  4908. });
  4909. return {
  4910. loaderData,
  4911. errors
  4912. };
  4913. }
  4914. function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
  4915. let mergedLoaderData = _extends({}, newLoaderData);
  4916. for (let match of matches) {
  4917. let id = match.route.id;
  4918. if (newLoaderData.hasOwnProperty(id)) {
  4919. if (newLoaderData[id] !== undefined) {
  4920. mergedLoaderData[id] = newLoaderData[id];
  4921. }
  4922. } else if (loaderData[id] !== undefined && match.route.loader) {
  4923. // Preserve existing keys not included in newLoaderData and where a loader
  4924. // wasn't removed by HMR
  4925. mergedLoaderData[id] = loaderData[id];
  4926. }
  4927. if (errors && errors.hasOwnProperty(id)) {
  4928. // Don't keep any loader data below the boundary
  4929. break;
  4930. }
  4931. }
  4932. return mergedLoaderData;
  4933. }
  4934. function getActionDataForCommit(pendingActionResult) {
  4935. if (!pendingActionResult) {
  4936. return {};
  4937. }
  4938. return isErrorResult(pendingActionResult[1]) ? {
  4939. // Clear out prior actionData on errors
  4940. actionData: {}
  4941. } : {
  4942. actionData: {
  4943. [pendingActionResult[0]]: pendingActionResult[1].data
  4944. }
  4945. };
  4946. }
  4947. // Find the nearest error boundary, looking upwards from the leaf route (or the
  4948. // route specified by routeId) for the closest ancestor error boundary,
  4949. // defaulting to the root match
  4950. function findNearestBoundary(matches, routeId) {
  4951. let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
  4952. return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
  4953. }
  4954. function getShortCircuitMatches(routes) {
  4955. // Prefer a root layout route if present, otherwise shim in a route object
  4956. let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || {
  4957. id: "__shim-error-route__"
  4958. };
  4959. return {
  4960. matches: [{
  4961. params: {},
  4962. pathname: "",
  4963. pathnameBase: "",
  4964. route
  4965. }],
  4966. route
  4967. };
  4968. }
  4969. function getInternalRouterError(status, _temp5) {
  4970. let {
  4971. pathname,
  4972. routeId,
  4973. method,
  4974. type,
  4975. message
  4976. } = _temp5 === void 0 ? {} : _temp5;
  4977. let statusText = "Unknown Server Error";
  4978. let errorMessage = "Unknown @remix-run/router error";
  4979. if (status === 400) {
  4980. statusText = "Bad Request";
  4981. if (method && pathname && routeId) {
  4982. 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.";
  4983. } else if (type === "defer-action") {
  4984. errorMessage = "defer() is not supported in actions";
  4985. } else if (type === "invalid-body") {
  4986. errorMessage = "Unable to encode submission body";
  4987. }
  4988. } else if (status === 403) {
  4989. statusText = "Forbidden";
  4990. errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\"";
  4991. } else if (status === 404) {
  4992. statusText = "Not Found";
  4993. errorMessage = "No route matches URL \"" + pathname + "\"";
  4994. } else if (status === 405) {
  4995. statusText = "Method Not Allowed";
  4996. if (method && pathname && routeId) {
  4997. 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.";
  4998. } else if (method) {
  4999. errorMessage = "Invalid request method \"" + method.toUpperCase() + "\"";
  5000. }
  5001. }
  5002. return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);
  5003. }
  5004. // Find any returned redirect errors, starting from the lowest match
  5005. function findRedirect(results) {
  5006. let entries = Object.entries(results);
  5007. for (let i = entries.length - 1; i >= 0; i--) {
  5008. let [key, result] = entries[i];
  5009. if (isRedirectResult(result)) {
  5010. return {
  5011. key,
  5012. result
  5013. };
  5014. }
  5015. }
  5016. }
  5017. function stripHashFromPath(path) {
  5018. let parsedPath = typeof path === "string" ? parsePath(path) : path;
  5019. return createPath(_extends({}, parsedPath, {
  5020. hash: ""
  5021. }));
  5022. }
  5023. function isHashChangeOnly(a, b) {
  5024. if (a.pathname !== b.pathname || a.search !== b.search) {
  5025. return false;
  5026. }
  5027. if (a.hash === "") {
  5028. // /page -> /page#hash
  5029. return b.hash !== "";
  5030. } else if (a.hash === b.hash) {
  5031. // /page#hash -> /page#hash
  5032. return true;
  5033. } else if (b.hash !== "") {
  5034. // /page#hash -> /page#other
  5035. return true;
  5036. }
  5037. // If the hash is removed the browser will re-perform a request to the server
  5038. // /page#hash -> /page
  5039. return false;
  5040. }
  5041. function isDataStrategyResult(result) {
  5042. return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error);
  5043. }
  5044. function isRedirectDataStrategyResultResult(result) {
  5045. return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
  5046. }
  5047. function isDeferredResult(result) {
  5048. return result.type === ResultType.deferred;
  5049. }
  5050. function isErrorResult(result) {
  5051. return result.type === ResultType.error;
  5052. }
  5053. function isRedirectResult(result) {
  5054. return (result && result.type) === ResultType.redirect;
  5055. }
  5056. function isDataWithResponseInit(value) {
  5057. return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
  5058. }
  5059. function isDeferredData(value) {
  5060. let deferred = value;
  5061. return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function";
  5062. }
  5063. function isResponse(value) {
  5064. return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
  5065. }
  5066. function isRedirectResponse(result) {
  5067. if (!isResponse(result)) {
  5068. return false;
  5069. }
  5070. let status = result.status;
  5071. let location = result.headers.get("Location");
  5072. return status >= 300 && status <= 399 && location != null;
  5073. }
  5074. function isValidMethod(method) {
  5075. return validRequestMethods.has(method.toLowerCase());
  5076. }
  5077. function isMutationMethod(method) {
  5078. return validMutationMethods.has(method.toLowerCase());
  5079. }
  5080. async function resolveNavigationDeferredResults(matches, results, signal, currentMatches, currentLoaderData) {
  5081. let entries = Object.entries(results);
  5082. for (let index = 0; index < entries.length; index++) {
  5083. let [routeId, result] = entries[index];
  5084. let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
  5085. // If we don't have a match, then we can have a deferred result to do
  5086. // anything with. This is for revalidating fetchers where the route was
  5087. // removed during HMR
  5088. if (!match) {
  5089. continue;
  5090. }
  5091. let currentMatch = currentMatches.find(m => m.route.id === match.route.id);
  5092. let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;
  5093. if (isDeferredResult(result) && isRevalidatingLoader) {
  5094. // Note: we do not have to touch activeDeferreds here since we race them
  5095. // against the signal in resolveDeferredData and they'll get aborted
  5096. // there if needed
  5097. await resolveDeferredData(result, signal, false).then(result => {
  5098. if (result) {
  5099. results[routeId] = result;
  5100. }
  5101. });
  5102. }
  5103. }
  5104. }
  5105. async function resolveFetcherDeferredResults(matches, results, revalidatingFetchers) {
  5106. for (let index = 0; index < revalidatingFetchers.length; index++) {
  5107. let {
  5108. key,
  5109. routeId,
  5110. controller
  5111. } = revalidatingFetchers[index];
  5112. let result = results[key];
  5113. let match = matches.find(m => (m == null ? void 0 : m.route.id) === routeId);
  5114. // If we don't have a match, then we can have a deferred result to do
  5115. // anything with. This is for revalidating fetchers where the route was
  5116. // removed during HMR
  5117. if (!match) {
  5118. continue;
  5119. }
  5120. if (isDeferredResult(result)) {
  5121. // Note: we do not have to touch activeDeferreds here since we race them
  5122. // against the signal in resolveDeferredData and they'll get aborted
  5123. // there if needed
  5124. invariant(controller, "Expected an AbortController for revalidating fetcher deferred result");
  5125. await resolveDeferredData(result, controller.signal, true).then(result => {
  5126. if (result) {
  5127. results[key] = result;
  5128. }
  5129. });
  5130. }
  5131. }
  5132. }
  5133. async function resolveDeferredData(result, signal, unwrap) {
  5134. if (unwrap === void 0) {
  5135. unwrap = false;
  5136. }
  5137. let aborted = await result.deferredData.resolveData(signal);
  5138. if (aborted) {
  5139. return;
  5140. }
  5141. if (unwrap) {
  5142. try {
  5143. return {
  5144. type: ResultType.data,
  5145. data: result.deferredData.unwrappedData
  5146. };
  5147. } catch (e) {
  5148. // Handle any TrackedPromise._error values encountered while unwrapping
  5149. return {
  5150. type: ResultType.error,
  5151. error: e
  5152. };
  5153. }
  5154. }
  5155. return {
  5156. type: ResultType.data,
  5157. data: result.deferredData.data
  5158. };
  5159. }
  5160. function hasNakedIndexQuery(search) {
  5161. return new URLSearchParams(search).getAll("index").some(v => v === "");
  5162. }
  5163. function getTargetMatch(matches, location) {
  5164. let search = typeof location === "string" ? parsePath(location).search : location.search;
  5165. if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
  5166. // Return the leaf index route when index is present
  5167. return matches[matches.length - 1];
  5168. }
  5169. // Otherwise grab the deepest "path contributing" match (ignoring index and
  5170. // pathless layout routes)
  5171. let pathMatches = getPathContributingMatches(matches);
  5172. return pathMatches[pathMatches.length - 1];
  5173. }
  5174. function getSubmissionFromNavigation(navigation) {
  5175. let {
  5176. formMethod,
  5177. formAction,
  5178. formEncType,
  5179. text,
  5180. formData,
  5181. json
  5182. } = navigation;
  5183. if (!formMethod || !formAction || !formEncType) {
  5184. return;
  5185. }
  5186. if (text != null) {
  5187. return {
  5188. formMethod,
  5189. formAction,
  5190. formEncType,
  5191. formData: undefined,
  5192. json: undefined,
  5193. text
  5194. };
  5195. } else if (formData != null) {
  5196. return {
  5197. formMethod,
  5198. formAction,
  5199. formEncType,
  5200. formData,
  5201. json: undefined,
  5202. text: undefined
  5203. };
  5204. } else if (json !== undefined) {
  5205. return {
  5206. formMethod,
  5207. formAction,
  5208. formEncType,
  5209. formData: undefined,
  5210. json,
  5211. text: undefined
  5212. };
  5213. }
  5214. }
  5215. function getLoadingNavigation(location, submission) {
  5216. if (submission) {
  5217. let navigation = {
  5218. state: "loading",
  5219. location,
  5220. formMethod: submission.formMethod,
  5221. formAction: submission.formAction,
  5222. formEncType: submission.formEncType,
  5223. formData: submission.formData,
  5224. json: submission.json,
  5225. text: submission.text
  5226. };
  5227. return navigation;
  5228. } else {
  5229. let navigation = {
  5230. state: "loading",
  5231. location,
  5232. formMethod: undefined,
  5233. formAction: undefined,
  5234. formEncType: undefined,
  5235. formData: undefined,
  5236. json: undefined,
  5237. text: undefined
  5238. };
  5239. return navigation;
  5240. }
  5241. }
  5242. function getSubmittingNavigation(location, submission) {
  5243. let navigation = {
  5244. state: "submitting",
  5245. location,
  5246. formMethod: submission.formMethod,
  5247. formAction: submission.formAction,
  5248. formEncType: submission.formEncType,
  5249. formData: submission.formData,
  5250. json: submission.json,
  5251. text: submission.text
  5252. };
  5253. return navigation;
  5254. }
  5255. function getLoadingFetcher(submission, data) {
  5256. if (submission) {
  5257. let fetcher = {
  5258. state: "loading",
  5259. formMethod: submission.formMethod,
  5260. formAction: submission.formAction,
  5261. formEncType: submission.formEncType,
  5262. formData: submission.formData,
  5263. json: submission.json,
  5264. text: submission.text,
  5265. data
  5266. };
  5267. return fetcher;
  5268. } else {
  5269. let fetcher = {
  5270. state: "loading",
  5271. formMethod: undefined,
  5272. formAction: undefined,
  5273. formEncType: undefined,
  5274. formData: undefined,
  5275. json: undefined,
  5276. text: undefined,
  5277. data
  5278. };
  5279. return fetcher;
  5280. }
  5281. }
  5282. function getSubmittingFetcher(submission, existingFetcher) {
  5283. let fetcher = {
  5284. state: "submitting",
  5285. formMethod: submission.formMethod,
  5286. formAction: submission.formAction,
  5287. formEncType: submission.formEncType,
  5288. formData: submission.formData,
  5289. json: submission.json,
  5290. text: submission.text,
  5291. data: existingFetcher ? existingFetcher.data : undefined
  5292. };
  5293. return fetcher;
  5294. }
  5295. function getDoneFetcher(data) {
  5296. let fetcher = {
  5297. state: "idle",
  5298. formMethod: undefined,
  5299. formAction: undefined,
  5300. formEncType: undefined,
  5301. formData: undefined,
  5302. json: undefined,
  5303. text: undefined,
  5304. data
  5305. };
  5306. return fetcher;
  5307. }
  5308. function restoreAppliedTransitions(_window, transitions) {
  5309. try {
  5310. let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);
  5311. if (sessionPositions) {
  5312. let json = JSON.parse(sessionPositions);
  5313. for (let [k, v] of Object.entries(json || {})) {
  5314. if (v && Array.isArray(v)) {
  5315. transitions.set(k, new Set(v || []));
  5316. }
  5317. }
  5318. }
  5319. } catch (e) {
  5320. // no-op, use default empty object
  5321. }
  5322. }
  5323. function persistAppliedTransitions(_window, transitions) {
  5324. if (transitions.size > 0) {
  5325. let json = {};
  5326. for (let [k, v] of transitions) {
  5327. json[k] = [...v];
  5328. }
  5329. try {
  5330. _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));
  5331. } catch (error) {
  5332. warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ").");
  5333. }
  5334. }
  5335. }
  5336. //#endregion
  5337. exports.AbortedDeferredError = AbortedDeferredError;
  5338. exports.Action = Action;
  5339. exports.IDLE_BLOCKER = IDLE_BLOCKER;
  5340. exports.IDLE_FETCHER = IDLE_FETCHER;
  5341. exports.IDLE_NAVIGATION = IDLE_NAVIGATION;
  5342. exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL;
  5343. exports.UNSAFE_DeferredData = DeferredData;
  5344. exports.UNSAFE_ErrorResponseImpl = ErrorResponseImpl;
  5345. exports.UNSAFE_convertRouteMatchToUiMatch = convertRouteMatchToUiMatch;
  5346. exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes;
  5347. exports.UNSAFE_decodePath = decodePath;
  5348. exports.UNSAFE_getResolveToMatches = getResolveToMatches;
  5349. exports.UNSAFE_invariant = invariant;
  5350. exports.UNSAFE_warning = warning;
  5351. exports.createBrowserHistory = createBrowserHistory;
  5352. exports.createHashHistory = createHashHistory;
  5353. exports.createMemoryHistory = createMemoryHistory;
  5354. exports.createPath = createPath;
  5355. exports.createRouter = createRouter;
  5356. exports.createStaticHandler = createStaticHandler;
  5357. exports.data = data;
  5358. exports.defer = defer;
  5359. exports.generatePath = generatePath;
  5360. exports.getStaticContextFromError = getStaticContextFromError;
  5361. exports.getToPathname = getToPathname;
  5362. exports.isDataWithResponseInit = isDataWithResponseInit;
  5363. exports.isDeferredData = isDeferredData;
  5364. exports.isRouteErrorResponse = isRouteErrorResponse;
  5365. exports.joinPaths = joinPaths;
  5366. exports.json = json;
  5367. exports.matchPath = matchPath;
  5368. exports.matchRoutes = matchRoutes;
  5369. exports.normalizePathname = normalizePathname;
  5370. exports.parsePath = parsePath;
  5371. exports.redirect = redirect;
  5372. exports.redirectDocument = redirectDocument;
  5373. exports.replace = replace;
  5374. exports.resolvePath = resolvePath;
  5375. exports.resolveTo = resolveTo;
  5376. exports.stripBasename = stripBasename;
  5377. Object.defineProperty(exports, '__esModule', { value: true });
  5378. }));
  5379. //# sourceMappingURL=router.umd.js.map