UNPKG

130 kBJavaScriptView Raw
1/**
2 * react-router v8.5.3
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 */
11import { PROTOCOL_RELATIVE_URL_REGEX, normalizeProtocolRelativeUrl } from "./url.js";
12import { createBrowserURLImpl, createLocation, createPath, invariant, parsePath, warning } from "./history.js";
13import { validateNavigationTarget } from "./navigation.js";
14import { DiscoveryCancelledError, ErrorResponseImpl, RouterContextProvider, convertRouteMatchToUiMatch, convertRoutesToDataRoutes, createDataFunctionUrl, getPathContributingMatches, getResolveToMatches, getRoutePattern, isAbsoluteUrl, isRouteErrorResponse, isUnsupportedLazyRouteFunctionKey, isUnsupportedLazyRouteObjectKey, prependBasename, removeDoubleSlashes, resolveTo, stripBasename } from "./utils.js";
15import { consumeInstrumentationClientResultMetaReceiver, getRouteInstrumentationUpdates, instrumentClientSideRouter } from "./instrumentation.js";
16import { V6RegExMatcher } from "./matcher.js";
17import { getRoutePatternMatcher } from "./matcher-route-pattern.preload.js";
18//#region lib/router/router.ts
19const validMutationMethodsArr = [
20 "POST",
21 "PUT",
22 "PATCH",
23 "DELETE"
24];
25const validMutationMethods = new Set(validMutationMethodsArr);
26const validRequestMethodsArr = ["GET", ...validMutationMethodsArr];
27const validRequestMethods = new Set(validRequestMethodsArr);
28const redirectStatusCodes = new Set([
29 301,
30 302,
31 303,
32 307,
33 308
34]);
35const redirectPreserveMethodStatusCodes = new Set([307, 308]);
36const IDLE_NAVIGATION = {
37 state: "idle",
38 location: void 0,
39 matches: void 0,
40 historyAction: void 0,
41 formMethod: void 0,
42 formAction: void 0,
43 formEncType: void 0,
44 formData: void 0,
45 json: void 0,
46 text: void 0
47};
48const IDLE_FETCHER = {
49 state: "idle",
50 data: void 0,
51 formMethod: void 0,
52 formAction: void 0,
53 formEncType: void 0,
54 formData: void 0,
55 json: void 0,
56 text: void 0
57};
58const IDLE_BLOCKER = {
59 state: "unblocked",
60 proceed: void 0,
61 reset: void 0,
62 location: void 0
63};
64const TRANSITIONS_STORAGE_KEY = "remix-router-transitions";
65const ResetLoaderDataSymbol = Symbol("ResetLoaderData");
66function createDataRouteMatcher(future, basename) {
67 if (future.unstable_routePatternMatching) {
68 let RoutePatternMatcher = getRoutePatternMatcher();
69 invariant(RoutePatternMatcher, "You must call unstable_preloadRoutePattern() from \"react-router/route-pattern\" before enabling future.unstable_routePatternMatching.");
70 return new RoutePatternMatcher(basename);
71 }
72 return new V6RegExMatcher(basename);
73}
74/**
75* Encapsulates the stable and in-flight route trees together with their
76* pre-computed branch caches so the structures always stay in sync.
77*/
78var DataRoutes = class {
79 #routes;
80 #hmrRoutes;
81 #matcher;
82 constructor(routes, matcher) {
83 this.#routes = routes;
84 this.#matcher = matcher;
85 this.#matcher.update(routes);
86 }
87 /** The stable route tree */
88 get stableRoutes() {
89 return this.#routes;
90 }
91 /** The in-flight route tree if one is active, otherwise the stable tree */
92 get activeRoutes() {
93 return this.#hmrRoutes ?? this.#routes;
94 }
95 get hasHMRRoutes() {
96 return this.#hmrRoutes != null;
97 }
98 /** Replace the stable route tree and recompute its branches */
99 setRoutes(routes) {
100 this.#routes = routes;
101 if (!this.#hmrRoutes) this.#matcher.update(routes);
102 }
103 /** Set a new in-flight route tree and recompute its branches */
104 setHmrRoutes(routes) {
105 this.#hmrRoutes = routes;
106 this.#matcher.update(routes);
107 }
108 /** Commit in-flight routes/branches to the stable slot and clear in-flight */
109 commitHmrRoutes() {
110 if (this.#hmrRoutes) {
111 this.#routes = this.#hmrRoutes;
112 this.#hmrRoutes = void 0;
113 this.#matcher.update(this.#routes);
114 }
115 }
116};
117const clientErrors = /* @__PURE__ */ new WeakMap();
118/**
119* Create a router and listen to history POP navigations
120*/
121function createRouter(init) {
122 const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0;
123 const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined";
124 invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
125 let hydrationRouteProperties = init.hydrationRouteProperties || [];
126 let _mapRouteProperties = init.mapRouteProperties;
127 let mapRouteProperties = _mapRouteProperties ? _mapRouteProperties : () => ({});
128 if (init.instrumentations) {
129 let instrumentations = init.instrumentations;
130 mapRouteProperties = (route) => {
131 return {
132 ..._mapRouteProperties?.(route),
133 ...getRouteInstrumentationUpdates(instrumentations.map((i) => i.route).filter(Boolean), route)
134 };
135 };
136 }
137 let future = { ...init.future };
138 let basename = init.basename || "/";
139 if (!basename.startsWith("/")) basename = `/${basename}`;
140 let dataRouteMatcher = createDataRouteMatcher(future, basename);
141 let manifest = {};
142 let dataRoutes = new DataRoutes(convertRoutesToDataRoutes(init.routes, mapRouteProperties, void 0, manifest), dataRouteMatcher);
143 let dataStrategyImpl = init.dataStrategy || defaultDataStrategyWithMiddleware;
144 let unlistenHistory = null;
145 let subscribers = /* @__PURE__ */ new Set();
146 let savedScrollPositions = null;
147 let getScrollRestorationKey = null;
148 let getScrollPosition = null;
149 let initialScrollRestored = init.hydrationData != null;
150 let initialMatches = dataRouteMatcher.match(init.history.location);
151 let initialMatchesIsFOW = false;
152 let initialErrors = null;
153 let initialized;
154 let renderFallback;
155 if (initialMatches == null && !init.patchRoutesOnNavigation) {
156 let error = getInternalRouterError(404, { pathname: init.history.location.pathname });
157 let { matches, route } = getShortCircuitMatches(dataRoutes.activeRoutes);
158 initialized = true;
159 renderFallback = !initialized;
160 initialMatches = matches;
161 initialErrors = { [route.id]: error };
162 } else {
163 if (initialMatches && !init.hydrationData) {
164 if (checkFogOfWar(initialMatches, init.history.location.pathname).active) initialMatches = null;
165 }
166 if (!initialMatches) {
167 initialized = false;
168 renderFallback = !initialized;
169 initialMatches = [];
170 let fogOfWar = checkFogOfWar(null, init.history.location.pathname);
171 if (fogOfWar.active && fogOfWar.matches) {
172 initialMatchesIsFOW = true;
173 initialMatches = fogOfWar.matches;
174 }
175 } else if (initialMatches.some((m) => m.route.lazy)) {
176 initialized = false;
177 renderFallback = !initialized;
178 } else if (!initialMatches.some((m) => routeHasLoaderOrMiddleware(m.route))) {
179 initialized = true;
180 renderFallback = !initialized;
181 } else {
182 let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
183 let errors = init.hydrationData ? init.hydrationData.errors : null;
184 let relevantMatches = initialMatches;
185 if (errors) {
186 let idx = initialMatches.findIndex((m) => errors[m.route.id] !== void 0);
187 relevantMatches = relevantMatches.slice(0, idx + 1);
188 }
189 renderFallback = false;
190 initialized = true;
191 relevantMatches.forEach((m) => {
192 let status = getRouteHydrationStatus(m.route, loaderData, errors);
193 renderFallback = renderFallback || status.renderFallback;
194 initialized = initialized && !status.shouldLoad;
195 });
196 }
197 }
198 let router;
199 let state = {
200 historyAction: init.history.action,
201 location: init.history.location,
202 matches: initialMatches,
203 initialized,
204 renderFallback,
205 navigation: IDLE_NAVIGATION,
206 restoreScrollPosition: init.hydrationData != null ? false : null,
207 preventScrollReset: false,
208 revalidation: "idle",
209 loaderData: init.hydrationData && init.hydrationData.loaderData || {},
210 actionData: init.hydrationData && init.hydrationData.actionData || null,
211 errors: init.hydrationData && init.hydrationData.errors || initialErrors,
212 fetchers: /* @__PURE__ */ new Map(),
213 blockers: /* @__PURE__ */ new Map()
214 };
215 let pendingAction = "POP";
216 let pendingActionData;
217 let pendingPopstateDelta = 0;
218 let pendingDiscoveryCancellation;
219 let pendingPopstateNavigationDfd = null;
220 let pendingPreventScrollReset = false;
221 let pendingNavigationController;
222 let pendingViewTransitionEnabled = false;
223 let appliedViewTransitions = /* @__PURE__ */ new Map();
224 let removePageHideEventListener = null;
225 let isUninterruptedRevalidation = false;
226 let isRevalidationRequired = false;
227 let cancelledFetcherLoads = /* @__PURE__ */ new Set();
228 let fetchControllers = /* @__PURE__ */ new Map();
229 let incrementingLoadId = 0;
230 let pendingNavigationLoadId = -1;
231 let pendingNavigationDiscoverySignal = null;
232 let fetchReloadIds = /* @__PURE__ */ new Map();
233 let fetchRedirectIds = /* @__PURE__ */ new Set();
234 let fetchLoadMatches = /* @__PURE__ */ new Map();
235 let activeFetchers = /* @__PURE__ */ new Map();
236 let fetchersQueuedForDeletion = /* @__PURE__ */ new Set();
237 let blockerFunctions = /* @__PURE__ */ new Map();
238 let unblockBlockerHistoryUpdate = void 0;
239 let pendingRevalidationDfd = null;
240 function initialize() {
241 unlistenHistory = init.history.listen(({ action: historyAction, location, delta }) => {
242 if (unblockBlockerHistoryUpdate) {
243 unblockBlockerHistoryUpdate();
244 unblockBlockerHistoryUpdate = void 0;
245 return;
246 }
247 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.");
248 let blockerKey = shouldBlockNavigation({
249 currentLocation: state.location,
250 nextLocation: location,
251 historyAction
252 });
253 if (blockerKey && delta != null) {
254 let nextHistoryUpdatePromise = new Promise((resolve) => {
255 unblockBlockerHistoryUpdate = resolve;
256 });
257 init.history.go(delta * -1);
258 updateBlocker(blockerKey, {
259 state: "blocked",
260 location,
261 proceed() {
262 updateBlocker(blockerKey, {
263 state: "proceeding",
264 proceed: void 0,
265 reset: void 0,
266 location
267 });
268 nextHistoryUpdatePromise.then(() => init.history.go(delta));
269 },
270 reset() {
271 let blockers = new Map(state.blockers);
272 blockers.set(blockerKey, IDLE_BLOCKER);
273 updateState({ blockers });
274 }
275 });
276 pendingPopstateNavigationDfd?.resolve();
277 pendingPopstateNavigationDfd = null;
278 return;
279 }
280 if (future.unstable_customRouteDiscovery) pendingPopstateDelta += delta || 0;
281 return startNavigation(historyAction, location);
282 });
283 if (isBrowser) {
284 restoreAppliedTransitions(routerWindow, appliedViewTransitions);
285 let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);
286 routerWindow.addEventListener("pagehide", _saveAppliedTransitions);
287 removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions);
288 }
289 if (!state.initialized) startNavigation("POP", state.location, { initialHydration: true });
290 return router;
291 }
292 function dispose() {
293 if (unlistenHistory) unlistenHistory();
294 if (removePageHideEventListener) removePageHideEventListener();
295 subscribers.clear();
296 pendingNavigationController && pendingNavigationController.abort();
297 state.fetchers.forEach((_, key) => deleteFetcher(state.fetchers, key));
298 state.blockers.forEach((_, key) => deleteBlocker(key));
299 }
300 function subscribe(fn) {
301 subscribers.add(fn);
302 return () => subscribers.delete(fn);
303 }
304 function updateState(newState, opts = {}) {
305 let newErrors = newState.errors ?? null;
306 let cachedErrors = newErrors ? clientErrors.get(newErrors) : void 0;
307 if (cachedErrors !== void 0) newErrors = cachedErrors;
308 if (newState.errors !== void 0 || newState.initialized) {
309 if (state.errors) clientErrors.delete(state.errors);
310 if (newState.errors) clientErrors.set(newState.errors, newErrors);
311 }
312 if (newState.matches) newState.matches = newState.matches.map((m) => {
313 let route = manifest[m.route.id];
314 let matchRoute = m.route;
315 if (matchRoute.element !== route.element || matchRoute.errorElement !== route.errorElement || matchRoute.hydrateFallbackElement !== route.hydrateFallbackElement) return {
316 ...m,
317 route
318 };
319 return m;
320 });
321 state = {
322 ...state,
323 ...newState
324 };
325 let unmountedFetchers = [];
326 let mountedFetchers = [];
327 state.fetchers.forEach((fetcher, key) => {
328 if (fetcher.state === "idle") if (fetchersQueuedForDeletion.has(key)) unmountedFetchers.push(key);
329 else mountedFetchers.push(key);
330 });
331 fetchersQueuedForDeletion.forEach((key) => {
332 if (!state.fetchers.has(key) && !fetchControllers.has(key)) unmountedFetchers.push(key);
333 });
334 [...subscribers].forEach((subscriber) => subscriber(state, {
335 deletedFetchers: unmountedFetchers,
336 newErrors,
337 viewTransitionOpts: opts.viewTransitionOpts,
338 flushSync: opts.flushSync === true
339 }));
340 unmountedFetchers.forEach((key) => deleteFetcher(state.fetchers, key));
341 mountedFetchers.forEach((key) => state.fetchers.delete(key));
342 }
343 function completeNavigation(location, newState, { flushSync } = {}) {
344 let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && location.state?._isRedirect !== true;
345 let actionDataForCommit = newState.actionData || (isActionReload ? pendingActionData : void 0);
346 let actionData;
347 if (actionDataForCommit) if (Object.keys(actionDataForCommit).length > 0) actionData = actionDataForCommit;
348 else actionData = null;
349 else actionData = null;
350 let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;
351 let blockers = state.blockers;
352 if (blockers.size > 0 && !isUninterruptedRevalidation) {
353 blockers = new Map(blockers);
354 blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));
355 }
356 let restoreScrollPosition = isUninterruptedRevalidation ? false : getSavedScrollPosition(location, newState.matches || state.matches);
357 let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && location.state?._isRedirect !== true;
358 dataRoutes.commitHmrRoutes();
359 if (isUninterruptedRevalidation) {} else if (pendingAction === "POP") {} else if (pendingAction === "PUSH") init.history.push(location, location.state);
360 else if (pendingAction === "REPLACE") init.history.replace(location, location.state);
361 let viewTransitionOpts;
362 if (pendingAction === "POP" && !isUninterruptedRevalidation && location !== state.location) {
363 let priorPaths = appliedViewTransitions.get(state.location.pathname);
364 if (priorPaths && priorPaths.has(location.pathname)) viewTransitionOpts = {
365 currentLocation: state.location,
366 nextLocation: location
367 };
368 else if (appliedViewTransitions.has(location.pathname)) viewTransitionOpts = {
369 currentLocation: location,
370 nextLocation: state.location
371 };
372 } else if (pendingViewTransitionEnabled) {
373 let toPaths = appliedViewTransitions.get(state.location.pathname);
374 if (toPaths) toPaths.add(location.pathname);
375 else {
376 toPaths = new Set([location.pathname]);
377 appliedViewTransitions.set(state.location.pathname, toPaths);
378 }
379 viewTransitionOpts = {
380 currentLocation: state.location,
381 nextLocation: location
382 };
383 }
384 updateState({
385 ...newState,
386 actionData,
387 loaderData,
388 historyAction: pendingAction,
389 location,
390 initialized: true,
391 renderFallback: false,
392 navigation: IDLE_NAVIGATION,
393 revalidation: "idle",
394 restoreScrollPosition,
395 preventScrollReset,
396 blockers
397 }, {
398 viewTransitionOpts,
399 flushSync: flushSync === true
400 });
401 resetPendingNavigation();
402 pendingPopstateNavigationDfd?.resolve();
403 pendingPopstateNavigationDfd = null;
404 pendingRevalidationDfd?.resolve();
405 pendingRevalidationDfd = null;
406 }
407 function resetPendingNavigation() {
408 pendingPopstateDelta = 0;
409 pendingAction = "POP";
410 pendingActionData = void 0;
411 pendingPreventScrollReset = false;
412 pendingViewTransitionEnabled = false;
413 isUninterruptedRevalidation = false;
414 isRevalidationRequired = fetchReloadIds.size > 0;
415 }
416 async function navigate(to, opts) {
417 if (pendingDiscoveryCancellation) await pendingDiscoveryCancellation;
418 pendingPopstateNavigationDfd?.resolve();
419 pendingPopstateNavigationDfd = null;
420 if (typeof to === "number") {
421 if (!pendingPopstateNavigationDfd) pendingPopstateNavigationDfd = createDeferred();
422 let promise = pendingPopstateNavigationDfd.promise;
423 init.history.go(to);
424 return promise;
425 }
426 let instrumentationNavigateMetaReceiver = consumeInstrumentationClientResultMetaReceiver(router);
427 let { path, submission, error } = normalizeNavigateOptions(false, normalizeTo(state.location, state.matches, basename, to, opts?.fromRouteId, opts?.relative), opts);
428 let maskPath;
429 if (opts?.mask) {
430 let partialPath = typeof opts.mask === "string" ? parsePath(opts.mask) : {
431 ...state.location.mask,
432 ...opts.mask
433 };
434 maskPath = {
435 pathname: partialPath.pathname ?? "",
436 search: partialPath.search ?? "",
437 hash: partialPath.hash ?? ""
438 };
439 if (PROTOCOL_RELATIVE_URL_REGEX.test(maskPath.pathname)) throw new Error("External navigation is not allowed");
440 else if (maskPath.pathname.startsWith("\\")) maskPath.pathname = maskPath.pathname.replace(/^\\+/, "/");
441 validateNavigationTarget(typeof opts.mask === "string" ? opts.mask : createPath(opts.mask), createPath(maskPath), init.history.createURL("/"), "reject");
442 }
443 let currentLocation = state.location;
444 let nextLocation = createLocation(currentLocation, path, opts && opts.state, void 0, maskPath);
445 nextLocation = {
446 ...nextLocation,
447 ...init.history.encodeLocation(nextLocation)
448 };
449 validateNavigationTarget(to == null ? init.history.createHref(state.location) : typeof to === "string" ? to : createPath(to), init.history.createHref(nextLocation.mask || nextLocation), init.history.createURL("/"), "reject");
450 let userReplace = opts && opts.replace != null ? opts.replace : void 0;
451 let historyAction = "PUSH";
452 let currentPath = state.location.pathname + state.location.search;
453 if (userReplace === true) historyAction = "REPLACE";
454 else if (userReplace === false) {} else if (submission != null && isMutationMethod(submission.formMethod) && (submission.formAction === currentPath || nextLocation.pathname + nextLocation.search === currentPath)) historyAction = "REPLACE";
455 let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0;
456 let flushSync = (opts && opts.flushSync) === true;
457 let blockerKey = shouldBlockNavigation({
458 currentLocation,
459 nextLocation,
460 historyAction
461 });
462 if (blockerKey) {
463 updateBlocker(blockerKey, {
464 state: "blocked",
465 location: nextLocation,
466 proceed() {
467 updateBlocker(blockerKey, {
468 state: "proceeding",
469 proceed: void 0,
470 reset: void 0,
471 location: nextLocation
472 });
473 navigate(to, opts);
474 },
475 reset() {
476 let blockers = new Map(state.blockers);
477 blockers.set(blockerKey, IDLE_BLOCKER);
478 updateState({ blockers });
479 }
480 });
481 return;
482 }
483 await startNavigation(historyAction, nextLocation, {
484 submission,
485 pendingError: error,
486 preventScrollReset,
487 replace: opts && opts.replace,
488 enableViewTransition: opts && opts.viewTransition,
489 flushSync,
490 callSiteDefaultShouldRevalidate: opts && opts.defaultShouldRevalidate,
491 instrumentationNavigateMetaReceiver
492 });
493 }
494 function revalidate() {
495 if (pendingDiscoveryCancellation) return pendingDiscoveryCancellation.then(revalidate);
496 if (!pendingRevalidationDfd) pendingRevalidationDfd = createDeferred();
497 interruptActiveLoads();
498 updateState({ revalidation: "loading" });
499 let promise = pendingRevalidationDfd.promise;
500 if (state.navigation.state === "submitting") return promise;
501 if (state.navigation.state === "idle") {
502 startNavigation(state.historyAction, state.location, {
503 startUninterruptedRevalidation: true,
504 dataStrategyInitiator: "revalidation"
505 });
506 return promise;
507 }
508 startNavigation(pendingAction || state.historyAction, state.navigation.location, {
509 overrideNavigation: state.navigation,
510 dataStrategyInitiator: "revalidation",
511 enableViewTransition: pendingViewTransitionEnabled === true
512 });
513 return promise;
514 }
515 async function startNavigation(historyAction, location, opts) {
516 if (pendingDiscoveryCancellation) await pendingDiscoveryCancellation;
517 pendingNavigationController && pendingNavigationController.abort();
518 pendingNavigationController = null;
519 pendingAction = historyAction;
520 if (!opts?.overrideNavigation) pendingActionData = void 0;
521 isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;
522 saveScrollPosition(state.location, state.matches);
523 pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
524 pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;
525 let matches = opts?.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ? state.matches : dataRouteMatcher.match(location);
526 let flushSync = (opts && opts.flushSync) === true;
527 if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
528 completeNavigation(location, { matches }, { flushSync });
529 return;
530 }
531 let fogOfWar = checkFogOfWar(matches, location.pathname);
532 if (fogOfWar.active && fogOfWar.matches) matches = fogOfWar.matches;
533 if (opts?.instrumentationNavigateMetaReceiver) {
534 let meta = getInstrumentationNavigateMeta(init.history, location, matches);
535 opts.instrumentationNavigateMetaReceiver(meta);
536 }
537 if (!matches) {
538 let { error, notFoundMatches, route } = handleNavigational404(location.pathname);
539 completeNavigation(location, {
540 matches: notFoundMatches,
541 loaderData: {},
542 errors: { [route.id]: error }
543 }, { flushSync });
544 return;
545 }
546 let loadingNavigation = opts && opts.overrideNavigation ? {
547 ...opts.overrideNavigation,
548 matches,
549 historyAction
550 } : void 0;
551 pendingNavigationController = new AbortController();
552 let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
553 let dataStrategyInitiator = opts?.initialHydration ? "initialization" : opts?.dataStrategyInitiator ?? "navigation";
554 let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
555 let pendingActionResult;
556 if (opts && opts.pendingError) pendingActionResult = [findNearestBoundary(matches).route.id, {
557 type: "error",
558 error: opts.pendingError
559 }];
560 else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
561 let actionResult = await handleAction(request, dataStrategyInitiator, location, opts.submission, matches, historyAction, scopedContext, fogOfWar.active, opts && opts.initialHydration === true, {
562 replace: opts.replace,
563 flushSync
564 });
565 if (actionResult.shortCircuited) return;
566 if (actionResult.pendingActionResult) {
567 let [routeId, result] = actionResult.pendingActionResult;
568 if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {
569 pendingNavigationController = null;
570 completeNavigation(location, {
571 matches: actionResult.matches,
572 loaderData: {},
573 errors: { [routeId]: result.error }
574 });
575 return;
576 }
577 }
578 matches = actionResult.matches || matches;
579 pendingActionResult = actionResult.pendingActionResult;
580 historyAction = pendingAction;
581 loadingNavigation = getLoadingNavigation(location, matches, historyAction, opts.submission);
582 flushSync = false;
583 fogOfWar.active = false;
584 request = createClientSideRequest(init.history, request.url, request.signal);
585 }
586 if (pendingActionResult) pendingActionData = getActionDataForCommit(pendingActionResult).actionData;
587 let { shortCircuited, matches: updatedMatches, loaderData, errors, workingFetchers } = await handleLoaders(request, dataStrategyInitiator, location, matches, historyAction, scopedContext, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult, opts && opts.callSiteDefaultShouldRevalidate);
588 if (shortCircuited) return;
589 pendingNavigationController = null;
590 completeNavigation(location, {
591 matches: updatedMatches || matches,
592 ...getActionDataForCommit(pendingActionResult),
593 loaderData,
594 errors,
595 ...workingFetchers ? { fetchers: workingFetchers } : {}
596 });
597 }
598 function cancelDiscoveryNavigation() {
599 let cancellation = createDeferred();
600 pendingDiscoveryCancellation = cancellation.promise;
601 let delta = pendingPopstateDelta;
602 let popstateNavigationDfd = pendingPopstateNavigationDfd;
603 pendingPopstateNavigationDfd = null;
604 pendingNavigationController?.abort();
605 pendingNavigationController = null;
606 resetPendingNavigation();
607 pendingRevalidationDfd?.resolve();
608 pendingRevalidationDfd = null;
609 let blockers = new Map(state.blockers);
610 blockers.forEach((blocker, key) => {
611 if (blocker.state === "proceeding") blockers.set(key, IDLE_BLOCKER);
612 });
613 let fetchers = new Map(state.fetchers);
614 let didUpdateFetchers = markFetchRedirectsDone(fetchers);
615 fetchers.forEach((fetcher, key) => {
616 if (fetcher.state === "loading" && !fetchControllers.has(key)) {
617 fetchers.set(key, getDoneFetcher(fetcher.data));
618 didUpdateFetchers = true;
619 }
620 });
621 cancelledFetcherLoads.clear();
622 updateState({
623 navigation: IDLE_NAVIGATION,
624 revalidation: "idle",
625 blockers,
626 ...didUpdateFetchers ? { fetchers } : {}
627 });
628 function finishCancellation() {
629 pendingDiscoveryCancellation = void 0;
630 popstateNavigationDfd?.resolve();
631 cancellation.resolve();
632 }
633 if (delta) {
634 unblockBlockerHistoryUpdate = finishCancellation;
635 init.history.go(-delta);
636 } else finishCancellation();
637 return cancellation.promise;
638 }
639 async function handleAction(request, dataStrategyInitiator, location, submission, matches, historyAction, scopedContext, isFogOfWar, initialHydration, opts = {}) {
640 if (!future.unstable_customRouteDiscovery) interruptActiveLoads();
641 updateState({ navigation: getSubmittingNavigation(location, matches, historyAction, submission) }, { flushSync: opts.flushSync === true });
642 if (isFogOfWar) {
643 let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
644 if (future.unstable_customRouteDiscovery && request.signal.aborted || discoverResult.type === "aborted") return { shortCircuited: true };
645 else if (discoverResult.type === "cancelled") {
646 await cancelDiscoveryNavigation();
647 return { shortCircuited: true };
648 } else if (discoverResult.type === "error") {
649 if (discoverResult.partialMatches.length === 0) {
650 let { matches, route } = getShortCircuitMatches(dataRoutes.activeRoutes);
651 return {
652 matches,
653 pendingActionResult: [route.id, {
654 type: "error",
655 error: discoverResult.error
656 }]
657 };
658 }
659 let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
660 return {
661 matches: discoverResult.partialMatches,
662 pendingActionResult: [boundaryId, {
663 type: "error",
664 error: discoverResult.error
665 }]
666 };
667 } else if (!discoverResult.matches) {
668 let { notFoundMatches, error, route } = handleNavigational404(location.pathname);
669 return {
670 matches: notFoundMatches,
671 pendingActionResult: [route.id, {
672 type: "error",
673 error
674 }]
675 };
676 } else matches = discoverResult.matches;
677 }
678 if (future.unstable_customRouteDiscovery) interruptActiveLoads();
679 let result;
680 let actionMatch = getTargetMatch(matches, location);
681 if (!actionMatch.route.action && !actionMatch.route.lazy) result = {
682 type: "error",
683 error: getInternalRouterError(405, {
684 method: request.method,
685 pathname: location.pathname,
686 routeId: actionMatch.route.id
687 })
688 };
689 else {
690 let results = await callDataStrategy(request, location, getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, location, matches, actionMatch, initialHydration ? [] : hydrationRouteProperties, scopedContext), scopedContext, null, dataStrategyInitiator, historyAction);
691 result = results[actionMatch.route.id];
692 if (!result) {
693 for (let match of matches) if (results[match.route.id]) {
694 result = results[match.route.id];
695 break;
696 }
697 }
698 if (request.signal.aborted) return { shortCircuited: true };
699 }
700 if (isRedirectResult(result)) {
701 let replace;
702 if (opts && opts.replace != null) replace = opts.replace;
703 else replace = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename, init.history) === state.location.pathname + state.location.search;
704 await startRedirectNavigation(request, result, true, dataStrategyInitiator, {
705 submission,
706 replace
707 });
708 return { shortCircuited: true };
709 }
710 if (isErrorResult(result)) {
711 let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
712 if ((opts && opts.replace) !== true) pendingAction = "PUSH";
713 return {
714 matches,
715 pendingActionResult: [
716 boundaryMatch.route.id,
717 result,
718 actionMatch.route.id
719 ]
720 };
721 }
722 return {
723 matches,
724 pendingActionResult: [actionMatch.route.id, result]
725 };
726 }
727 async function handleLoaders(request, dataStrategyInitiator, location, matches, historyAction, scopedContext, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult, callSiteDefaultShouldRevalidate) {
728 let loadingNavigation = overrideNavigation || getLoadingNavigation(location, matches, historyAction, submission);
729 let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);
730 let shouldUpdateNavigationState = !isUninterruptedRevalidation && !initialHydration;
731 if (isFogOfWar) {
732 pendingNavigationDiscoverySignal = request.signal;
733 if (shouldUpdateNavigationState) {
734 let actionData = getUpdatedActionData(pendingActionResult);
735 updateState({
736 navigation: loadingNavigation,
737 ...actionData !== void 0 ? { actionData } : {}
738 }, { flushSync });
739 }
740 let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);
741 if (pendingNavigationDiscoverySignal === request.signal) pendingNavigationDiscoverySignal = null;
742 if (future.unstable_customRouteDiscovery && request.signal.aborted || discoverResult.type === "aborted") return { shortCircuited: true };
743 else if (discoverResult.type === "cancelled") {
744 await cancelDiscoveryNavigation();
745 return { shortCircuited: true };
746 } else if (discoverResult.type === "error") {
747 if (discoverResult.partialMatches.length === 0) {
748 let { matches, route } = getShortCircuitMatches(dataRoutes.activeRoutes);
749 return {
750 matches,
751 loaderData: {},
752 errors: { [route.id]: discoverResult.error }
753 };
754 }
755 let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id;
756 return {
757 matches: discoverResult.partialMatches,
758 loaderData: {},
759 errors: { [boundaryId]: discoverResult.error }
760 };
761 } else if (!discoverResult.matches) {
762 let { error, notFoundMatches, route } = handleNavigational404(location.pathname);
763 return {
764 matches: notFoundMatches,
765 loaderData: {},
766 errors: { [route.id]: error }
767 };
768 } else {
769 matches = discoverResult.matches;
770 if (initialHydration && !request.signal.aborted) updateState({ matches });
771 }
772 }
773 let { dsMatches, revalidatingFetchers } = getMatchesToLoad(request, scopedContext, mapRouteProperties, manifest, init.history, state, matches, activeSubmission, location, initialHydration ? [] : hydrationRouteProperties, initialHydration === true, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, dataRouteMatcher, pendingActionResult, callSiteDefaultShouldRevalidate);
774 pendingNavigationLoadId = ++incrementingLoadId;
775 if (!init.dataStrategy && !dsMatches.some((m) => m.shouldLoad) && !dsMatches.some((m) => m.route.middleware && m.route.middleware.length > 0) && revalidatingFetchers.length === 0) {
776 let workingFetchers = new Map(state.fetchers);
777 let didUpdateFetcherRedirects = markFetchRedirectsDone(workingFetchers);
778 completeNavigation(location, {
779 matches,
780 loaderData: {},
781 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null,
782 ...getActionDataForCommit(pendingActionResult),
783 ...didUpdateFetcherRedirects ? { fetchers: workingFetchers } : {}
784 }, { flushSync });
785 return { shortCircuited: true };
786 }
787 if (shouldUpdateNavigationState) {
788 let updates = {};
789 if (!isFogOfWar) {
790 updates.navigation = loadingNavigation;
791 let actionData = getUpdatedActionData(pendingActionResult);
792 if (actionData !== void 0) updates.actionData = actionData;
793 }
794 if (revalidatingFetchers.length > 0) updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);
795 updateState(updates, { flushSync });
796 }
797 revalidatingFetchers.forEach((rf) => {
798 abortFetcher(rf.key);
799 if (rf.controller) fetchControllers.set(rf.key, rf.controller);
800 });
801 let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => {
802 if (fetchControllers.get(rf.key) === rf.controller) abortFetcher(rf.key);
803 });
804 if (pendingNavigationController) pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations);
805 let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(dsMatches, revalidatingFetchers, request, location, scopedContext, dataStrategyInitiator, historyAction);
806 if (request.signal.aborted) return { shortCircuited: true };
807 if (pendingNavigationController) pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
808 revalidatingFetchers.forEach((rf) => {
809 if (fetchControllers.get(rf.key) === rf.controller) fetchControllers.delete(rf.key);
810 });
811 let redirect = findRedirect(loaderResults);
812 if (redirect) {
813 await startRedirectNavigation(request, redirect.result, true, dataStrategyInitiator, { replace });
814 return { shortCircuited: true };
815 }
816 redirect = findRedirect(fetcherResults);
817 if (redirect) {
818 fetchRedirectIds.add(redirect.key);
819 await startRedirectNavigation(request, redirect.result, true, dataStrategyInitiator, { replace });
820 return { shortCircuited: true };
821 }
822 let workingFetchers = new Map(state.fetchers);
823 let { loaderData, errors } = processLoaderData(state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, workingFetchers);
824 if (initialHydration && state.errors) {
825 let newClientErrors = errors ?? null;
826 errors = {
827 ...state.errors,
828 ...errors
829 };
830 clientErrors.set(errors, newClientErrors);
831 }
832 let didUpdateFetcherRedirects = markFetchRedirectsDone(workingFetchers);
833 let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId, workingFetchers);
834 let shouldUpdateFetchers = didUpdateFetcherRedirects || didAbortFetchLoads || revalidatingFetchers.length > 0;
835 return {
836 matches,
837 loaderData,
838 errors,
839 ...shouldUpdateFetchers ? { workingFetchers } : {}
840 };
841 }
842 function getUpdatedActionData(pendingActionResult) {
843 if (pendingActionResult && !isErrorResult(pendingActionResult[1])) return {
844 ...state.actionData,
845 [pendingActionResult[0]]: pendingActionResult[1].data
846 };
847 else if (state.actionData) if (Object.keys(state.actionData).length === 0) return null;
848 else return state.actionData;
849 }
850 function getUpdatedRevalidatingFetchers(revalidatingFetchers) {
851 let workingFetchers = new Map(state.fetchers);
852 revalidatingFetchers.forEach((rf) => {
853 let fetcher = workingFetchers.get(rf.key);
854 let revalidatingFetcher = getLoadingFetcher(void 0, fetcher ? fetcher.data : void 0);
855 workingFetchers.set(rf.key, revalidatingFetcher);
856 });
857 return workingFetchers;
858 }
859 async function fetch(key, routeId, href, opts) {
860 if (pendingDiscoveryCancellation) await pendingDiscoveryCancellation;
861 abortFetcher(key);
862 let flushSync = (opts && opts.flushSync) === true;
863 let instrumentationResultMetaReceiver = consumeInstrumentationClientResultMetaReceiver(router);
864 let normalizedPath = normalizeTo(state.location, state.matches, basename, href, routeId, opts?.relative);
865 validateNavigationTarget(null, normalizedPath, init.history.createURL("/"), "reject");
866 let matches = dataRouteMatcher.match(normalizedPath);
867 let fogOfWar = checkFogOfWar(matches, normalizedPath);
868 if (fogOfWar.active && fogOfWar.matches) matches = fogOfWar.matches;
869 if (instrumentationResultMetaReceiver) instrumentationResultMetaReceiver(getInstrumentationNavigateMeta(init.history, normalizedPath, matches));
870 if (!matches) {
871 setFetcherError(key, routeId, getInternalRouterError(404, { pathname: normalizedPath }), { flushSync });
872 return;
873 }
874 let { path, submission, error } = normalizeNavigateOptions(true, normalizedPath, opts);
875 if (error) {
876 setFetcherError(key, routeId, error, { flushSync });
877 return;
878 }
879 let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider();
880 let preventScrollReset = (opts && opts.preventScrollReset) === true;
881 if (submission && isMutationMethod(submission.formMethod)) {
882 await handleFetcherAction(key, routeId, path, matches, scopedContext, fogOfWar.active, flushSync, preventScrollReset, submission, opts && opts.defaultShouldRevalidate);
883 return;
884 }
885 let loadMatch = {
886 routeId,
887 path,
888 isDiscovering: fogOfWar.active
889 };
890 fetchLoadMatches.set(key, loadMatch);
891 await handleFetcherLoader(key, loadMatch, matches, scopedContext, flushSync, preventScrollReset, submission);
892 }
893 function isNavigationAwaitingDiscovery() {
894 return pendingNavigationDiscoverySignal?.aborted === false;
895 }
896 async function handleFetcherAction(key, routeId, path, requestMatches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission, callSiteDefaultShouldRevalidate) {
897 if (!future.unstable_customRouteDiscovery) interruptActiveLoads();
898 fetchLoadMatches.delete(key);
899 let existingFetcher = state.fetchers.get(key);
900 updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), { flushSync });
901 let abortController = new AbortController();
902 if (future.unstable_customRouteDiscovery) fetchControllers.set(key, abortController);
903 let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
904 if (isFogOfWar) {
905 let discoverResult = await discoverRoutes(requestMatches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
906 if (future.unstable_customRouteDiscovery && fetchRequest.signal.aborted || discoverResult.type === "aborted") return;
907 else if (discoverResult.type === "cancelled") {
908 fetchControllers.delete(key);
909 fetchLoadMatches.delete(key);
910 updateFetcherState(key, getDoneFetcher(existingFetcher?.data), { flushSync });
911 return;
912 } else if (discoverResult.type === "error") {
913 setFetcherError(key, routeId, discoverResult.error, { flushSync });
914 return;
915 } else if (!discoverResult.matches) {
916 setFetcherError(key, routeId, getInternalRouterError(404, { pathname: path }), { flushSync });
917 return;
918 } else requestMatches = discoverResult.matches;
919 }
920 let match = getTargetMatch(requestMatches, path);
921 if (!match.route.action && !match.route.lazy) {
922 setFetcherError(key, routeId, getInternalRouterError(405, {
923 method: submission.formMethod,
924 pathname: path,
925 routeId
926 }), { flushSync });
927 return;
928 }
929 if (future.unstable_customRouteDiscovery) interruptActiveLoads();
930 fetchControllers.set(key, abortController);
931 let originatingLoadId = incrementingLoadId;
932 let fetchMatches = getTargetedDataStrategyMatches(mapRouteProperties, manifest, fetchRequest, path, requestMatches, match, hydrationRouteProperties, scopedContext);
933 let actionResults = await callDataStrategy(fetchRequest, path, fetchMatches, scopedContext, key, "fetcher");
934 let actionResult = actionResults[match.route.id];
935 if (!actionResult) {
936 for (let match of fetchMatches) if (actionResults[match.route.id]) {
937 actionResult = actionResults[match.route.id];
938 break;
939 }
940 }
941 if (fetchRequest.signal.aborted) {
942 if (fetchControllers.get(key) === abortController) fetchControllers.delete(key);
943 return;
944 }
945 if (fetchersQueuedForDeletion.has(key)) {
946 if (isErrorResult(actionResult)) {
947 updateFetcherState(key, getDoneFetcher(void 0));
948 return;
949 }
950 if (isRedirectResult(actionResult)) {
951 isRevalidationRequired = true;
952 actionResult = {
953 type: "data",
954 data: void 0
955 };
956 }
957 } else {
958 if (isRedirectResult(actionResult)) if (pendingNavigationLoadId > originatingLoadId) {
959 isRevalidationRequired = true;
960 actionResult = {
961 type: "data",
962 data: void 0
963 };
964 } else {
965 fetchControllers.delete(key);
966 fetchRedirectIds.add(key);
967 updateFetcherState(key, getLoadingFetcher(submission));
968 return startRedirectNavigation(fetchRequest, actionResult, false, "fetcher", {
969 fetcherSubmission: submission,
970 preventScrollReset
971 });
972 }
973 if (isErrorResult(actionResult)) {
974 setFetcherError(key, routeId, actionResult.error);
975 return;
976 }
977 }
978 isRevalidationRequired = true;
979 let revalidationLocation = !isNavigationAwaitingDiscovery() ? state.navigation.location : void 0;
980 let nextLocation = revalidationLocation || state.location;
981 let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);
982 let matches = revalidationLocation ? dataRouteMatcher.match(revalidationLocation) : state.matches;
983 invariant(matches, "Didn't find any matches after fetcher action");
984 let loadId = ++incrementingLoadId;
985 fetchReloadIds.set(key, loadId);
986 let { dsMatches, revalidatingFetchers } = getMatchesToLoad(revalidationRequest, scopedContext, mapRouteProperties, manifest, init.history, state, matches, submission, nextLocation, hydrationRouteProperties, false, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, dataRouteMatcher, [match.route.id, actionResult], callSiteDefaultShouldRevalidate);
987 let loadFetcher = getLoadingFetcher(submission, actionResult.data);
988 let workingFetchers = new Map(state.fetchers);
989 workingFetchers.set(key, loadFetcher);
990 revalidatingFetchers.filter((rf) => rf.key !== key).forEach((rf) => {
991 let staleKey = rf.key;
992 let existingFetcher = workingFetchers.get(staleKey);
993 let revalidatingFetcher = getLoadingFetcher(void 0, existingFetcher ? existingFetcher.data : void 0);
994 workingFetchers.set(staleKey, revalidatingFetcher);
995 abortFetcher(staleKey);
996 if (rf.controller) fetchControllers.set(staleKey, rf.controller);
997 });
998 updateState({ fetchers: workingFetchers });
999 let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => {
1000 if (fetchControllers.get(rf.key) === rf.controller) abortFetcher(rf.key);
1001 });
1002 abortController.signal.addEventListener("abort", abortPendingFetchRevalidations);
1003 let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(dsMatches, revalidatingFetchers, revalidationRequest, nextLocation, scopedContext, "fetcher");
1004 if (abortController.signal.aborted) {
1005 if (fetchReloadIds.get(key) === loadId) fetchReloadIds.delete(key);
1006 return;
1007 }
1008 abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations);
1009 fetchReloadIds.delete(key);
1010 fetchControllers.delete(key);
1011 revalidatingFetchers.forEach((r) => {
1012 if (fetchControllers.get(r.key) === r.controller) fetchControllers.delete(r.key);
1013 });
1014 let fetcherIsMounted = state.fetchers.has(key);
1015 let getRedirectStateWithDoneFetcher = (s) => {
1016 if (!fetcherIsMounted) return s;
1017 let workingFetchers = new Map(s.fetchers);
1018 workingFetchers.set(key, getDoneFetcher(actionResult.data));
1019 return {
1020 ...s,
1021 fetchers: workingFetchers
1022 };
1023 };
1024 let redirect = findRedirect(loaderResults);
1025 if (redirect) {
1026 state = getRedirectStateWithDoneFetcher(state);
1027 return startRedirectNavigation(revalidationRequest, redirect.result, false, "fetcher", { preventScrollReset });
1028 }
1029 redirect = findRedirect(fetcherResults);
1030 if (redirect) {
1031 fetchRedirectIds.add(redirect.key);
1032 state = getRedirectStateWithDoneFetcher(state);
1033 return startRedirectNavigation(revalidationRequest, redirect.result, false, "fetcher", { preventScrollReset });
1034 }
1035 let finalFetchers = new Map(state.fetchers);
1036 if (fetcherIsMounted) finalFetchers.set(key, getDoneFetcher(actionResult.data));
1037 let { loaderData, errors } = processLoaderData(state, matches, loaderResults, void 0, revalidatingFetchers, fetcherResults, finalFetchers);
1038 abortStaleFetchLoads(loadId, finalFetchers);
1039 if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId && !isNavigationAwaitingDiscovery()) {
1040 invariant(pendingAction, "Expected pending action");
1041 pendingNavigationController && pendingNavigationController.abort();
1042 markFetchRedirectsDone(finalFetchers);
1043 completeNavigation(state.navigation.location, {
1044 matches,
1045 loaderData,
1046 errors,
1047 fetchers: finalFetchers
1048 });
1049 } else {
1050 updateState({
1051 errors,
1052 loaderData: mergeLoaderData(state.loaderData, loaderData, state.matches, errors),
1053 fetchers: finalFetchers
1054 });
1055 isRevalidationRequired = fetchReloadIds.size > 0;
1056 }
1057 }
1058 async function handleFetcherLoader(key, loadMatch, matches, scopedContext, flushSync, preventScrollReset, submission) {
1059 let { routeId, path } = loadMatch;
1060 let existingFetcher = state.fetchers.get(key);
1061 updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : void 0), { flushSync });
1062 let abortController = new AbortController();
1063 if (future.unstable_customRouteDiscovery) fetchControllers.set(key, abortController);
1064 let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
1065 if (loadMatch.isDiscovering) {
1066 let discoverResult = await discoverRoutes(matches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key);
1067 if (future.unstable_customRouteDiscovery && fetchRequest.signal.aborted || discoverResult.type === "aborted") return;
1068 else if (discoverResult.type === "cancelled") {
1069 fetchControllers.delete(key);
1070 fetchLoadMatches.delete(key);
1071 updateFetcherState(key, getDoneFetcher(existingFetcher?.data), { flushSync });
1072 return;
1073 } else if (discoverResult.type === "error") {
1074 setFetcherError(key, routeId, discoverResult.error, { flushSync });
1075 return;
1076 } else if (!discoverResult.matches) {
1077 setFetcherError(key, routeId, getInternalRouterError(404, { pathname: path }), { flushSync });
1078 return;
1079 } else {
1080 matches = discoverResult.matches;
1081 loadMatch.isDiscovering = false;
1082 }
1083 }
1084 let match = getTargetMatch(matches, path);
1085 fetchControllers.set(key, abortController);
1086 let originatingLoadId = incrementingLoadId;
1087 let results = await callDataStrategy(fetchRequest, path, getTargetedDataStrategyMatches(mapRouteProperties, manifest, fetchRequest, path, matches, match, hydrationRouteProperties, scopedContext), scopedContext, key, "fetcher");
1088 let result = results[match.route.id];
1089 if (!result) {
1090 for (let match of matches) if (results[match.route.id]) {
1091 result = results[match.route.id];
1092 break;
1093 }
1094 }
1095 if (fetchControllers.get(key) === abortController) fetchControllers.delete(key);
1096 if (fetchRequest.signal.aborted) return;
1097 if (fetchersQueuedForDeletion.has(key)) {
1098 updateFetcherState(key, getDoneFetcher(void 0));
1099 return;
1100 }
1101 if (isRedirectResult(result)) if (pendingNavigationLoadId > originatingLoadId) {
1102 updateFetcherState(key, getDoneFetcher(void 0));
1103 return;
1104 } else {
1105 fetchRedirectIds.add(key);
1106 await startRedirectNavigation(fetchRequest, result, false, "fetcher", { preventScrollReset });
1107 return;
1108 }
1109 if (isErrorResult(result)) {
1110 setFetcherError(key, routeId, result.error);
1111 return;
1112 }
1113 updateFetcherState(key, getDoneFetcher(result.data));
1114 }
1115 /**
1116 * Utility function to handle redirects returned from an action or loader.
1117 * Normally, a redirect "replaces" the navigation that triggered it. So, for
1118 * example:
1119 *
1120 * - user is on /a
1121 * - user clicks a link to /b
1122 * - loader for /b redirects to /c
1123 *
1124 * In a non-JS app the browser would track the in-flight navigation to /b and
1125 * then replace it with /c when it encountered the redirect response. In
1126 * the end it would only ever update the URL bar with /c.
1127 *
1128 * In client-side routing using pushState/replaceState, we aim to emulate
1129 * this behavior and we also do not update history until the end of the
1130 * navigation (including processed redirects). This means that we never
1131 * actually touch history until we've processed redirects, so we just use
1132 * the history action from the original navigation (PUSH or REPLACE).
1133 */
1134 async function startRedirectNavigation(request, redirect, isNavigation, dataStrategyInitiator, { submission, fetcherSubmission, preventScrollReset, replace } = {}) {
1135 if (!isNavigation) {
1136 pendingPopstateNavigationDfd?.resolve();
1137 pendingPopstateNavigationDfd = null;
1138 }
1139 if (redirect.response.headers.has("X-Remix-Revalidate")) isRevalidationRequired = true;
1140 let location = redirect.response.headers.get("Location");
1141 invariant(location, "Expected a Location header on the redirect Response");
1142 let originalLocation = location;
1143 let currentUrl = new URL(request.url);
1144 location = normalizeRedirectLocation(location, currentUrl, basename, init.history);
1145 validateNavigationTarget(originalLocation, location, currentUrl, "allow-explicit");
1146 let redirectLocation = createLocation(state.location, location, { _isRedirect: true });
1147 if (isBrowser) {
1148 let isDocumentReload = false;
1149 if (redirect.response.headers.has("X-Remix-Reload-Document")) isDocumentReload = true;
1150 else if (isAbsoluteUrl(location)) {
1151 const url = createBrowserURLImpl(routerWindow, location, true);
1152 isDocumentReload = url.origin !== routerWindow.location.origin || stripBasename(url.pathname, basename) == null;
1153 }
1154 if (isDocumentReload) {
1155 if (replace) routerWindow.location.replace(location);
1156 else routerWindow.location.assign(location);
1157 return;
1158 }
1159 }
1160 pendingNavigationController = null;
1161 let redirectNavigationType = replace === true || redirect.response.headers.has("X-Remix-Replace") ? "REPLACE" : "PUSH";
1162 let { formMethod, formAction, formEncType } = state.navigation;
1163 if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) submission = getSubmissionFromNavigation(state.navigation);
1164 let activeSubmission = submission || fetcherSubmission;
1165 if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) await startNavigation(redirectNavigationType, redirectLocation, {
1166 submission: {
1167 ...activeSubmission,
1168 formAction: location
1169 },
1170 preventScrollReset: preventScrollReset || pendingPreventScrollReset,
1171 enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0,
1172 dataStrategyInitiator
1173 });
1174 else await startNavigation(redirectNavigationType, redirectLocation, {
1175 overrideNavigation: getLoadingNavigation(redirectLocation, [], redirectNavigationType, submission),
1176 fetcherSubmission,
1177 preventScrollReset: preventScrollReset || pendingPreventScrollReset,
1178 enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0,
1179 dataStrategyInitiator
1180 });
1181 }
1182 async function callDataStrategy(request, path, matches, scopedContext, fetcherKey, initiator, navigationType = null) {
1183 let results;
1184 let dataResults = {};
1185 try {
1186 results = await callDataStrategyImpl(dataStrategyImpl, request, path, matches, fetcherKey, initiator, scopedContext, false, navigationType);
1187 } catch (e) {
1188 matches.filter((m) => m.shouldLoad).forEach((m) => {
1189 dataResults[m.route.id] = {
1190 type: "error",
1191 error: e
1192 };
1193 });
1194 return dataResults;
1195 }
1196 if (request.signal.aborted) return dataResults;
1197 if (!isMutationMethod(request.method)) for (let match of matches) {
1198 if (results[match.route.id]?.type === "error") break;
1199 if (!results.hasOwnProperty(match.route.id) && !state.loaderData.hasOwnProperty(match.route.id) && (!state.errors || !state.errors.hasOwnProperty(match.route.id)) && match.shouldCallHandler()) results[match.route.id] = {
1200 type: "error",
1201 result: /* @__PURE__ */ new Error(`No result returned from dataStrategy for route ${match.route.id}`)
1202 };
1203 }
1204 for (let [routeId, result] of Object.entries(results)) if (isRedirectDataStrategyResult(result)) {
1205 let response = result.result;
1206 dataResults[routeId] = {
1207 type: "redirect",
1208 response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename)
1209 };
1210 } else dataResults[routeId] = await convertDataStrategyResultToDataResult(result);
1211 return dataResults;
1212 }
1213 async function callLoadersAndMaybeResolveData(matches, fetchersToLoad, request, location, scopedContext, initiator, navigationType = null) {
1214 let loaderResultsPromise = callDataStrategy(request, location, matches, scopedContext, null, initiator, navigationType);
1215 let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async (f) => {
1216 if (f.matches && f.match && f.request && f.controller) {
1217 let result = (await callDataStrategy(f.request, f.path, f.matches, scopedContext, f.key, initiator, navigationType))[f.match.route.id];
1218 return { [f.key]: result };
1219 } else return Promise.resolve({ [f.key]: {
1220 type: "error",
1221 error: getInternalRouterError(404, { pathname: f.path })
1222 } });
1223 }));
1224 return {
1225 loaderResults: await loaderResultsPromise,
1226 fetcherResults: (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {})
1227 };
1228 }
1229 function interruptActiveLoads() {
1230 isRevalidationRequired = true;
1231 fetchLoadMatches.forEach((loadMatch, key) => {
1232 if (future.unstable_customRouteDiscovery && loadMatch.isDiscovering) return;
1233 if (fetchControllers.has(key)) cancelledFetcherLoads.add(key);
1234 abortFetcher(key);
1235 });
1236 }
1237 function updateFetcherState(key, fetcher, opts = {}) {
1238 let workingFetchers = new Map(state.fetchers);
1239 workingFetchers.set(key, fetcher);
1240 updateState({ fetchers: workingFetchers }, { flushSync: (opts && opts.flushSync) === true });
1241 }
1242 function setFetcherError(key, routeId, error, opts = {}) {
1243 let boundaryMatch = findNearestBoundary(state.matches, routeId);
1244 let workingFetchers = new Map(state.fetchers);
1245 deleteFetcher(workingFetchers, key);
1246 updateState({
1247 errors: { [boundaryMatch.route.id]: error },
1248 fetchers: workingFetchers
1249 }, { flushSync: (opts && opts.flushSync) === true });
1250 }
1251 function getFetcher(key) {
1252 activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);
1253 if (fetchersQueuedForDeletion.has(key)) fetchersQueuedForDeletion.delete(key);
1254 return state.fetchers.get(key) || IDLE_FETCHER;
1255 }
1256 function resetFetcher(key, opts) {
1257 abortFetcher(key, opts?.reason);
1258 fetchLoadMatches.delete(key);
1259 cancelledFetcherLoads.delete(key);
1260 updateFetcherState(key, getDoneFetcher(null));
1261 }
1262 function deleteFetcher(fetchers, key) {
1263 let fetcher = state.fetchers.get(key);
1264 if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) abortFetcher(key);
1265 fetchLoadMatches.delete(key);
1266 fetchReloadIds.delete(key);
1267 fetchRedirectIds.delete(key);
1268 fetchersQueuedForDeletion.delete(key);
1269 cancelledFetcherLoads.delete(key);
1270 fetchers.delete(key);
1271 }
1272 function queueFetcherForDeletion(key) {
1273 let count = (activeFetchers.get(key) || 0) - 1;
1274 if (count <= 0) {
1275 activeFetchers.delete(key);
1276 fetchersQueuedForDeletion.add(key);
1277 } else activeFetchers.set(key, count);
1278 updateState({ fetchers: new Map(state.fetchers) });
1279 }
1280 function abortFetcher(key, reason) {
1281 let controller = fetchControllers.get(key);
1282 if (controller) {
1283 controller.abort(reason);
1284 fetchControllers.delete(key);
1285 }
1286 }
1287 function markFetchersDone(keys, fetchers) {
1288 for (let key of keys) {
1289 let fetcher = fetchers.get(key);
1290 invariant(fetcher, `Expected fetcher: ${key}`);
1291 let doneFetcher = getDoneFetcher(fetcher.data);
1292 fetchers.set(key, doneFetcher);
1293 }
1294 }
1295 function markFetchRedirectsDone(fetchers) {
1296 let doneKeys = [];
1297 let didUpdateFetchers = false;
1298 for (let key of fetchRedirectIds) {
1299 let fetcher = fetchers.get(key);
1300 invariant(fetcher, `Expected fetcher: ${key}`);
1301 if (fetcher.state === "loading") {
1302 fetchRedirectIds.delete(key);
1303 doneKeys.push(key);
1304 didUpdateFetchers = true;
1305 }
1306 }
1307 markFetchersDone(doneKeys, fetchers);
1308 return didUpdateFetchers;
1309 }
1310 function abortStaleFetchLoads(landedId, fetchers) {
1311 let yeetedKeys = [];
1312 for (let [key, id] of fetchReloadIds) if (id < landedId) {
1313 let fetcher = fetchers.get(key);
1314 invariant(fetcher, `Expected fetcher: ${key}`);
1315 if (fetcher.state === "loading") {
1316 abortFetcher(key);
1317 fetchReloadIds.delete(key);
1318 yeetedKeys.push(key);
1319 }
1320 }
1321 markFetchersDone(yeetedKeys, fetchers);
1322 return yeetedKeys.length > 0;
1323 }
1324 function getBlocker(key, fn) {
1325 let blocker = state.blockers.get(key) || IDLE_BLOCKER;
1326 if (blockerFunctions.get(key) !== fn) blockerFunctions.set(key, fn);
1327 return blocker;
1328 }
1329 function deleteBlocker(key) {
1330 state.blockers.delete(key);
1331 blockerFunctions.delete(key);
1332 }
1333 function updateBlocker(key, newBlocker) {
1334 let blocker = state.blockers.get(key) || IDLE_BLOCKER;
1335 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}`);
1336 let blockers = new Map(state.blockers);
1337 blockers.set(key, newBlocker);
1338 updateState({ blockers });
1339 }
1340 function shouldBlockNavigation({ currentLocation, nextLocation, historyAction }) {
1341 if (blockerFunctions.size === 0) return;
1342 if (blockerFunctions.size > 1) warning(false, "A router only supports one blocker at a time");
1343 let entries = Array.from(blockerFunctions.entries());
1344 let [blockerKey, blockerFunction] = entries[entries.length - 1];
1345 let blocker = state.blockers.get(blockerKey);
1346 if (blocker && blocker.state === "proceeding") return;
1347 if (blockerFunction({
1348 currentLocation,
1349 nextLocation,
1350 historyAction
1351 })) return blockerKey;
1352 }
1353 function handleNavigational404(pathname) {
1354 let error = getInternalRouterError(404, { pathname });
1355 let routesToUse = dataRoutes.activeRoutes;
1356 let { matches, route } = getShortCircuitMatches(routesToUse);
1357 return {
1358 notFoundMatches: matches,
1359 route,
1360 error
1361 };
1362 }
1363 function enableScrollRestoration(positions, getPosition, getKey) {
1364 savedScrollPositions = positions;
1365 getScrollPosition = getPosition;
1366 getScrollRestorationKey = getKey || null;
1367 if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
1368 initialScrollRestored = true;
1369 let y = getSavedScrollPosition(state.location, state.matches);
1370 if (y != null) updateState({ restoreScrollPosition: y });
1371 }
1372 return () => {
1373 savedScrollPositions = null;
1374 getScrollPosition = null;
1375 getScrollRestorationKey = null;
1376 };
1377 }
1378 function getScrollKey(location, matches) {
1379 if (getScrollRestorationKey) return getScrollRestorationKey(location, matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))) || location.key;
1380 return location.key;
1381 }
1382 function saveScrollPosition(location, matches) {
1383 if (savedScrollPositions && getScrollPosition) {
1384 let key = getScrollKey(location, matches);
1385 savedScrollPositions[key] = getScrollPosition();
1386 }
1387 }
1388 function getSavedScrollPosition(location, matches) {
1389 if (savedScrollPositions) {
1390 let key = getScrollKey(location, matches);
1391 let y = savedScrollPositions[key];
1392 if (typeof y === "number") return y;
1393 }
1394 return null;
1395 }
1396 function checkFogOfWar(matches, pathname) {
1397 if (init.patchRoutesOnNavigation) {
1398 if (!matches) return {
1399 active: true,
1400 matches: dataRouteMatcher.match(pathname, true) || []
1401 };
1402 else if (Object.keys(matches[0].params).length > 0) return {
1403 active: true,
1404 matches: dataRouteMatcher.match(pathname, true)
1405 };
1406 }
1407 return {
1408 active: false,
1409 matches: null
1410 };
1411 }
1412 async function discoverRoutes(matches, pathname, signal, fetcherKey) {
1413 if (!init.patchRoutesOnNavigation) return {
1414 type: "success",
1415 matches
1416 };
1417 let partialMatches = matches;
1418 while (true) {
1419 let localManifest = manifest;
1420 try {
1421 await init.patchRoutesOnNavigation({
1422 signal,
1423 path: pathname,
1424 matches: partialMatches,
1425 fetcherKey,
1426 patch: (routeId, children) => {
1427 if (signal.aborted) return;
1428 patchRoutesImpl(routeId, children, dataRoutes, localManifest, mapRouteProperties, false);
1429 }
1430 });
1431 } catch (e) {
1432 if (future.unstable_customRouteDiscovery) {
1433 if (signal.aborted) return { type: "aborted" };
1434 if (e instanceof DiscoveryCancelledError) return { type: "cancelled" };
1435 }
1436 return {
1437 type: "error",
1438 error: e,
1439 partialMatches
1440 };
1441 }
1442 if (signal.aborted) return { type: "aborted" };
1443 let newMatches = dataRouteMatcher.match(pathname);
1444 let newPartialMatches = null;
1445 if (newMatches) if (Object.keys(newMatches[0].params).length === 0) return {
1446 type: "success",
1447 matches: newMatches
1448 };
1449 else {
1450 newPartialMatches = dataRouteMatcher.match(pathname, true);
1451 if (!(newPartialMatches && partialMatches.length < newPartialMatches.length && compareMatches(partialMatches, newPartialMatches.slice(0, partialMatches.length)))) return {
1452 type: "success",
1453 matches: newMatches
1454 };
1455 }
1456 if (!newPartialMatches) newPartialMatches = dataRouteMatcher.match(pathname, true);
1457 if (!newPartialMatches || compareMatches(partialMatches, newPartialMatches)) return {
1458 type: "success",
1459 matches: null
1460 };
1461 partialMatches = newPartialMatches;
1462 }
1463 }
1464 function compareMatches(a, b) {
1465 return a.length === b.length && a.every((m, i) => m.route.id === b[i].route.id);
1466 }
1467 function _internalSetRoutes(newRoutes) {
1468 manifest = {};
1469 dataRoutes.setHmrRoutes(convertRoutesToDataRoutes(newRoutes, mapRouteProperties, void 0, manifest));
1470 }
1471 function patchRoutes(routeId, children, unstable_allowElementMutations = false) {
1472 patchRoutesImpl(routeId, children, dataRoutes, manifest, mapRouteProperties, unstable_allowElementMutations);
1473 if (!dataRoutes.hasHMRRoutes) updateState({});
1474 }
1475 router = {
1476 get basename() {
1477 return basename;
1478 },
1479 get future() {
1480 return future;
1481 },
1482 get state() {
1483 return state;
1484 },
1485 get routes() {
1486 return dataRoutes.stableRoutes;
1487 },
1488 match(locationArg) {
1489 return dataRouteMatcher.match(locationArg);
1490 },
1491 get manifest() {
1492 return manifest;
1493 },
1494 get window() {
1495 return routerWindow;
1496 },
1497 initialize,
1498 subscribe,
1499 enableScrollRestoration,
1500 navigate,
1501 fetch,
1502 revalidate,
1503 createHref: (to) => init.history.createHref(to),
1504 createURL: (to) => init.history.createURL(to),
1505 encodeLocation: (to) => init.history.encodeLocation(to),
1506 getFetcher,
1507 resetFetcher,
1508 deleteFetcher: queueFetcherForDeletion,
1509 dispose,
1510 getBlocker,
1511 deleteBlocker,
1512 patchRoutes,
1513 _internalFetchControllers: fetchControllers,
1514 _internalSetRoutes,
1515 _internalSetStateDoNotUseOrYouWillBreakYourApp(newState) {
1516 updateState(newState);
1517 }
1518 };
1519 if (init.instrumentations) router = instrumentClientSideRouter(router, init.instrumentations.map((i) => i.router).filter(Boolean));
1520 return router;
1521}
1522/**
1523* Create a static handler to perform server-side data loading
1524*
1525* @example
1526* export async function handleRequest(request: Request) {
1527* let { query, dataRoutes } = createStaticHandler(routes);
1528* let context = await query(request);
1529*
1530* if (context instanceof Response) {
1531* return context;
1532* }
1533*
1534* let router = createStaticRouter(dataRoutes, context);
1535* return new Response(
1536* ReactDOMServer.renderToString(<StaticRouterProvider ... />),
1537* { headers: { "Content-Type": "text/html" } }
1538* );
1539* }
1540*
1541* @public
1542* @category Data Routers
1543* @mode data
1544* @param routes The {@link RouteObject | route objects} to create a static
1545* handler for
1546* @param opts Options
1547* @param opts.basename The base URL for the static handler (default: `/`)
1548* @param opts.future Future flags for the static handler
1549* @returns A static handler that can be used to query data for the provided
1550* routes
1551*/
1552function createStaticHandler(routes, opts) {
1553 invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
1554 let manifest = {};
1555 let basename = (opts ? opts.basename : null) || "/";
1556 let _mapRouteProperties = opts?.mapRouteProperties;
1557 let mapRouteProperties = _mapRouteProperties ? _mapRouteProperties : () => ({});
1558 let dataRouteMatcher = createDataRouteMatcher({ ...opts?.future }, basename);
1559 if (opts?.instrumentations) {
1560 let instrumentations = opts.instrumentations;
1561 mapRouteProperties = (route) => {
1562 return {
1563 ..._mapRouteProperties?.(route),
1564 ...getRouteInstrumentationUpdates(instrumentations.map((i) => i.route).filter(Boolean), route)
1565 };
1566 };
1567 }
1568 let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, void 0, manifest);
1569 dataRouteMatcher.update(dataRoutes);
1570 let match = (locationArg) => dataRouteMatcher.match(locationArg);
1571 /**
1572 * The query() method is intended for document requests, in which we want to
1573 * call an optional action and potentially multiple loaders for all nested
1574 * routes. It returns a StaticHandlerContext object, which is very similar
1575 * to the router state (location, loaderData, actionData, errors, etc.) and
1576 * also adds SSR-specific information such as the statusCode and headers
1577 * from action/loaders Responses.
1578 *
1579 * It _should_ never throw and should report all errors through the
1580 * returned handlerContext.errors object, properly associating errors to
1581 * their error boundary. Additionally, it tracks _deepestRenderedBoundaryId
1582 * which can be used to emulate React error boundaries during SSR by performing
1583 * a second pass only down to the boundaryId.
1584 *
1585 * The one exception where we do not return a StaticHandlerContext is when a
1586 * redirect response is returned or thrown from any action/loader. We
1587 * propagate that out and return the raw Response so the HTTP server can
1588 * return it directly.
1589 *
1590 * - `opts.requestContext` is an optional server context that will be passed
1591 * to actions/loaders in the `context` parameter
1592 * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent
1593 * the bubbling of errors which allows single-fetch-type implementations
1594 * where the client will handle the bubbling and we may need to return data
1595 * for the handling route
1596 */
1597 async function query(request, { requestContext, filterMatchesToLoad, skipLoaderErrorBubbling, skipRevalidation, dataStrategy, generateMiddlewareResponse, normalizePath } = {}) {
1598 let normalizePathImpl = normalizePath || defaultNormalizePath;
1599 let method = request.method;
1600 let location = createLocation("", normalizePathImpl(request), null, "default");
1601 let matches = dataRouteMatcher.match(location);
1602 requestContext = requestContext != null ? requestContext : new RouterContextProvider();
1603 if (!isValidMethod(method) && method !== "HEAD") {
1604 let error = getInternalRouterError(405, { method });
1605 let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
1606 let staticContext = {
1607 basename,
1608 location,
1609 matches: methodNotAllowedMatches,
1610 loaderData: {},
1611 actionData: null,
1612 errors: { [route.id]: error },
1613 statusCode: error.status,
1614 loaderHeaders: {},
1615 actionHeaders: {},
1616 _match: match
1617 };
1618 return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
1619 } else if (!matches) {
1620 let error = getInternalRouterError(404, { pathname: location.pathname });
1621 let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
1622 let staticContext = {
1623 basename,
1624 location,
1625 matches: notFoundMatches,
1626 loaderData: {},
1627 actionData: null,
1628 errors: { [route.id]: error },
1629 statusCode: error.status,
1630 loaderHeaders: {},
1631 actionHeaders: {},
1632 _match: match
1633 };
1634 return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
1635 }
1636 if (generateMiddlewareResponse) {
1637 invariant(requestContext instanceof RouterContextProvider, "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`");
1638 try {
1639 await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
1640 let renderedStaticContext;
1641 let response = await runServerMiddlewarePipeline({
1642 request,
1643 url: createDataFunctionUrl(request, location),
1644 pattern: getRoutePattern(matches),
1645 matches,
1646 params: matches[0].params,
1647 context: requestContext
1648 }, async () => {
1649 return await generateMiddlewareResponse(async (revalidationRequest, opts = {}) => {
1650 let result = await queryImpl(revalidationRequest, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null, "filterMatchesToLoad" in opts ? opts.filterMatchesToLoad ?? null : filterMatchesToLoad ?? null, skipRevalidation === true);
1651 if (isResponse(result)) return result;
1652 renderedStaticContext = {
1653 location,
1654 basename,
1655 ...result,
1656 _match: match
1657 };
1658 return renderedStaticContext;
1659 });
1660 }, async (error, routeId) => {
1661 if (isRedirectResponse(error)) return error;
1662 if (isResponse(error)) try {
1663 error = new ErrorResponseImpl(error.status, error.statusText, await parseResponseBody(error));
1664 } catch (e) {
1665 error = e;
1666 }
1667 if (isDataWithResponseInit(error)) error = dataWithResponseInitToErrorResponse(error);
1668 if (renderedStaticContext) {
1669 if (routeId in renderedStaticContext.loaderData) renderedStaticContext.loaderData[routeId] = void 0;
1670 let staticContext = getStaticContextFromError(dataRoutes, renderedStaticContext, error, skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id);
1671 return generateMiddlewareResponse(() => Promise.resolve(staticContext));
1672 } else {
1673 let staticContext = {
1674 matches,
1675 location,
1676 basename,
1677 loaderData: {},
1678 actionData: null,
1679 errors: { [skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, matches.find((m) => m.route.id === routeId || m.route.loader)?.route.id || routeId).route.id]: error },
1680 statusCode: isRouteErrorResponse(error) ? error.status : 500,
1681 actionHeaders: {},
1682 loaderHeaders: {},
1683 _match: match
1684 };
1685 return generateMiddlewareResponse(() => Promise.resolve(staticContext));
1686 }
1687 });
1688 invariant(isResponse(response), "Expected a response in query()");
1689 return response;
1690 } catch (e) {
1691 if (isResponse(e)) return e;
1692 throw e;
1693 }
1694 }
1695 let result = await queryImpl(request, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null, filterMatchesToLoad || null, skipRevalidation === true);
1696 if (isResponse(result)) return result;
1697 return {
1698 location,
1699 basename,
1700 ...result,
1701 _match: match
1702 };
1703 }
1704 /**
1705 * The queryRoute() method is intended for targeted route requests, either
1706 * for fetch ?_data requests or resource route requests. In this case, we
1707 * are only ever calling a single action or loader, and we are returning the
1708 * returned value directly. In most cases, this will be a Response returned
1709 * from the action/loader, but it may be a primitive or other value as well -
1710 * and in such cases the calling context should handle that accordingly.
1711 *
1712 * We do respect the throw/return differentiation, so if an action/loader
1713 * throws, then this method will throw the value. This is important so we
1714 * can do proper boundary identification in Remix where a thrown Response
1715 * must go to the Catch Boundary but a returned Response is happy-path.
1716 *
1717 * One thing to note is that any Router-initiated Errors that make sense
1718 * to associate with a status code will be thrown as an ErrorResponse
1719 * instance which include the raw Error, such that the calling context can
1720 * serialize the error as they see fit while including the proper response
1721 * code. Examples here are 404 and 405 errors that occur prior to reaching
1722 * any user-defined loaders.
1723 *
1724 * - `opts.routeId` allows you to specify the specific route handler to call.
1725 * If not provided the handler will determine the proper route by matching
1726 * against `request.url`
1727 * - `opts.requestContext` is an optional server context that will be passed
1728 * to actions/loaders in the `context` parameter
1729 */
1730 async function queryRoute(request, { routeId, requestContext, dataStrategy, generateMiddlewareResponse, normalizePath } = {}) {
1731 let normalizePathImpl = normalizePath || defaultNormalizePath;
1732 let method = request.method;
1733 let location = createLocation("", normalizePathImpl(request), null, "default");
1734 let matches = dataRouteMatcher.match(location);
1735 requestContext = requestContext != null ? requestContext : new RouterContextProvider();
1736 if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") throw getInternalRouterError(405, { method });
1737 else if (!matches) throw getInternalRouterError(404, { pathname: location.pathname });
1738 let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
1739 if (routeId && !match) throw getInternalRouterError(403, {
1740 pathname: location.pathname,
1741 routeId
1742 });
1743 else if (!match) throw getInternalRouterError(404, { pathname: location.pathname });
1744 if (generateMiddlewareResponse) {
1745 invariant(requestContext instanceof RouterContextProvider, "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`");
1746 await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
1747 return await runServerMiddlewarePipeline({
1748 request,
1749 url: createDataFunctionUrl(request, location),
1750 pattern: getRoutePattern(matches),
1751 matches,
1752 params: matches[0].params,
1753 context: requestContext
1754 }, async () => {
1755 return await generateMiddlewareResponse(async (innerRequest) => {
1756 let processed = handleQueryResult(await queryImpl(innerRequest, location, matches, requestContext, dataStrategy || null, false, match, null, false));
1757 return isResponse(processed) ? processed : typeof processed === "string" ? new Response(processed) : Response.json(processed);
1758 });
1759 }, (error) => {
1760 if (isDataWithResponseInit(error)) return Promise.resolve(dataWithResponseInitToResponse(error));
1761 if (isResponse(error)) return Promise.resolve(error);
1762 throw error;
1763 });
1764 }
1765 return handleQueryResult(await queryImpl(request, location, matches, requestContext, dataStrategy || null, false, match, null, false));
1766 function handleQueryResult(result) {
1767 if (isResponse(result)) return result;
1768 let error = result.errors ? Object.values(result.errors)[0] : void 0;
1769 if (error !== void 0) throw error;
1770 if (result.actionData) return Object.values(result.actionData)[0];
1771 if (result.loaderData) return Object.values(result.loaderData)[0];
1772 }
1773 }
1774 async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
1775 invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
1776 try {
1777 if (isMutationMethod(request.method)) return await submit(request, location, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null, filterMatchesToLoad, skipRevalidation);
1778 let result = await loadRouteData(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad);
1779 return isResponse(result) ? result : {
1780 ...result,
1781 actionData: null,
1782 actionHeaders: {}
1783 };
1784 } catch (e) {
1785 if (isDataStrategyResult(e) && isResponse(e.result)) {
1786 if (e.type === "error") throw e.result;
1787 return e.result;
1788 }
1789 if (isRedirectResponse(e)) return e;
1790 throw e;
1791 }
1792 }
1793 async function submit(request, location, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
1794 let result;
1795 if (!actionMatch.route.action && !actionMatch.route.lazy) {
1796 let error = getInternalRouterError(405, {
1797 method: request.method,
1798 pathname: new URL(request.url).pathname,
1799 routeId: actionMatch.route.id
1800 });
1801 if (isRouteRequest) throw error;
1802 result = {
1803 type: "error",
1804 error
1805 };
1806 } else {
1807 result = (await callDataStrategy(request, location, getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, location, matches, actionMatch, [], requestContext), isRouteRequest, requestContext, dataStrategy))[actionMatch.route.id];
1808 if (request.signal.aborted) throwStaticHandlerAbortedError(request, isRouteRequest);
1809 }
1810 if (isRedirectResult(result)) throw new Response(null, {
1811 status: result.response.status,
1812 headers: { Location: result.response.headers.get("Location") }
1813 });
1814 if (isRouteRequest) {
1815 if (isErrorResult(result)) throw result.error;
1816 return {
1817 matches: [actionMatch],
1818 loaderData: {},
1819 actionData: { [actionMatch.route.id]: result.data },
1820 errors: null,
1821 statusCode: 200,
1822 loaderHeaders: {},
1823 actionHeaders: {}
1824 };
1825 }
1826 if (skipRevalidation) if (isErrorResult(result)) {
1827 let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
1828 return {
1829 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1830 actionData: null,
1831 actionHeaders: { ...result.headers ? { [actionMatch.route.id]: result.headers } : {} },
1832 matches,
1833 loaderData: {},
1834 errors: { [boundaryMatch.route.id]: result.error },
1835 loaderHeaders: {}
1836 };
1837 } else return {
1838 actionData: { [actionMatch.route.id]: result.data },
1839 actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
1840 matches,
1841 loaderData: {},
1842 errors: null,
1843 statusCode: result.statusCode || 200,
1844 loaderHeaders: {}
1845 };
1846 let loaderRequest = new Request(request.url, {
1847 headers: request.headers,
1848 redirect: request.redirect,
1849 signal: request.signal
1850 });
1851 if (isErrorResult(result)) return {
1852 ...await loadRouteData(loaderRequest, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, filterMatchesToLoad, [(skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id)).route.id, result]),
1853 statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1854 actionData: null,
1855 actionHeaders: { ...result.headers ? { [actionMatch.route.id]: result.headers } : {} }
1856 };
1857 return {
1858 ...await loadRouteData(loaderRequest, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, filterMatchesToLoad),
1859 actionData: { [actionMatch.route.id]: result.data },
1860 ...result.statusCode ? { statusCode: result.statusCode } : {},
1861 actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
1862 };
1863 }
1864 async function loadRouteData(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
1865 let isRouteRequest = routeMatch != null;
1866 if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) throw getInternalRouterError(400, {
1867 method: request.method,
1868 pathname: new URL(request.url).pathname,
1869 routeId: routeMatch?.route.id
1870 });
1871 let dsMatches;
1872 if (routeMatch) dsMatches = getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, location, matches, routeMatch, [], requestContext);
1873 else {
1874 let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1 : void 0;
1875 let pattern = getRoutePattern(matches);
1876 dsMatches = matches.map((match, index) => {
1877 if (maxIdx != null && index > maxIdx) return getDataStrategyMatch(mapRouteProperties, manifest, request, location, pattern, match, [], requestContext, false);
1878 return getDataStrategyMatch(mapRouteProperties, manifest, request, location, pattern, match, [], requestContext, (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match)));
1879 });
1880 }
1881 if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) return {
1882 matches,
1883 loaderData: {},
1884 errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null,
1885 statusCode: 200,
1886 loaderHeaders: {}
1887 };
1888 let results = await callDataStrategy(request, location, dsMatches, isRouteRequest, requestContext, dataStrategy);
1889 if (request.signal.aborted) throwStaticHandlerAbortedError(request, isRouteRequest);
1890 return {
1891 ...processRouteLoaderData(matches, results, pendingActionResult, true, skipLoaderErrorBubbling),
1892 matches
1893 };
1894 }
1895 async function callDataStrategy(request, location, matches, isRouteRequest, requestContext, dataStrategy) {
1896 let results = await callDataStrategyImpl(dataStrategy || defaultDataStrategy, request, location, matches, null, "static", requestContext, true);
1897 let dataResults = {};
1898 await Promise.all(matches.map(async (match) => {
1899 if (!(match.route.id in results)) return;
1900 let result = results[match.route.id];
1901 if (isRedirectDataStrategyResult(result)) {
1902 let response = result.result;
1903 throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename);
1904 }
1905 if (isRouteRequest) {
1906 if (isResponse(result.result)) throw result;
1907 else if (isDataWithResponseInit(result.result)) throw dataWithResponseInitToResponse(result.result);
1908 }
1909 dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
1910 }));
1911 return dataResults;
1912 }
1913 return {
1914 dataRoutes,
1915 get _matchCost() {
1916 return dataRouteMatcher instanceof V6RegExMatcher ? dataRouteMatcher.matchCost : void 0;
1917 },
1918 match,
1919 query,
1920 queryRoute
1921 };
1922}
1923/**
1924* Given an existing StaticHandlerContext and an error thrown at render time,
1925* provide an updated StaticHandlerContext suitable for a second SSR render
1926*
1927* @category Utils
1928*/
1929function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
1930 let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
1931 return {
1932 ...handlerContext,
1933 statusCode: isRouteErrorResponse(error) ? error.status : 500,
1934 errors: { [errorBoundaryId]: error }
1935 };
1936}
1937function throwStaticHandlerAbortedError(request, isRouteRequest) {
1938 if (request.signal.reason !== void 0) throw request.signal.reason;
1939 throw new Error(`${isRouteRequest ? "queryRoute" : "query"}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`);
1940}
1941function isSubmissionNavigation(opts) {
1942 return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0);
1943}
1944function defaultNormalizePath(request) {
1945 let url = new URL(request.url);
1946 return {
1947 pathname: url.pathname,
1948 search: url.search,
1949 hash: url.hash
1950 };
1951}
1952function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
1953 let contextualMatches;
1954 let activeRouteMatch;
1955 if (fromRouteId) {
1956 contextualMatches = [];
1957 for (let match of matches) {
1958 contextualMatches.push(match);
1959 if (match.route.id === fromRouteId) {
1960 activeRouteMatch = match;
1961 break;
1962 }
1963 }
1964 } else {
1965 contextualMatches = matches;
1966 activeRouteMatch = matches[matches.length - 1];
1967 }
1968 let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches), stripBasename(location.pathname, basename) || location.pathname, relative === "path");
1969 if (to == null) {
1970 path.search = location.search;
1971 path.hash = location.hash;
1972 }
1973 if ((to == null || to === "" || to === ".") && activeRouteMatch) {
1974 let nakedIndex = hasNakedIndexQuery(path.search);
1975 if (activeRouteMatch.route.index && !nakedIndex) path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1976 else if (!activeRouteMatch.route.index && nakedIndex) {
1977 let params = new URLSearchParams(path.search);
1978 let indexValues = params.getAll("index");
1979 params.delete("index");
1980 indexValues.filter((v) => v).forEach((v) => params.append("index", v));
1981 let qs = params.toString();
1982 path.search = qs ? `?${qs}` : "";
1983 }
1984 }
1985 if (basename !== "/") path.pathname = prependBasename({
1986 basename,
1987 pathname: path.pathname
1988 });
1989 return createPath(path);
1990}
1991function normalizeNavigateOptions(isFetcher, path, opts) {
1992 if (!opts || !isSubmissionNavigation(opts)) return { path };
1993 if (opts.formMethod && !isValidMethod(opts.formMethod)) return {
1994 path,
1995 error: getInternalRouterError(405, { method: opts.formMethod })
1996 };
1997 let getInvalidBodyError = () => ({
1998 path,
1999 error: getInternalRouterError(400, { type: "invalid-body" })
2000 });
2001 let formMethod = (opts.formMethod || "get").toUpperCase();
2002 let formAction = stripHashFromPath(path);
2003 if (opts.body !== void 0) {
2004 if (opts.formEncType === "text/plain") {
2005 if (!isMutationMethod(formMethod)) return getInvalidBodyError();
2006 let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? Array.from(opts.body.entries()).reduce((acc, [name, value]) => `${acc}${name}=${value}\n`, "") : String(opts.body);
2007 return {
2008 path,
2009 submission: {
2010 formMethod,
2011 formAction,
2012 formEncType: opts.formEncType,
2013 formData: void 0,
2014 json: void 0,
2015 text
2016 }
2017 };
2018 } else if (opts.formEncType === "application/json") {
2019 if (!isMutationMethod(formMethod)) return getInvalidBodyError();
2020 try {
2021 let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body;
2022 return {
2023 path,
2024 submission: {
2025 formMethod,
2026 formAction,
2027 formEncType: opts.formEncType,
2028 formData: void 0,
2029 json,
2030 text: void 0
2031 }
2032 };
2033 } catch {
2034 return getInvalidBodyError();
2035 }
2036 }
2037 }
2038 invariant(typeof FormData === "function", "FormData is not available in this environment");
2039 let searchParams;
2040 let formData;
2041 if (opts.formData) {
2042 searchParams = convertFormDataToSearchParams(opts.formData);
2043 formData = opts.formData;
2044 } else if (opts.body instanceof FormData) {
2045 searchParams = convertFormDataToSearchParams(opts.body);
2046 formData = opts.body;
2047 } else if (opts.body instanceof URLSearchParams) {
2048 searchParams = opts.body;
2049 formData = convertSearchParamsToFormData(searchParams);
2050 } else if (opts.body == null) {
2051 searchParams = new URLSearchParams();
2052 formData = new FormData();
2053 } else try {
2054 searchParams = new URLSearchParams(opts.body);
2055 formData = convertSearchParamsToFormData(searchParams);
2056 } catch {
2057 return getInvalidBodyError();
2058 }
2059 let submission = {
2060 formMethod,
2061 formAction,
2062 formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
2063 formData,
2064 json: void 0,
2065 text: void 0
2066 };
2067 if (isMutationMethod(submission.formMethod)) return {
2068 path,
2069 submission
2070 };
2071 let parsedPath = parsePath(path);
2072 if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) searchParams.append("index", "");
2073 parsedPath.search = `?${searchParams}`;
2074 return {
2075 path: createPath(parsedPath),
2076 submission
2077 };
2078}
2079function getMatchesToLoad(request, scopedContext, mapRouteProperties, manifest, history, state, matches, submission, location, lazyRoutePropertiesToSkip, initialHydration, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, dataRouteMatcher, pendingActionResult, callSiteDefaultShouldRevalidate) {
2080 let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : void 0;
2081 let currentUrl = history.createURL(state.location);
2082 let nextUrl = history.createURL(location);
2083 let maxIdx;
2084 if (initialHydration && state.errors) {
2085 let boundaryId = Object.keys(state.errors)[0];
2086 maxIdx = matches.findIndex((m) => m.route.id === boundaryId);
2087 } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) {
2088 let boundaryId = pendingActionResult[0];
2089 maxIdx = matches.findIndex((m) => m.route.id === boundaryId) - 1;
2090 }
2091 let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : void 0;
2092 let shouldSkipRevalidation = actionStatus && actionStatus >= 400;
2093 let baseShouldRevalidateArgs = {
2094 currentUrl,
2095 currentParams: state.matches[0]?.params || {},
2096 nextUrl,
2097 nextParams: matches[0].params,
2098 ...submission,
2099 actionResult,
2100 actionStatus
2101 };
2102 let pattern = getRoutePattern(matches);
2103 let dsMatches = matches.map((match, index) => {
2104 let { route } = match;
2105 let forceShouldLoad = null;
2106 if (maxIdx != null && index > maxIdx) forceShouldLoad = false;
2107 else if (route.lazy) forceShouldLoad = true;
2108 else if (!routeHasLoaderOrMiddleware(route)) forceShouldLoad = false;
2109 else if (initialHydration) {
2110 let { shouldLoad } = getRouteHydrationStatus(route, state.loaderData, state.errors);
2111 forceShouldLoad = shouldLoad;
2112 } else if (isNewLoader(state.loaderData, state.matches[index], match)) forceShouldLoad = true;
2113 if (forceShouldLoad !== null) return getDataStrategyMatch(mapRouteProperties, manifest, request, location, pattern, match, lazyRoutePropertiesToSkip, scopedContext, forceShouldLoad);
2114 let defaultShouldRevalidate = false;
2115 if (typeof callSiteDefaultShouldRevalidate === "boolean") defaultShouldRevalidate = callSiteDefaultShouldRevalidate;
2116 else if (shouldSkipRevalidation) defaultShouldRevalidate = false;
2117 else if (isRevalidationRequired) defaultShouldRevalidate = true;
2118 else if (currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search) defaultShouldRevalidate = true;
2119 else if (currentUrl.search !== nextUrl.search) defaultShouldRevalidate = true;
2120 else if (isNewRouteInstance(state.matches[index], match)) defaultShouldRevalidate = true;
2121 let shouldRevalidateArgs = {
2122 ...baseShouldRevalidateArgs,
2123 defaultShouldRevalidate
2124 };
2125 return getDataStrategyMatch(mapRouteProperties, manifest, request, location, pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateLoader(match, shouldRevalidateArgs), shouldRevalidateArgs, callSiteDefaultShouldRevalidate);
2126 });
2127 let revalidatingFetchers = [];
2128 fetchLoadMatches.forEach((f, key) => {
2129 if (initialHydration || !matches.some((m) => m.route.id === f.routeId) || fetchersQueuedForDeletion.has(key) || f.isDiscovering) return;
2130 let fetcher = state.fetchers.get(key);
2131 let isMidInitialLoad = fetcher && fetcher.state !== "idle" && fetcher.data === void 0;
2132 let fetcherMatches = dataRouteMatcher.match(f.path);
2133 if (!fetcherMatches) {
2134 revalidatingFetchers.push({
2135 key,
2136 routeId: f.routeId,
2137 path: f.path,
2138 matches: null,
2139 match: null,
2140 request: null,
2141 controller: null
2142 });
2143 return;
2144 }
2145 if (fetchRedirectIds.has(key)) return;
2146 let fetcherMatch = getTargetMatch(fetcherMatches, f.path);
2147 let fetchController = new AbortController();
2148 let fetchRequest = createClientSideRequest(history, f.path, fetchController.signal);
2149 let fetcherDsMatches = null;
2150 if (cancelledFetcherLoads.has(key)) {
2151 cancelledFetcherLoads.delete(key);
2152 fetcherDsMatches = getTargetedDataStrategyMatches(mapRouteProperties, manifest, fetchRequest, f.path, fetcherMatches, fetcherMatch, lazyRoutePropertiesToSkip, scopedContext);
2153 } else if (isMidInitialLoad) {
2154 if (isRevalidationRequired) fetcherDsMatches = getTargetedDataStrategyMatches(mapRouteProperties, manifest, fetchRequest, f.path, fetcherMatches, fetcherMatch, lazyRoutePropertiesToSkip, scopedContext);
2155 } else {
2156 let defaultShouldRevalidate;
2157 if (typeof callSiteDefaultShouldRevalidate === "boolean") defaultShouldRevalidate = callSiteDefaultShouldRevalidate;
2158 else if (shouldSkipRevalidation) defaultShouldRevalidate = false;
2159 else defaultShouldRevalidate = isRevalidationRequired;
2160 let shouldRevalidateArgs = {
2161 ...baseShouldRevalidateArgs,
2162 defaultShouldRevalidate
2163 };
2164 if (shouldRevalidateLoader(fetcherMatch, shouldRevalidateArgs)) fetcherDsMatches = getTargetedDataStrategyMatches(mapRouteProperties, manifest, fetchRequest, f.path, fetcherMatches, fetcherMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs);
2165 }
2166 if (fetcherDsMatches) revalidatingFetchers.push({
2167 key,
2168 routeId: f.routeId,
2169 path: f.path,
2170 matches: fetcherDsMatches,
2171 match: fetcherMatch,
2172 request: fetchRequest,
2173 controller: fetchController
2174 });
2175 });
2176 return {
2177 dsMatches,
2178 revalidatingFetchers
2179 };
2180}
2181function routeHasLoaderOrMiddleware(route) {
2182 return route.loader != null || route.middleware != null && route.middleware.length > 0;
2183}
2184function getRouteHydrationStatus(route, loaderData, errors) {
2185 if (route.lazy) return {
2186 shouldLoad: true,
2187 renderFallback: true
2188 };
2189 if (!routeHasLoaderOrMiddleware(route)) return {
2190 shouldLoad: false,
2191 renderFallback: false
2192 };
2193 let hasData = loaderData != null && route.id in loaderData;
2194 let hasError = errors != null && errors[route.id] !== void 0;
2195 if (!hasData && hasError) return {
2196 shouldLoad: false,
2197 renderFallback: false
2198 };
2199 if (typeof route.loader === "function" && route.loader.hydrate === true) return {
2200 shouldLoad: true,
2201 renderFallback: !hasData
2202 };
2203 let shouldLoad = !hasData && !hasError;
2204 return {
2205 shouldLoad,
2206 renderFallback: shouldLoad
2207 };
2208}
2209function isNewLoader(currentLoaderData, currentMatch, match) {
2210 let isNew = !currentMatch || match.route.id !== currentMatch.route.id;
2211 let isMissingData = !currentLoaderData.hasOwnProperty(match.route.id);
2212 return isNew || isMissingData;
2213}
2214function isNewRouteInstance(currentMatch, match) {
2215 let currentPath = currentMatch.route.path;
2216 return currentMatch.pathname !== match.pathname || currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"];
2217}
2218function shouldRevalidateLoader(loaderMatch, arg) {
2219 if (loaderMatch.route.shouldRevalidate) {
2220 let routeChoice = loaderMatch.route.shouldRevalidate(arg);
2221 if (typeof routeChoice === "boolean") return routeChoice;
2222 }
2223 return arg.defaultShouldRevalidate;
2224}
2225function patchRoutesImpl(routeId, children, dataRoutes, manifest, mapRouteProperties, allowElementMutations) {
2226 let childrenToPatch;
2227 if (routeId) {
2228 let route = manifest[routeId];
2229 invariant(route, `No route found to patch children into: routeId = ${routeId}`);
2230 if (!route.children) route.children = [];
2231 childrenToPatch = route.children;
2232 } else childrenToPatch = dataRoutes.activeRoutes;
2233 let uniqueChildren = [];
2234 let existingChildren = [];
2235 children.forEach((newRoute) => {
2236 let existingRoute = childrenToPatch.find((existingRoute) => isSameRoute(newRoute, existingRoute));
2237 if (existingRoute) existingChildren.push({
2238 existingRoute,
2239 newRoute
2240 });
2241 else uniqueChildren.push(newRoute);
2242 });
2243 if (uniqueChildren.length > 0) {
2244 let newRoutes = convertRoutesToDataRoutes(uniqueChildren, mapRouteProperties, [
2245 routeId || "_",
2246 "patch",
2247 String(childrenToPatch?.length || "0")
2248 ], manifest);
2249 childrenToPatch.push(...newRoutes);
2250 }
2251 if (allowElementMutations && existingChildren.length > 0) for (let i = 0; i < existingChildren.length; i++) {
2252 let { existingRoute, newRoute } = existingChildren[i];
2253 let existingRouteTyped = existingRoute;
2254 let [newRouteTyped] = convertRoutesToDataRoutes([newRoute], mapRouteProperties, [], {}, true);
2255 Object.assign(existingRouteTyped, {
2256 element: newRouteTyped.element ? newRouteTyped.element : existingRouteTyped.element,
2257 errorElement: newRouteTyped.errorElement ? newRouteTyped.errorElement : existingRouteTyped.errorElement,
2258 hydrateFallbackElement: newRouteTyped.hydrateFallbackElement ? newRouteTyped.hydrateFallbackElement : existingRouteTyped.hydrateFallbackElement
2259 });
2260 }
2261 if (!dataRoutes.hasHMRRoutes) dataRoutes.setRoutes([...dataRoutes.activeRoutes]);
2262}
2263function isSameRoute(newRoute, existingRoute) {
2264 if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) return true;
2265 if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) return false;
2266 if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) return true;
2267 return newRoute.children?.every((aChild, i) => existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild))) ?? false;
2268}
2269const lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
2270const loadLazyRouteProperty = ({ key, route, manifest, mapRouteProperties }) => {
2271 let routeToUpdate = manifest[route.id];
2272 invariant(routeToUpdate, "No route found in manifest");
2273 if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") return;
2274 let lazyFn = routeToUpdate.lazy[key];
2275 if (!lazyFn) return;
2276 let cache = lazyRoutePropertyCache.get(routeToUpdate);
2277 if (!cache) {
2278 cache = {};
2279 lazyRoutePropertyCache.set(routeToUpdate, cache);
2280 }
2281 let cachedPromise = cache[key];
2282 if (cachedPromise) return cachedPromise;
2283 let propertyPromise = (async () => {
2284 let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
2285 let isStaticallyDefined = routeToUpdate[key] !== void 0;
2286 if (isUnsupported) {
2287 warning(!isUnsupported, "Route property " + key + " is not a supported lazy route property. This property will be ignored.");
2288 cache[key] = Promise.resolve();
2289 } else if (isStaticallyDefined) warning(false, `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`);
2290 else {
2291 let value = await lazyFn();
2292 if (value != null) {
2293 Object.assign(routeToUpdate, { [key]: value });
2294 Object.assign(routeToUpdate, mapRouteProperties(routeToUpdate));
2295 }
2296 }
2297 if (typeof routeToUpdate.lazy === "object") {
2298 routeToUpdate.lazy[key] = void 0;
2299 if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) routeToUpdate.lazy = void 0;
2300 }
2301 })();
2302 cache[key] = propertyPromise;
2303 propertyPromise.catch(() => {
2304 if (cache[key] === propertyPromise) delete cache[key];
2305 });
2306 return propertyPromise;
2307};
2308const lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
2309/**
2310* Execute route.lazy functions to lazily load route modules (loader, action,
2311* shouldRevalidate) and update the routeManifest in place which shares objects
2312* with dataRoutes so those get updated as well.
2313*/
2314function loadLazyRoute(route, type, manifest, mapRouteProperties, lazyRoutePropertiesToSkip) {
2315 let routeToUpdate = manifest[route.id];
2316 invariant(routeToUpdate, "No route found in manifest");
2317 if (!route.lazy) return {
2318 lazyRoutePromise: void 0,
2319 lazyHandlerPromise: void 0
2320 };
2321 if (typeof route.lazy === "function") {
2322 let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
2323 if (cachedPromise) return {
2324 lazyRoutePromise: cachedPromise,
2325 lazyHandlerPromise: cachedPromise
2326 };
2327 let lazyRoutePromise = (async () => {
2328 invariant(typeof route.lazy === "function", "No lazy route function found");
2329 let lazyRoute = await route.lazy();
2330 let routeUpdates = {};
2331 for (let lazyRouteProperty in lazyRoute) {
2332 let lazyValue = lazyRoute[lazyRouteProperty];
2333 if (lazyValue === void 0) continue;
2334 let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
2335 let isStaticallyDefined = routeToUpdate[lazyRouteProperty] !== void 0;
2336 if (isUnsupported) warning(!isUnsupported, "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored.");
2337 else if (isStaticallyDefined) warning(!isStaticallyDefined, `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.`);
2338 else routeUpdates[lazyRouteProperty] = lazyValue;
2339 }
2340 Object.assign(routeToUpdate, routeUpdates);
2341 Object.assign(routeToUpdate, {
2342 ...mapRouteProperties(routeToUpdate),
2343 lazy: void 0
2344 });
2345 })();
2346 lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise);
2347 lazyRoutePromise.catch(() => {
2348 if (lazyRouteFunctionCache.get(routeToUpdate) === lazyRoutePromise) lazyRouteFunctionCache.delete(routeToUpdate);
2349 });
2350 return {
2351 lazyRoutePromise,
2352 lazyHandlerPromise: lazyRoutePromise
2353 };
2354 }
2355 let lazyKeys = Object.keys(route.lazy);
2356 let lazyPropertyPromises = [];
2357 let lazyHandlerPromise = void 0;
2358 for (let key of lazyKeys) {
2359 if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) continue;
2360 let promise = loadLazyRouteProperty({
2361 key,
2362 route,
2363 manifest,
2364 mapRouteProperties
2365 });
2366 if (promise) {
2367 lazyPropertyPromises.push(promise);
2368 if (key === type) lazyHandlerPromise = promise;
2369 }
2370 }
2371 let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {}) : void 0;
2372 lazyRoutePromise?.catch(() => {});
2373 lazyHandlerPromise?.catch(() => {});
2374 return {
2375 lazyRoutePromise,
2376 lazyHandlerPromise
2377 };
2378}
2379function isNonNullable(value) {
2380 return value !== void 0;
2381}
2382function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties) {
2383 let promises = matches.map(({ route }) => {
2384 if (typeof route.lazy !== "object" || !route.lazy.middleware) return;
2385 return loadLazyRouteProperty({
2386 key: "middleware",
2387 route,
2388 manifest,
2389 mapRouteProperties
2390 });
2391 }).filter(isNonNullable);
2392 return promises.length > 0 ? Promise.all(promises) : void 0;
2393}
2394async function defaultDataStrategy(args) {
2395 let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
2396 let keyedResults = {};
2397 (await Promise.all(matchesToLoad.map((m) => m.resolve()))).forEach((result, i) => {
2398 keyedResults[matchesToLoad[i].route.id] = result;
2399 });
2400 return keyedResults;
2401}
2402async function defaultDataStrategyWithMiddleware(args) {
2403 if (!args.matches.some((m) => m.route.middleware)) return defaultDataStrategy(args);
2404 return runClientMiddlewarePipeline(args, () => defaultDataStrategy(args));
2405}
2406function runServerMiddlewarePipeline(args, handler, errorHandler) {
2407 return runMiddlewarePipeline(args, handler, processResult, isResponse, errorHandler);
2408 function processResult(result) {
2409 return isDataWithResponseInit(result) ? dataWithResponseInitToResponse(result) : result;
2410 }
2411}
2412function runClientMiddlewarePipeline(args, handler) {
2413 return runMiddlewarePipeline(args, handler, (r) => {
2414 if (isRedirectResponse(r)) throw r;
2415 return r;
2416 }, isDataStrategyResults, errorHandler);
2417 async function errorHandler(error, routeId, nextResult) {
2418 if (nextResult) return Object.assign(nextResult.value, { [routeId]: {
2419 type: "error",
2420 result: error
2421 } });
2422 else {
2423 let { matches } = args;
2424 let maxBoundaryIdx = Math.min(Math.max(matches.findIndex((m) => m.route.id === routeId), 0), Math.max(matches.findIndex((m) => m.shouldCallHandler()), 0));
2425 let deepestRouteId = matches[maxBoundaryIdx].route.id;
2426 for (let match of matches.slice(0, maxBoundaryIdx + 1)) try {
2427 await match._lazyPromises?.route;
2428 } catch {
2429 deepestRouteId = match.route.id;
2430 break;
2431 }
2432 return { [findNearestBoundary(matches, deepestRouteId).route.id]: {
2433 type: "error",
2434 result: error
2435 } };
2436 }
2437 }
2438}
2439async function runMiddlewarePipeline(args, handler, processResult, isResult, errorHandler) {
2440 let { matches, ...dataFnArgs } = args;
2441 return await callRouteMiddleware(dataFnArgs, matches.flatMap((m) => m.route.middleware ? m.route.middleware.map((fn) => [m.route.id, fn]) : []), handler, processResult, isResult, errorHandler);
2442}
2443async function callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx = 0) {
2444 let { request } = args;
2445 if (request.signal.aborted) throw request.signal.reason ?? /* @__PURE__ */ new Error(`Request aborted: ${request.method} ${request.url}`);
2446 let tuple = middlewares[idx];
2447 if (!tuple) return await handler();
2448 let [routeId, middleware] = tuple;
2449 let nextResult;
2450 let next = async () => {
2451 if (nextResult) throw new Error("You may only call `next()` once per middleware");
2452 try {
2453 nextResult = { value: await callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx + 1) };
2454 return nextResult.value;
2455 } catch (error) {
2456 nextResult = { value: await errorHandler(error, routeId, nextResult) };
2457 return nextResult.value;
2458 }
2459 };
2460 try {
2461 let value = await middleware(args, next);
2462 let result = value != null ? processResult(value) : void 0;
2463 if (isResult(result)) return result;
2464 else if (nextResult) return result ?? nextResult.value;
2465 else {
2466 nextResult = { value: await next() };
2467 return nextResult.value;
2468 }
2469 } catch (error) {
2470 return await errorHandler(error, routeId, nextResult);
2471 }
2472}
2473function getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip) {
2474 let lazyMiddlewarePromise = loadLazyRouteProperty({
2475 key: "middleware",
2476 route: match.route,
2477 manifest,
2478 mapRouteProperties
2479 });
2480 let lazyRoutePromises = loadLazyRoute(match.route, isMutationMethod(request.method) ? "action" : "loader", manifest, mapRouteProperties, lazyRoutePropertiesToSkip);
2481 return {
2482 middleware: lazyMiddlewarePromise,
2483 route: lazyRoutePromises.lazyRoutePromise,
2484 handler: lazyRoutePromises.lazyHandlerPromise
2485 };
2486}
2487function getDataStrategyMatch(mapRouteProperties, manifest, request, path, pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, shouldRevalidateArgs = null, callSiteDefaultShouldRevalidate) {
2488 let isUsingNewApi = false;
2489 let _lazyPromises = getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip);
2490 return {
2491 ...match,
2492 _lazyPromises,
2493 shouldLoad,
2494 shouldRevalidateArgs,
2495 shouldCallHandler(defaultShouldRevalidate) {
2496 isUsingNewApi = true;
2497 if (!shouldRevalidateArgs) return shouldLoad;
2498 if (typeof callSiteDefaultShouldRevalidate === "boolean") return shouldRevalidateLoader(match, {
2499 ...shouldRevalidateArgs,
2500 defaultShouldRevalidate: callSiteDefaultShouldRevalidate
2501 });
2502 if (typeof defaultShouldRevalidate === "boolean") return shouldRevalidateLoader(match, {
2503 ...shouldRevalidateArgs,
2504 defaultShouldRevalidate
2505 });
2506 return shouldRevalidateLoader(match, shouldRevalidateArgs);
2507 },
2508 resolve(handlerOverride) {
2509 let { lazy, loader, middleware } = match.route;
2510 let callHandler = isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (lazy || loader);
2511 let isMiddlewareOnlyRoute = middleware && middleware.length > 0 && !loader && !lazy;
2512 if (callHandler && (isMutationMethod(request.method) || !isMiddlewareOnlyRoute)) return callLoaderOrAction({
2513 request,
2514 path,
2515 pattern,
2516 match,
2517 lazyHandlerPromise: _lazyPromises?.handler,
2518 lazyRoutePromise: _lazyPromises?.route,
2519 handlerOverride,
2520 scopedContext
2521 });
2522 return Promise.resolve({
2523 type: "data",
2524 result: void 0
2525 });
2526 }
2527 };
2528}
2529function getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, path, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
2530 return matches.map((match) => {
2531 if (match.route.id !== targetMatch.route.id) return {
2532 ...match,
2533 shouldLoad: false,
2534 shouldRevalidateArgs,
2535 shouldCallHandler: () => false,
2536 _lazyPromises: getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip),
2537 resolve: () => Promise.resolve({
2538 type: "data",
2539 result: void 0
2540 })
2541 };
2542 return getDataStrategyMatch(mapRouteProperties, manifest, request, path, getRoutePattern(matches), match, lazyRoutePropertiesToSkip, scopedContext, true, shouldRevalidateArgs);
2543 });
2544}
2545async function callDataStrategyImpl(dataStrategyImpl, request, path, matches, fetcherKey, initiator, scopedContext, isStaticHandler, navigationType = null) {
2546 if (matches.some((m) => m._lazyPromises?.middleware)) await Promise.all(matches.map((m) => m._lazyPromises?.middleware));
2547 let dataStrategyArgs = {
2548 request,
2549 url: createDataFunctionUrl(request, path),
2550 pattern: getRoutePattern(matches),
2551 params: matches[0].params,
2552 context: scopedContext,
2553 matches,
2554 unstable_initiator: initiator,
2555 unstable_navigationType: initiator === "navigation" ? navigationType : null
2556 };
2557 let runClientMiddleware = isStaticHandler ? () => {
2558 throw new Error("You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`");
2559 } : (cb) => {
2560 let typedDataStrategyArgs = dataStrategyArgs;
2561 return runClientMiddlewarePipeline(typedDataStrategyArgs, () => {
2562 return cb({
2563 ...typedDataStrategyArgs,
2564 fetcherKey,
2565 runClientMiddleware: () => {
2566 throw new Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler");
2567 }
2568 });
2569 });
2570 };
2571 let results = await dataStrategyImpl({
2572 ...dataStrategyArgs,
2573 fetcherKey,
2574 runClientMiddleware
2575 });
2576 try {
2577 await Promise.all(matches.flatMap((m) => [m._lazyPromises?.handler, m._lazyPromises?.route]));
2578 } catch {}
2579 return results;
2580}
2581async function callLoaderOrAction({ request, path, pattern, match, lazyHandlerPromise, lazyRoutePromise, handlerOverride, scopedContext }) {
2582 let result;
2583 let onReject;
2584 let isAction = isMutationMethod(request.method);
2585 let type = isAction ? "action" : "loader";
2586 let runHandler = (handler) => {
2587 let reject;
2588 let abortPromise = new Promise((_, r) => reject = r);
2589 onReject = () => reject();
2590 request.signal.addEventListener("abort", onReject);
2591 let actualHandler = (ctx) => {
2592 if (typeof handler !== "function") return Promise.reject(/* @__PURE__ */ new Error(`You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`));
2593 return handler({
2594 request,
2595 url: createDataFunctionUrl(request, path),
2596 pattern,
2597 params: match.params,
2598 context: scopedContext
2599 }, ...ctx !== void 0 ? [ctx] : []);
2600 };
2601 let handlerPromise = (async () => {
2602 try {
2603 return {
2604 type: "data",
2605 result: await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler())
2606 };
2607 } catch (e) {
2608 return {
2609 type: "error",
2610 result: e
2611 };
2612 }
2613 })();
2614 return Promise.race([handlerPromise, abortPromise]);
2615 };
2616 try {
2617 let handler = isAction ? match.route.action : match.route.loader;
2618 if (lazyHandlerPromise || lazyRoutePromise) if (handler) {
2619 let handlerError;
2620 let [value] = await Promise.all([
2621 runHandler(handler).catch((e) => {
2622 handlerError = e;
2623 }),
2624 lazyHandlerPromise,
2625 lazyRoutePromise
2626 ]);
2627 if (handlerError !== void 0) throw handlerError;
2628 result = value;
2629 } else {
2630 await lazyHandlerPromise;
2631 let handler = isAction ? match.route.action : match.route.loader;
2632 if (handler) [result] = await Promise.all([runHandler(handler), lazyRoutePromise]);
2633 else if (type === "action") {
2634 let url = new URL(request.url);
2635 let pathname = url.pathname + url.search;
2636 throw getInternalRouterError(405, {
2637 method: request.method,
2638 pathname,
2639 routeId: match.route.id
2640 });
2641 } else {
2642 await lazyRoutePromise;
2643 return {
2644 type: "data",
2645 result: void 0
2646 };
2647 }
2648 }
2649 else if (!handler) {
2650 let url = new URL(request.url);
2651 throw getInternalRouterError(404, { pathname: url.pathname + url.search });
2652 } else result = await runHandler(handler);
2653 } catch (e) {
2654 return {
2655 type: "error",
2656 result: e
2657 };
2658 } finally {
2659 if (onReject) request.signal.removeEventListener("abort", onReject);
2660 }
2661 return result;
2662}
2663async function parseResponseBody(response) {
2664 let contentType = response.headers.get("Content-Type");
2665 if (contentType && /\bapplication\/json\b/.test(contentType)) return response.body == null ? null : response.json();
2666 return response.text();
2667}
2668async function convertDataStrategyResultToDataResult(dataStrategyResult) {
2669 let { result, type } = dataStrategyResult;
2670 if (isResponse(result)) {
2671 let data;
2672 try {
2673 data = await parseResponseBody(result);
2674 } catch (e) {
2675 return {
2676 type: "error",
2677 error: e
2678 };
2679 }
2680 if (type === "error") return {
2681 type: "error",
2682 error: new ErrorResponseImpl(result.status, result.statusText, data),
2683 statusCode: result.status,
2684 headers: result.headers
2685 };
2686 return {
2687 type: "data",
2688 data,
2689 statusCode: result.status,
2690 headers: result.headers
2691 };
2692 }
2693 if (type === "error") {
2694 if (isDataWithResponseInit(result)) {
2695 if (result.data instanceof Error) return {
2696 type: "error",
2697 error: result.data,
2698 statusCode: result.init?.status,
2699 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
2700 };
2701 return {
2702 type: "error",
2703 error: dataWithResponseInitToErrorResponse(result),
2704 statusCode: isRouteErrorResponse(result) ? result.status : void 0,
2705 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
2706 };
2707 }
2708 return {
2709 type: "error",
2710 error: result,
2711 statusCode: isRouteErrorResponse(result) ? result.status : void 0
2712 };
2713 }
2714 if (isDataWithResponseInit(result)) return {
2715 type: "data",
2716 data: result.data,
2717 statusCode: result.init?.status,
2718 headers: result.init?.headers ? new Headers(result.init.headers) : void 0
2719 };
2720 return {
2721 type: "data",
2722 data: result
2723 };
2724}
2725function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
2726 let location = response.headers.get("Location");
2727 invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header");
2728 validateNavigationTarget(location, location, new URL(request.url), "allow-explicit");
2729 if (!isAbsoluteUrl(location)) {
2730 let trimmedMatches = matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1);
2731 location = normalizeTo(new URL(request.url), trimmedMatches, basename, location);
2732 response.headers.set("Location", location);
2733 }
2734 return response;
2735}
2736const invalidProtocols = [
2737 "about:",
2738 "blob:",
2739 "chrome:",
2740 "chrome-untrusted:",
2741 "content:",
2742 "data:",
2743 "devtools:",
2744 "file:",
2745 "filesystem:",
2746 "javascript:"
2747];
2748function hasInvalidProtocol(location) {
2749 try {
2750 return invalidProtocols.includes(new URL(location).protocol);
2751 } catch {
2752 return false;
2753 }
2754}
2755function normalizeRedirectLocation(location, currentUrl, basename, historyInstance) {
2756 if (isAbsoluteUrl(location)) {
2757 let normalizedLocation = location;
2758 let url = PROTOCOL_RELATIVE_URL_REGEX.test(normalizedLocation) ? new URL(normalizeProtocolRelativeUrl(normalizedLocation, currentUrl.protocol)) : new URL(normalizedLocation);
2759 if (hasInvalidProtocol(url.toString())) throw new Error("Invalid redirect location");
2760 let isSameBasename = stripBasename(url.pathname, basename) != null;
2761 if (url.origin === currentUrl.origin && isSameBasename) return removeDoubleSlashes(url.pathname) + url.search + url.hash;
2762 }
2763 try {
2764 if (hasInvalidProtocol(historyInstance.createURL(location).toString())) throw new Error("Invalid redirect location");
2765 } catch {}
2766 return location;
2767}
2768function createClientSideRequest(history, location, signal, submission) {
2769 let url = history.createURL(stripHashFromPath(location)).toString();
2770 let init = { signal };
2771 if (submission && isMutationMethod(submission.formMethod)) {
2772 let { formMethod, formEncType } = submission;
2773 init.method = formMethod.toUpperCase();
2774 if (formEncType === "application/json") {
2775 init.headers = new Headers({ "Content-Type": formEncType });
2776 init.body = JSON.stringify(submission.json);
2777 } else if (formEncType === "text/plain") init.body = submission.text;
2778 else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) init.body = convertFormDataToSearchParams(submission.formData);
2779 else init.body = submission.formData;
2780 }
2781 return new Request(url, init);
2782}
2783function convertFormDataToSearchParams(formData) {
2784 let searchParams = new URLSearchParams();
2785 for (let [key, value] of formData.entries()) searchParams.append(key, typeof value === "string" ? value : value.name);
2786 return searchParams;
2787}
2788function convertSearchParamsToFormData(searchParams) {
2789 let formData = new FormData();
2790 for (let [key, value] of searchParams.entries()) formData.append(key, value);
2791 return formData;
2792}
2793function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
2794 let loaderData = {};
2795 let errors = null;
2796 let statusCode;
2797 let foundError = false;
2798 let loaderHeaders = {};
2799 let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
2800 matches.forEach((match) => {
2801 if (!(match.route.id in results)) return;
2802 let id = match.route.id;
2803 let result = results[id];
2804 invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
2805 if (isErrorResult(result)) {
2806 let error = result.error;
2807 if (pendingError !== void 0) {
2808 error = pendingError;
2809 pendingError = void 0;
2810 }
2811 errors = errors || {};
2812 if (skipLoaderErrorBubbling) errors[id] = error;
2813 else {
2814 let boundaryMatch = findNearestBoundary(matches, id);
2815 if (errors[boundaryMatch.route.id] == null) errors[boundaryMatch.route.id] = error;
2816 }
2817 if (!isStaticHandler) loaderData[id] = ResetLoaderDataSymbol;
2818 if (!foundError) {
2819 foundError = true;
2820 statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
2821 }
2822 if (result.headers) loaderHeaders[id] = result.headers;
2823 } else {
2824 loaderData[id] = result.data;
2825 if (result.statusCode && result.statusCode !== 200 && !foundError) statusCode = result.statusCode;
2826 if (result.headers) loaderHeaders[id] = result.headers;
2827 }
2828 });
2829 if (pendingError !== void 0 && pendingActionResult) {
2830 errors = { [pendingActionResult[0]]: pendingError };
2831 if (pendingActionResult[2]) loaderData[pendingActionResult[2]] = void 0;
2832 }
2833 return {
2834 loaderData,
2835 errors,
2836 statusCode: statusCode || 200,
2837 loaderHeaders
2838 };
2839}
2840function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults, workingFetchers) {
2841 let { loaderData, errors } = processRouteLoaderData(matches, results, pendingActionResult);
2842 revalidatingFetchers.filter((f) => !f.matches || f.matches.some((m) => m.shouldLoad)).forEach((rf) => {
2843 let { key, routeId, controller } = rf;
2844 if (controller && controller.signal.aborted) return;
2845 let result = fetcherResults[key];
2846 invariant(result, "Did not find corresponding fetcher result");
2847 if (isErrorResult(result)) {
2848 let boundaryMatch = findNearestBoundary(state.matches, routeId);
2849 if (!(errors && errors[boundaryMatch.route.id])) errors = {
2850 ...errors,
2851 [boundaryMatch.route.id]: result.error
2852 };
2853 workingFetchers.delete(key);
2854 } else if (isRedirectResult(result)) invariant(false, "Unhandled fetcher revalidation redirect");
2855 else {
2856 let doneFetcher = getDoneFetcher(result.data);
2857 workingFetchers.set(key, doneFetcher);
2858 }
2859 });
2860 return {
2861 loaderData,
2862 errors
2863 };
2864}
2865function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
2866 let mergedLoaderData = Object.entries(newLoaderData).filter(([, v]) => v !== ResetLoaderDataSymbol).reduce((merged, [k, v]) => {
2867 merged[k] = v;
2868 return merged;
2869 }, {});
2870 let preservedCount = 0;
2871 for (let match of matches) {
2872 let id = match.route.id;
2873 if (!newLoaderData.hasOwnProperty(id) && loaderData.hasOwnProperty(id) && match.route.loader) {
2874 mergedLoaderData[id] = loaderData[id];
2875 preservedCount++;
2876 }
2877 if (errors && errors.hasOwnProperty(id)) break;
2878 }
2879 return Object.keys(newLoaderData).length === 0 && preservedCount === Object.keys(loaderData).length ? loaderData : mergedLoaderData;
2880}
2881function getActionDataForCommit(pendingActionResult) {
2882 if (!pendingActionResult) return {};
2883 return isErrorResult(pendingActionResult[1]) ? { actionData: {} } : { actionData: { [pendingActionResult[0]]: pendingActionResult[1].data } };
2884}
2885function findNearestBoundary(matches, routeId) {
2886 return (routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches]).reverse().find((m) => m.route.ErrorBoundary != null || m.route.errorElement != null) || matches[0];
2887}
2888function getShortCircuitMatches(routes) {
2889 let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || { id: `__shim-error-route__` };
2890 return {
2891 matches: [{
2892 params: {},
2893 pathname: "",
2894 pathnameBase: "",
2895 route
2896 }],
2897 route
2898 };
2899}
2900function getInternalRouterError(status, { pathname, routeId, method, type, message } = {}) {
2901 let statusText = "Unknown Server Error";
2902 let errorMessage = "Unknown @remix-run/router error";
2903 if (status === 400) {
2904 statusText = "Bad Request";
2905 if (method && pathname && routeId) 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.`;
2906 else if (type === "invalid-body") errorMessage = "Unable to encode submission body";
2907 } else if (status === 403) {
2908 statusText = "Forbidden";
2909 errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
2910 } else if (status === 404) {
2911 statusText = "Not Found";
2912 errorMessage = `No route matches URL "${pathname}"`;
2913 } else if (status === 405) {
2914 statusText = "Method Not Allowed";
2915 if (method && pathname && routeId) 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.`;
2916 else if (method) errorMessage = `Invalid request method "${method.toUpperCase()}"`;
2917 }
2918 return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);
2919}
2920function findRedirect(results) {
2921 let entries = Object.entries(results);
2922 for (let i = entries.length - 1; i >= 0; i--) {
2923 let [key, result] = entries[i];
2924 if (isRedirectResult(result)) return {
2925 key,
2926 result
2927 };
2928 }
2929}
2930function stripHashFromPath(path) {
2931 return createPath({
2932 ...typeof path === "string" ? parsePath(path) : path,
2933 hash: ""
2934 });
2935}
2936function isHashChangeOnly(a, b) {
2937 if (a.pathname !== b.pathname || a.search !== b.search) return false;
2938 if (a.hash === "") return b.hash !== "";
2939 else if (a.hash === b.hash) return true;
2940 else if (b.hash !== "") return true;
2941 return false;
2942}
2943function dataWithResponseInitToResponse(data) {
2944 return Response.json(data.data, data.init ?? void 0);
2945}
2946function dataWithResponseInitToErrorResponse(data) {
2947 return new ErrorResponseImpl(data.init?.status ?? 500, data.init?.statusText ?? "Internal Server Error", data.data);
2948}
2949function isDataStrategyResults(result) {
2950 return result != null && typeof result === "object" && Object.entries(result).every(([key, value]) => typeof key === "string" && isDataStrategyResult(value));
2951}
2952function isDataStrategyResult(result) {
2953 return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" || result.type === "error");
2954}
2955function isRedirectDataStrategyResult(result) {
2956 return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
2957}
2958function isErrorResult(result) {
2959 return result.type === "error";
2960}
2961function isRedirectResult(result) {
2962 return (result && result.type) === "redirect";
2963}
2964function isDataWithResponseInit(value) {
2965 return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
2966}
2967function isResponse(value) {
2968 return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
2969}
2970function isRedirectStatusCode(statusCode) {
2971 return redirectStatusCodes.has(statusCode);
2972}
2973function isRedirectResponse(result) {
2974 return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
2975}
2976function isValidMethod(method) {
2977 return validRequestMethods.has(method.toUpperCase());
2978}
2979function isMutationMethod(method) {
2980 return validMutationMethods.has(method.toUpperCase());
2981}
2982function hasNakedIndexQuery(search) {
2983 return new URLSearchParams(search).getAll("index").some((v) => v === "");
2984}
2985function getTargetMatch(matches, location) {
2986 let search = typeof location === "string" ? parsePath(location).search : location.search;
2987 if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) return matches[matches.length - 1];
2988 let pathMatches = getPathContributingMatches(matches);
2989 return pathMatches[pathMatches.length - 1];
2990}
2991function getInstrumentationNavigateMeta(history, location, matches) {
2992 return {
2993 url: createDataFunctionUrl(history.createURL(location), location),
2994 pattern: matches ? getRoutePattern(matches) : "",
2995 params: matches?.[0]?.params ? { ...matches[0].params } : {}
2996 };
2997}
2998function getSubmissionFromNavigation(navigation) {
2999 let { formMethod, formAction, formEncType, text, formData, json } = navigation;
3000 if (!formMethod || !formAction || !formEncType) return;
3001 if (text != null) return {
3002 formMethod,
3003 formAction,
3004 formEncType,
3005 formData: void 0,
3006 json: void 0,
3007 text
3008 };
3009 else if (formData != null) return {
3010 formMethod,
3011 formAction,
3012 formEncType,
3013 formData,
3014 json: void 0,
3015 text: void 0
3016 };
3017 else if (json !== void 0) return {
3018 formMethod,
3019 formAction,
3020 formEncType,
3021 formData: void 0,
3022 json,
3023 text: void 0
3024 };
3025}
3026function getLoadingNavigation(location, matches, historyAction, submission) {
3027 if (submission) return {
3028 state: "loading",
3029 location,
3030 matches,
3031 historyAction,
3032 formMethod: submission.formMethod,
3033 formAction: submission.formAction,
3034 formEncType: submission.formEncType,
3035 formData: submission.formData,
3036 json: submission.json,
3037 text: submission.text
3038 };
3039 else return {
3040 state: "loading",
3041 location,
3042 matches,
3043 historyAction,
3044 formMethod: void 0,
3045 formAction: void 0,
3046 formEncType: void 0,
3047 formData: void 0,
3048 json: void 0,
3049 text: void 0
3050 };
3051}
3052function getSubmittingNavigation(location, matches, historyAction, submission) {
3053 return {
3054 state: "submitting",
3055 location,
3056 matches,
3057 historyAction,
3058 formMethod: submission.formMethod,
3059 formAction: submission.formAction,
3060 formEncType: submission.formEncType,
3061 formData: submission.formData,
3062 json: submission.json,
3063 text: submission.text
3064 };
3065}
3066function getLoadingFetcher(submission, data) {
3067 if (submission) return {
3068 state: "loading",
3069 formMethod: submission.formMethod,
3070 formAction: submission.formAction,
3071 formEncType: submission.formEncType,
3072 formData: submission.formData,
3073 json: submission.json,
3074 text: submission.text,
3075 data
3076 };
3077 else return {
3078 state: "loading",
3079 formMethod: void 0,
3080 formAction: void 0,
3081 formEncType: void 0,
3082 formData: void 0,
3083 json: void 0,
3084 text: void 0,
3085 data
3086 };
3087}
3088function getSubmittingFetcher(submission, existingFetcher) {
3089 return {
3090 state: "submitting",
3091 formMethod: submission.formMethod,
3092 formAction: submission.formAction,
3093 formEncType: submission.formEncType,
3094 formData: submission.formData,
3095 json: submission.json,
3096 text: submission.text,
3097 data: existingFetcher ? existingFetcher.data : void 0
3098 };
3099}
3100function getDoneFetcher(data) {
3101 return {
3102 state: "idle",
3103 formMethod: void 0,
3104 formAction: void 0,
3105 formEncType: void 0,
3106 formData: void 0,
3107 json: void 0,
3108 text: void 0,
3109 data
3110 };
3111}
3112function restoreAppliedTransitions(_window, transitions) {
3113 try {
3114 let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);
3115 if (sessionPositions) {
3116 let json = JSON.parse(sessionPositions);
3117 for (let [k, v] of Object.entries(json || {})) if (v && Array.isArray(v)) transitions.set(k, new Set(v || []));
3118 }
3119 } catch {}
3120}
3121function persistAppliedTransitions(_window, transitions) {
3122 if (transitions.size > 0) {
3123 let json = {};
3124 for (let [k, v] of transitions) json[k] = [...v];
3125 try {
3126 _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));
3127 } catch (error) {
3128 warning(false, `Failed to save applied view transitions in sessionStorage (${error}).`);
3129 }
3130 }
3131}
3132function createDeferred() {
3133 let resolve;
3134 let reject;
3135 let promise = new Promise((res, rej) => {
3136 resolve = async (val) => {
3137 res(val);
3138 try {
3139 await promise;
3140 } catch {}
3141 };
3142 reject = async (error) => {
3143 rej(error);
3144 try {
3145 await promise;
3146 } catch {}
3147 };
3148 });
3149 return {
3150 promise,
3151 resolve,
3152 reject
3153 };
3154}
3155//#endregion
3156export { IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, clientErrors, createDataRouteMatcher, createRouter, createStaticHandler, getStaticContextFromError, hasInvalidProtocol, isDataWithResponseInit, isMutationMethod, isRedirectResponse, isRedirectStatusCode, isResponse };