UNPKG

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