@remix-run/router 0.0.0-experimental-e960cf1a → 0.0.0-experimental-a0888892

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/router.ts CHANGED
@@ -11,7 +11,7 @@ import type {
11
11
  ActionFunction,
12
12
  AgnosticDataRouteMatch,
13
13
  AgnosticDataRouteObject,
14
- AgnosticDataStrategyMatch,
14
+ DataStrategyMatch,
15
15
  AgnosticRouteObject,
16
16
  DataResult,
17
17
  DataStrategyFunction,
@@ -23,8 +23,8 @@ import type {
23
23
  FormEncType,
24
24
  FormMethod,
25
25
  HTMLFormMethod,
26
+ HandlerResult,
26
27
  ImmutableRouteKey,
27
- LazyRoutePromise,
28
28
  LoaderFunction,
29
29
  MapRoutePropertiesFunction,
30
30
  MutationFormMethod,
@@ -665,16 +665,6 @@ interface RevalidatingFetcher extends FetchLoadMatch {
665
665
  controller: AbortController | null;
666
666
  }
667
667
 
668
- /**
669
- * Wrapper object to allow us to throw any response out from callLoaderOrAction
670
- * for queryRouter while preserving whether or not it was thrown or returned
671
- * from the loader/action
672
- */
673
- interface QueryRouteResponse {
674
- type: ResultType.data | ResultType.error;
675
- response: Response;
676
- }
677
-
678
668
  const validMutationMethodsArr: MutationFormMethod[] = [
679
669
  "post",
680
670
  "put",
@@ -757,9 +747,6 @@ export function createRouter(init: RouterInit): Router {
757
747
  "You must provide a non-empty routes array to createRouter"
758
748
  );
759
749
 
760
- const dataStrategy = init.unstable_dataStrategy || defaultDataStrategy;
761
- const callLoaderOrAction = createCallLoaderOrAction(dataStrategy);
762
-
763
750
  let mapRouteProperties: MapRoutePropertiesFunction;
764
751
  if (init.mapRouteProperties) {
765
752
  mapRouteProperties = init.mapRouteProperties;
@@ -784,6 +771,7 @@ export function createRouter(init: RouterInit): Router {
784
771
  );
785
772
  let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;
786
773
  let basename = init.basename || "/";
774
+ let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy;
787
775
  // Config driven behavior flags
788
776
  let future: FutureConfig = {
789
777
  v7_fetcherPersist: false,
@@ -825,19 +813,35 @@ export function createRouter(init: RouterInit): Router {
825
813
  initialErrors = { [route.id]: error };
826
814
  }
827
815
 
828
- // "Initialized" here really means "Can `RouterProvider` render my route tree?"
829
- // Prior to `route.HydrateFallback`, we only had a root `fallbackElement` so we used
830
- // `state.initialized` to render that instead of `<DataRoutes>`. Now that we
831
- // support route level fallbacks we can always render and we'll just render
832
- // as deep as we have data for and detect the nearest ancestor HydrateFallback
833
- let initialized =
834
- future.v7_partialHydration ||
816
+ let initialized: boolean;
817
+ let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);
818
+ let hasLoaders = initialMatches.some((m) => m.route.loader);
819
+ if (hasLazyRoutes) {
835
820
  // All initialMatches need to be loaded before we're ready. If we have lazy
836
821
  // functions around still then we'll need to run them in initialize()
837
- (!initialMatches.some((m) => m.route.lazy) &&
838
- // And we have to either have no loaders or have been provided hydrationData
839
- (!initialMatches.some((m) => m.route.loader) ||
840
- init.hydrationData != null));
822
+ initialized = false;
823
+ } else if (!hasLoaders) {
824
+ // If we've got no loaders to run, then we're good to go
825
+ initialized = true;
826
+ } else if (future.v7_partialHydration) {
827
+ // If partial hydration is enabled, we're initialized so long as we were
828
+ // provided with hydrationData for every route with a loader, and no loaders
829
+ // were marked for explicit hydration
830
+ let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;
831
+ let errors = init.hydrationData ? init.hydrationData.errors : null;
832
+ initialized = initialMatches.every(
833
+ (m) =>
834
+ m.route.loader &&
835
+ (typeof m.route.loader !== "function" ||
836
+ m.route.loader.hydrate !== true) &&
837
+ ((loaderData && loaderData[m.route.id] !== undefined) ||
838
+ (errors && errors[m.route.id] !== undefined))
839
+ );
840
+ } else {
841
+ // Without partial hydration - we're initialized if we were provided any
842
+ // hydrationData - which is expected to be complete
843
+ initialized = init.hydrationData != null;
844
+ }
841
845
 
842
846
  let router: Router;
843
847
  let state: RouterState = {
@@ -1018,11 +1022,7 @@ export function createRouter(init: RouterInit): Router {
1018
1022
  // in the normal navigation flow. For SSR it's expected that lazy modules are
1019
1023
  // resolved prior to router creation since we can't go into a fallbackElement
1020
1024
  // UI for SSR'd apps
1021
- if (
1022
- !state.initialized ||
1023
- (future.v7_partialHydration &&
1024
- state.matches.some((m) => isUnhydratedRoute(state, m.route)))
1025
- ) {
1025
+ if (!state.initialized) {
1026
1026
  startNavigation(HistoryAction.Pop, state.location, {
1027
1027
  initialHydration: true,
1028
1028
  });
@@ -1575,16 +1575,13 @@ export function createRouter(init: RouterInit): Router {
1575
1575
  }),
1576
1576
  };
1577
1577
  } else {
1578
- result = await callLoaderOrAction(
1578
+ let results = await callDataStrategy(
1579
1579
  "action",
1580
1580
  request,
1581
- actionMatch,
1582
- matches,
1583
- manifest,
1584
- mapRouteProperties,
1585
- basename,
1586
- future.v7_relativeSplatPath
1581
+ [actionMatch],
1582
+ matches
1587
1583
  );
1584
+ result = results[0];
1588
1585
 
1589
1586
  if (request.signal.aborted) {
1590
1587
  return { shortCircuited: true };
@@ -1600,9 +1597,13 @@ export function createRouter(init: RouterInit): Router {
1600
1597
  // we redirected to the exact same location we're currently at to avoid
1601
1598
  // double back-buttons
1602
1599
  replace =
1603
- result.location === state.location.pathname + state.location.search;
1600
+ result.response.headers.get("Location") ===
1601
+ state.location.pathname + state.location.search;
1604
1602
  }
1605
- await startRedirectNavigation(state, result, { submission, replace });
1603
+ await startRedirectNavigation(request, result, {
1604
+ submission,
1605
+ replace,
1606
+ });
1606
1607
  return { shortCircuited: true };
1607
1608
  }
1608
1609
 
@@ -1770,7 +1771,7 @@ export function createRouter(init: RouterInit): Router {
1770
1771
  }
1771
1772
 
1772
1773
  let { loaderResults, fetcherResults } =
1773
- await loadDataAndMaybeResolveDeferred(
1774
+ await callLoadersAndMaybeResolveData(
1774
1775
  state.matches,
1775
1776
  matches,
1776
1777
  matchesToLoad,
@@ -1804,7 +1805,9 @@ export function createRouter(init: RouterInit): Router {
1804
1805
  revalidatingFetchers[redirect.idx - matchesToLoad.length].key;
1805
1806
  fetchRedirectIds.add(fetcherKey);
1806
1807
  }
1807
- await startRedirectNavigation(state, redirect.result, { replace });
1808
+ await startRedirectNavigation(request, redirect.result, {
1809
+ replace,
1810
+ });
1808
1811
  return { shortCircuited: true };
1809
1812
  }
1810
1813
 
@@ -1969,16 +1972,13 @@ export function createRouter(init: RouterInit): Router {
1969
1972
  fetchControllers.set(key, abortController);
1970
1973
 
1971
1974
  let originatingLoadId = incrementingLoadId;
1972
- let actionResult = await callLoaderOrAction(
1975
+ let actionResults = await callDataStrategy(
1973
1976
  "action",
1974
1977
  fetchRequest,
1975
- match,
1976
- requestMatches,
1977
- manifest,
1978
- mapRouteProperties,
1979
- basename,
1980
- future.v7_relativeSplatPath
1978
+ [match],
1979
+ requestMatches
1981
1980
  );
1981
+ let actionResult = actionResults[0];
1982
1982
 
1983
1983
  if (fetchRequest.signal.aborted) {
1984
1984
  // We can delete this so long as we weren't aborted by our own fetcher
@@ -2011,7 +2011,7 @@ export function createRouter(init: RouterInit): Router {
2011
2011
  } else {
2012
2012
  fetchRedirectIds.add(key);
2013
2013
  updateFetcherState(key, getLoadingFetcher(submission));
2014
- return startRedirectNavigation(state, actionResult, {
2014
+ return startRedirectNavigation(fetchRequest, actionResult, {
2015
2015
  fetcherSubmission: submission,
2016
2016
  });
2017
2017
  }
@@ -2101,7 +2101,7 @@ export function createRouter(init: RouterInit): Router {
2101
2101
  );
2102
2102
 
2103
2103
  let { loaderResults, fetcherResults } =
2104
- await loadDataAndMaybeResolveDeferred(
2104
+ await callLoadersAndMaybeResolveData(
2105
2105
  state.matches,
2106
2106
  matches,
2107
2107
  matchesToLoad,
@@ -2132,7 +2132,7 @@ export function createRouter(init: RouterInit): Router {
2132
2132
  revalidatingFetchers[redirect.idx - matchesToLoad.length].key;
2133
2133
  fetchRedirectIds.add(fetcherKey);
2134
2134
  }
2135
- return startRedirectNavigation(state, redirect.result);
2135
+ return startRedirectNavigation(revalidationRequest, redirect.result);
2136
2136
  }
2137
2137
 
2138
2138
  // Process and commit output from loaders
@@ -2220,16 +2220,13 @@ export function createRouter(init: RouterInit): Router {
2220
2220
  fetchControllers.set(key, abortController);
2221
2221
 
2222
2222
  let originatingLoadId = incrementingLoadId;
2223
- let result: DataResult = await callLoaderOrAction(
2223
+ let results = await callDataStrategy(
2224
2224
  "loader",
2225
2225
  fetchRequest,
2226
- match,
2227
- matches,
2228
- manifest,
2229
- mapRouteProperties,
2230
- basename,
2231
- future.v7_relativeSplatPath
2226
+ [match],
2227
+ matches
2232
2228
  );
2229
+ let result = results[0];
2233
2230
 
2234
2231
  // Deferred isn't supported for fetcher loads, await everything and treat it
2235
2232
  // as a normal load. resolveDeferredData will return undefined if this
@@ -2267,7 +2264,7 @@ export function createRouter(init: RouterInit): Router {
2267
2264
  return;
2268
2265
  } else {
2269
2266
  fetchRedirectIds.add(key);
2270
- await startRedirectNavigation(state, result);
2267
+ await startRedirectNavigation(fetchRequest, result);
2271
2268
  return;
2272
2269
  }
2273
2270
  }
@@ -2304,7 +2301,7 @@ export function createRouter(init: RouterInit): Router {
2304
2301
  * the history action from the original navigation (PUSH or REPLACE).
2305
2302
  */
2306
2303
  async function startRedirectNavigation(
2307
- state: RouterState,
2304
+ request: Request,
2308
2305
  redirect: RedirectResult,
2309
2306
  {
2310
2307
  submission,
@@ -2316,26 +2313,40 @@ export function createRouter(init: RouterInit): Router {
2316
2313
  replace?: boolean;
2317
2314
  } = {}
2318
2315
  ) {
2319
- if (redirect.revalidate) {
2316
+ if (redirect.response.headers.has("X-Remix-Revalidate")) {
2320
2317
  isRevalidationRequired = true;
2321
2318
  }
2322
2319
 
2323
- let redirectLocation = createLocation(state.location, redirect.location, {
2320
+ let location = redirect.response.headers.get("Location");
2321
+ invariant(location, "Expected a Location header on the redirect Response");
2322
+ let redirectLocation = createLocation(state.location, location, {
2324
2323
  _isRedirect: true,
2325
2324
  });
2326
- invariant(
2327
- redirectLocation,
2328
- "Expected a location on the redirect navigation"
2329
- );
2325
+
2326
+ if (ABSOLUTE_URL_REGEX.test(location)) {
2327
+ // Strip off the protocol+origin for same-origin + same-basename absolute redirects
2328
+ let normalizedLocation = location;
2329
+ let currentUrl = new URL(request.url);
2330
+ let url = normalizedLocation.startsWith("//")
2331
+ ? new URL(currentUrl.protocol + normalizedLocation)
2332
+ : new URL(normalizedLocation);
2333
+ let isSameBasename = stripBasename(url.pathname, basename) != null;
2334
+ if (url.origin === currentUrl.origin && isSameBasename) {
2335
+ normalizedLocation = url.pathname + url.search + url.hash;
2336
+ redirectLocation = createLocation(state.location, normalizedLocation, {
2337
+ _isRedirect: true,
2338
+ });
2339
+ }
2340
+ }
2330
2341
 
2331
2342
  if (isBrowser) {
2332
2343
  let isDocumentReload = false;
2333
2344
 
2334
- if (redirect.reloadDocument) {
2345
+ if (redirect.response.headers.has("X-Remix-Reload-Document")) {
2335
2346
  // Hard reload if the response contained X-Remix-Reload-Document
2336
2347
  isDocumentReload = true;
2337
- } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {
2338
- const url = init.history.createURL(redirect.location);
2348
+ } else if (ABSOLUTE_URL_REGEX.test(location)) {
2349
+ const url = init.history.createURL(location);
2339
2350
  isDocumentReload =
2340
2351
  // Hard reload if it's an absolute URL to a new origin
2341
2352
  url.origin !== routerWindow.location.origin ||
@@ -2345,9 +2356,9 @@ export function createRouter(init: RouterInit): Router {
2345
2356
 
2346
2357
  if (isDocumentReload) {
2347
2358
  if (replace) {
2348
- routerWindow.location.replace(redirect.location);
2359
+ routerWindow.location.replace(location);
2349
2360
  } else {
2350
- routerWindow.location.assign(redirect.location);
2361
+ routerWindow.location.assign(location);
2351
2362
  }
2352
2363
  return;
2353
2364
  }
@@ -2378,14 +2389,14 @@ export function createRouter(init: RouterInit): Router {
2378
2389
  // redirected location
2379
2390
  let activeSubmission = submission || fetcherSubmission;
2380
2391
  if (
2381
- redirectPreserveMethodStatusCodes.has(redirect.status) &&
2392
+ redirectPreserveMethodStatusCodes.has(redirect.response.status) &&
2382
2393
  activeSubmission &&
2383
2394
  isMutationMethod(activeSubmission.formMethod)
2384
2395
  ) {
2385
2396
  await startNavigation(redirectHistoryAction, redirectLocation, {
2386
2397
  submission: {
2387
2398
  ...activeSubmission,
2388
- formAction: redirect.location,
2399
+ formAction: location,
2389
2400
  },
2390
2401
  // Preserve this flag across redirects
2391
2402
  preventScrollReset: pendingPreventScrollReset,
@@ -2407,7 +2418,55 @@ export function createRouter(init: RouterInit): Router {
2407
2418
  }
2408
2419
  }
2409
2420
 
2410
- async function loadDataAndMaybeResolveDeferred(
2421
+ // Utility wrapper for calling dataStrategy client-side without having to
2422
+ // pass around the manifest, mapRouteProperties, etc.
2423
+ async function callDataStrategy(
2424
+ type: "loader" | "action",
2425
+ request: Request,
2426
+ matchesToLoad: AgnosticDataRouteMatch[],
2427
+ matches: AgnosticDataRouteMatch[]
2428
+ ): Promise<DataResult[]> {
2429
+ try {
2430
+ let results = await callDataStrategyImpl(
2431
+ dataStrategyImpl,
2432
+ type,
2433
+ request,
2434
+ matchesToLoad,
2435
+ matches,
2436
+ manifest,
2437
+ mapRouteProperties
2438
+ );
2439
+
2440
+ return await Promise.all(
2441
+ results.map((result, i) => {
2442
+ if (isRedirectHandlerResult(result)) {
2443
+ return {
2444
+ type: ResultType.redirect,
2445
+ response: normalizeRelativeRoutingRedirectResponse(
2446
+ result.result,
2447
+ request,
2448
+ matchesToLoad[i].route.id,
2449
+ matches,
2450
+ basename,
2451
+ future.v7_relativeSplatPath
2452
+ ),
2453
+ };
2454
+ }
2455
+
2456
+ return convertHandlerResultToDataResult(result);
2457
+ })
2458
+ );
2459
+ } catch (e) {
2460
+ // If the outer dataStrategy method throws, just return the error for all
2461
+ // matches - and it'll naturally bubble to the root
2462
+ return matchesToLoad.map(() => ({
2463
+ type: ResultType.error,
2464
+ error: e,
2465
+ }));
2466
+ }
2467
+ }
2468
+
2469
+ async function callLoadersAndMaybeResolveData(
2411
2470
  currentMatches: AgnosticDataRouteMatch[],
2412
2471
  matches: AgnosticDataRouteMatch[],
2413
2472
  matchesToLoad: AgnosticDataRouteMatch[],
@@ -2416,30 +2475,22 @@ export function createRouter(init: RouterInit): Router {
2416
2475
  ) {
2417
2476
  let [loaderResults, ...fetcherResults] = await Promise.all([
2418
2477
  matchesToLoad.length
2419
- ? dataStrategy({
2420
- matches: matchesToLoad.map((m) =>
2421
- finesseToAgnosticDataStrategyMatch(
2422
- m,
2423
- mapRouteProperties,
2424
- manifest
2425
- )
2426
- ),
2427
- request,
2428
- type: "loader",
2429
- defaultStrategy(match) {
2430
- return callLoaderOrActionImplementation(
2431
- "loader",
2432
- request,
2433
- match,
2434
- matches,
2435
- basename,
2436
- future.v7_relativeSplatPath
2437
- );
2438
- },
2439
- })
2478
+ ? callDataStrategy("loader", request, matchesToLoad, matches)
2440
2479
  : [],
2441
2480
  ...fetchersToLoad.map((f) => {
2442
- if (!f.matches || !f.match || !f.controller) {
2481
+ if (f.matches && f.match && f.controller) {
2482
+ let fetcherRequest = createClientSideRequest(
2483
+ init.history,
2484
+ f.path,
2485
+ f.controller.signal
2486
+ );
2487
+ return callDataStrategy(
2488
+ "loader",
2489
+ fetcherRequest,
2490
+ [f.match],
2491
+ f.matches
2492
+ ).then((r) => r[0]);
2493
+ } else {
2443
2494
  return Promise.resolve<DataResult>({
2444
2495
  type: ResultType.error,
2445
2496
  error: getInternalRouterError(404, {
@@ -2447,41 +2498,6 @@ export function createRouter(init: RouterInit): Router {
2447
2498
  }),
2448
2499
  });
2449
2500
  }
2450
-
2451
- return dataStrategy({
2452
- matches: [
2453
- finesseToAgnosticDataStrategyMatch(
2454
- f.match!,
2455
- mapRouteProperties,
2456
- manifest
2457
- ),
2458
- ],
2459
- request,
2460
- type: "loader",
2461
- defaultStrategy(match) {
2462
- invariant(
2463
- f.controller,
2464
- "Expected controller for fetcher in defaultStrategy"
2465
- );
2466
- invariant(
2467
- f.matches,
2468
- "Expected matches for fetcher in defaultStrategy"
2469
- );
2470
-
2471
- return callLoaderOrActionImplementation(
2472
- "loader",
2473
- createClientSideRequest(
2474
- init.history,
2475
- f.path,
2476
- f.controller.signal
2477
- ),
2478
- match,
2479
- f.matches,
2480
- basename,
2481
- future.v7_relativeSplatPath
2482
- );
2483
- },
2484
- }).then((r) => r[0]);
2485
2501
  }),
2486
2502
  ]);
2487
2503
 
@@ -2865,6 +2881,7 @@ export const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
2865
2881
  */
2866
2882
  export interface StaticHandlerFutureConfig {
2867
2883
  v7_relativeSplatPath: boolean;
2884
+ v7_throwAbortReason: boolean;
2868
2885
  }
2869
2886
 
2870
2887
  export interface CreateStaticHandlerOptions {
@@ -2873,7 +2890,7 @@ export interface CreateStaticHandlerOptions {
2873
2890
  * @deprecated Use `mapRouteProperties` instead
2874
2891
  */
2875
2892
  detectErrorBoundary?: DetectErrorBoundaryFunction;
2876
- dataStrategy?: DataStrategyFunction;
2893
+ unstable_dataStrategy?: DataStrategyFunction;
2877
2894
  mapRouteProperties?: MapRoutePropertiesFunction;
2878
2895
  future?: Partial<StaticHandlerFutureConfig>;
2879
2896
  }
@@ -2887,11 +2904,9 @@ export function createStaticHandler(
2887
2904
  "You must provide a non-empty routes array to createStaticHandler"
2888
2905
  );
2889
2906
 
2890
- const dataStrategy = opts?.dataStrategy || defaultDataStrategy;
2891
- const callLoaderOrAction = createCallLoaderOrAction(dataStrategy);
2892
-
2893
2907
  let manifest: RouteManifest = {};
2894
2908
  let basename = (opts ? opts.basename : null) || "/";
2909
+ let dataStrategyImpl = opts?.unstable_dataStrategy || defaultDataStrategy;
2895
2910
  let mapRouteProperties: MapRoutePropertiesFunction;
2896
2911
  if (opts?.mapRouteProperties) {
2897
2912
  mapRouteProperties = opts.mapRouteProperties;
@@ -2907,6 +2922,7 @@ export function createStaticHandler(
2907
2922
  // Config driven behavior flags
2908
2923
  let future: StaticHandlerFutureConfig = {
2909
2924
  v7_relativeSplatPath: false,
2925
+ v7_throwAbortReason: false,
2910
2926
  ...(opts ? opts.future : null),
2911
2927
  };
2912
2928
 
@@ -3122,14 +3138,14 @@ export function createStaticHandler(
3122
3138
  actionHeaders: {},
3123
3139
  };
3124
3140
  } catch (e) {
3125
- // If the user threw/returned a Response in callLoaderOrAction, we throw
3126
- // it to bail out and then return or throw here based on whether the user
3127
- // returned or threw
3128
- if (isQueryRouteResponse(e)) {
3141
+ // If the user threw/returned a Response in callLoaderOrAction for a
3142
+ // `queryRoute` call, we throw the `HandlerResult` to bail out early
3143
+ // and then return or throw the raw Response here accordingly
3144
+ if (isHandlerResult(e) && isResponse(e.result)) {
3129
3145
  if (e.type === ResultType.error) {
3130
- throw e.response;
3146
+ throw e.result;
3131
3147
  }
3132
- return e.response;
3148
+ return e.result;
3133
3149
  }
3134
3150
  // Redirects are always returned since they don't propagate to catch
3135
3151
  // boundaries
@@ -3163,23 +3179,18 @@ export function createStaticHandler(
3163
3179
  error,
3164
3180
  };
3165
3181
  } else {
3166
- result = await callLoaderOrAction(
3182
+ let results = await callDataStrategy(
3167
3183
  "action",
3168
3184
  request,
3169
- actionMatch,
3185
+ [actionMatch],
3170
3186
  matches,
3171
- manifest,
3172
- mapRouteProperties,
3173
- basename,
3174
- future.v7_relativeSplatPath,
3175
- { isStaticRequest: true, isRouteRequest, requestContext }
3187
+ isRouteRequest,
3188
+ requestContext
3176
3189
  );
3190
+ result = results[0];
3177
3191
 
3178
3192
  if (request.signal.aborted) {
3179
- let method = isRouteRequest ? "queryRoute" : "query";
3180
- throw new Error(
3181
- `${method}() call aborted: ${request.method} ${request.url}`
3182
- );
3193
+ throwStaticHandlerAbortedError(request, isRouteRequest, future);
3183
3194
  }
3184
3195
  }
3185
3196
 
@@ -3189,9 +3200,9 @@ export function createStaticHandler(
3189
3200
  // can get back on the "throw all redirect responses" train here should
3190
3201
  // this ever happen :/
3191
3202
  throw new Response(null, {
3192
- status: result.status,
3203
+ status: result.response.status,
3193
3204
  headers: {
3194
- Location: result.location,
3205
+ Location: result.response.headers.get("Location")!,
3195
3206
  },
3196
3207
  });
3197
3208
  }
@@ -3250,7 +3261,9 @@ export function createStaticHandler(
3250
3261
  : 500,
3251
3262
  actionData: null,
3252
3263
  actionHeaders: {
3253
- ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),
3264
+ ...(result.response
3265
+ ? { [actionMatch.route.id]: result.response.headers }
3266
+ : {}),
3254
3267
  },
3255
3268
  };
3256
3269
  }
@@ -3265,14 +3278,20 @@ export function createStaticHandler(
3265
3278
 
3266
3279
  return {
3267
3280
  ...context,
3268
- // action status codes take precedence over loader status codes
3269
- ...(result.statusCode ? { statusCode: result.statusCode } : {}),
3270
3281
  actionData: {
3271
3282
  [actionMatch.route.id]: result.data,
3272
3283
  },
3273
- actionHeaders: {
3274
- ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),
3275
- },
3284
+ // action status codes take precedence over loader status codes
3285
+ ...(result.response
3286
+ ? {
3287
+ statusCode: result.response.status,
3288
+ actionHeaders: {
3289
+ [actionMatch.route.id]: result.response.headers,
3290
+ },
3291
+ }
3292
+ : {
3293
+ actionHeaders: {},
3294
+ }),
3276
3295
  };
3277
3296
  }
3278
3297
 
@@ -3330,30 +3349,17 @@ export function createStaticHandler(
3330
3349
  };
3331
3350
  }
3332
3351
 
3333
- let results = await dataStrategy({
3334
- matches: matchesToLoad.map((m) =>
3335
- finesseToAgnosticDataStrategyMatch(m, mapRouteProperties, manifest)
3336
- ),
3352
+ let results = await callDataStrategy(
3353
+ "loader",
3337
3354
  request,
3338
- type: "loader",
3339
- defaultStrategy(match) {
3340
- return callLoaderOrActionImplementation(
3341
- "loader",
3342
- request,
3343
- match,
3344
- matches,
3345
- basename,
3346
- future.v7_relativeSplatPath,
3347
- { isStaticRequest: true, isRouteRequest, requestContext }
3348
- );
3349
- },
3350
- });
3355
+ matchesToLoad,
3356
+ matches,
3357
+ isRouteRequest,
3358
+ requestContext
3359
+ );
3351
3360
 
3352
3361
  if (request.signal.aborted) {
3353
- let method = isRouteRequest ? "queryRoute" : "query";
3354
- throw new Error(
3355
- `${method}() call aborted: ${request.method} ${request.url}`
3356
- );
3362
+ throwStaticHandlerAbortedError(request, isRouteRequest, future);
3357
3363
  }
3358
3364
 
3359
3365
  // Process and commit output from loaders
@@ -3386,6 +3392,52 @@ export function createStaticHandler(
3386
3392
  };
3387
3393
  }
3388
3394
 
3395
+ // Utility wrapper for calling dataStrategy server-side without having to
3396
+ // pass around the manifest, mapRouteProperties, etc.
3397
+ async function callDataStrategy(
3398
+ type: "loader" | "action",
3399
+ request: Request,
3400
+ matchesToLoad: AgnosticDataRouteMatch[],
3401
+ matches: AgnosticDataRouteMatch[],
3402
+ isRouteRequest: boolean,
3403
+ requestContext: unknown
3404
+ ): Promise<DataResult[]> {
3405
+ let results = await callDataStrategyImpl(
3406
+ dataStrategyImpl,
3407
+ type,
3408
+ request,
3409
+ matchesToLoad,
3410
+ matches,
3411
+ manifest,
3412
+ mapRouteProperties,
3413
+ requestContext
3414
+ );
3415
+
3416
+ return await Promise.all(
3417
+ results.map((result, i) => {
3418
+ if (isRedirectHandlerResult(result)) {
3419
+ // Throw redirects and let the server handle them with an HTTP redirect
3420
+ throw normalizeRelativeRoutingRedirectResponse(
3421
+ result.result,
3422
+ request,
3423
+ matchesToLoad[i].route.id,
3424
+ matches,
3425
+ basename,
3426
+ future.v7_relativeSplatPath
3427
+ );
3428
+ }
3429
+ if (isResponse(result.result) && isRouteRequest) {
3430
+ // For SSR single-route requests, we want to hand Responses back directly
3431
+ // without unwrapping. We do this with the QueryRouteResponse wrapper
3432
+ // interface so we can know whether it was returned or thrown
3433
+ throw result;
3434
+ }
3435
+
3436
+ return convertHandlerResultToDataResult(result);
3437
+ })
3438
+ );
3439
+ }
3440
+
3389
3441
  return {
3390
3442
  dataRoutes,
3391
3443
  query,
@@ -3399,13 +3451,6 @@ export function createStaticHandler(
3399
3451
  //#region Helpers
3400
3452
  ////////////////////////////////////////////////////////////////////////////////
3401
3453
 
3402
- function defaultDataStrategy({
3403
- defaultStrategy,
3404
- matches,
3405
- }: DataStrategyFunctionArgs) {
3406
- return Promise.all(matches.map((match) => defaultStrategy(match)));
3407
- }
3408
-
3409
3454
  /**
3410
3455
  * Given an existing StaticHandlerContext and an error thrown at render time,
3411
3456
  * provide an updated StaticHandlerContext suitable for a second SSR render
@@ -3417,7 +3462,7 @@ export function getStaticContextFromError(
3417
3462
  ) {
3418
3463
  let newContext: StaticHandlerContext = {
3419
3464
  ...context,
3420
- statusCode: 500,
3465
+ statusCode: isRouteErrorResponse(error) ? error.status : 500,
3421
3466
  errors: {
3422
3467
  [context._deepestRenderedBoundaryId || routes[0].id]: error,
3423
3468
  },
@@ -3425,6 +3470,19 @@ export function getStaticContextFromError(
3425
3470
  return newContext;
3426
3471
  }
3427
3472
 
3473
+ function throwStaticHandlerAbortedError(
3474
+ request: Request,
3475
+ isRouteRequest: boolean,
3476
+ future: StaticHandlerFutureConfig
3477
+ ) {
3478
+ if (future.v7_throwAbortReason && request.signal.reason !== undefined) {
3479
+ throw request.signal.reason;
3480
+ }
3481
+
3482
+ let method = isRouteRequest ? "queryRoute" : "query";
3483
+ throw new Error(`${method}() call aborted: ${request.method} ${request.url}`);
3484
+ }
3485
+
3428
3486
  function isSubmissionNavigation(
3429
3487
  opts: BaseNavigateOrFetchOptions
3430
3488
  ): opts is SubmissionNavigateOptions {
@@ -3700,21 +3758,27 @@ function getMatchesToLoad(
3700
3758
  let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);
3701
3759
 
3702
3760
  let navigationMatches = boundaryMatches.filter((match, index) => {
3703
- if (isInitialLoad) {
3704
- // On initial hydration we don't do any shouldRevalidate stuff - we just
3705
- // call the unhydrated loaders
3706
- return isUnhydratedRoute(state, match.route);
3707
- }
3708
-
3709
- if (match.route.lazy) {
3761
+ let { route } = match;
3762
+ if (route.lazy) {
3710
3763
  // We haven't loaded this route yet so we don't know if it's got a loader!
3711
3764
  return true;
3712
3765
  }
3713
3766
 
3714
- if (match.route.loader == null) {
3767
+ if (route.loader == null) {
3715
3768
  return false;
3716
3769
  }
3717
3770
 
3771
+ if (isInitialLoad) {
3772
+ if (typeof route.loader !== "function" || route.loader.hydrate) {
3773
+ return true;
3774
+ }
3775
+ return (
3776
+ state.loaderData[route.id] === undefined &&
3777
+ // Don't re-run if the loader ran and threw an error
3778
+ (!state.errors || state.errors[route.id] === undefined)
3779
+ );
3780
+ }
3781
+
3718
3782
  // Always call the loader on new route instances and pending defer cancellations
3719
3783
  if (
3720
3784
  isNewLoader(state.loaderData, state.matches[index], match) ||
@@ -3834,23 +3898,6 @@ function getMatchesToLoad(
3834
3898
  return [navigationMatches, revalidatingFetchers];
3835
3899
  }
3836
3900
 
3837
- // Is this route unhydrated (when v7_partialHydration=true) such that we need
3838
- // to call it's loader on the initial router creation
3839
- function isUnhydratedRoute(state: RouterState, route: AgnosticDataRouteObject) {
3840
- if (!route.loader) {
3841
- return false;
3842
- }
3843
- if (route.loader.hydrate) {
3844
- return true;
3845
- }
3846
- return (
3847
- state.loaderData[route.id] === undefined &&
3848
- (!state.errors ||
3849
- // Loader ran but errored - don't re-run
3850
- state.errors[route.id] === undefined)
3851
- );
3852
- }
3853
-
3854
3901
  function isNewLoader(
3855
3902
  currentLoaderData: RouteData,
3856
3903
  currentMatch: AgnosticDataRouteMatch,
@@ -3980,110 +4027,132 @@ async function loadLazyRouteModule(
3980
4027
  return routeToUpdate;
3981
4028
  }
3982
4029
 
3983
- function createCallLoaderOrAction(dataStrategy: DataStrategyFunction) {
3984
- return async (
3985
- type: "loader" | "action",
3986
- request: Request,
3987
- match: AgnosticDataRouteMatch,
3988
- matches: AgnosticDataRouteMatch[],
3989
- manifest: RouteManifest,
3990
- mapRouteProperties: MapRoutePropertiesFunction,
3991
- basename: string,
3992
- v7_relativeSplatPath: boolean,
3993
- opts: {
3994
- isStaticRequest?: boolean;
3995
- isRouteRequest?: boolean;
3996
- requestContext?: unknown;
3997
- } = {}
3998
- ): Promise<DataResult> => {
3999
- let [result] = await dataStrategy({
4000
- matches: [
4001
- finesseToAgnosticDataStrategyMatch(match, mapRouteProperties, manifest),
4002
- ],
4003
- request,
4004
- type,
4005
- defaultStrategy(match) {
4006
- return callLoaderOrActionImplementation(
4007
- type,
4008
- request,
4009
- match,
4010
- matches,
4011
- basename,
4012
- v7_relativeSplatPath,
4013
- opts
4014
- );
4015
- },
4016
- });
4017
-
4018
- return result;
4019
- };
4030
+ // Default implementation of `dataStrategy` which fetches all loaders in parallel
4031
+ function defaultDataStrategy(
4032
+ opts: DataStrategyFunctionArgs
4033
+ ): ReturnType<DataStrategyFunction> {
4034
+ return Promise.all(opts.matches.map((m) => m.bikeshed_loadRoute()));
4020
4035
  }
4021
4036
 
4022
- function finesseToAgnosticDataStrategyMatch(
4023
- match: AgnosticDataRouteMatch,
4037
+ async function callDataStrategyImpl(
4038
+ dataStrategyImpl: DataStrategyFunction,
4039
+ type: "loader" | "action",
4040
+ request: Request,
4041
+ matchesToLoad: AgnosticDataRouteMatch[],
4042
+ matches: AgnosticDataRouteMatch[],
4043
+ manifest: RouteManifest,
4024
4044
  mapRouteProperties: MapRoutePropertiesFunction,
4025
- manifest: RouteManifest
4026
- ): AgnosticDataStrategyMatch {
4027
- let loadRoutePromise: Promise<AgnosticDataRouteObject> | undefined;
4028
-
4029
- if (match.route.lazy) {
4030
- try {
4031
- loadRoutePromise = loadLazyRouteModule(
4032
- match.route,
4033
- mapRouteProperties,
4034
- manifest
4035
- );
4036
- } catch (error) {
4037
- loadRoutePromise = Promise.reject(error);
4038
- }
4039
- }
4045
+ requestContext?: unknown
4046
+ ): Promise<HandlerResult[]> {
4047
+ let routeIdsToLoad = matchesToLoad.reduce(
4048
+ (acc, m) => acc.add(m.route.id),
4049
+ new Set<string>()
4050
+ );
4051
+ let loadedMatches = new Set<string>();
4052
+
4053
+ // Send all matches here to allow for a middleware-type implementation.
4054
+ // handler will be a no-op for unneeded routes and we filter those results
4055
+ // back out below.
4056
+ let results = await dataStrategyImpl({
4057
+ matches: matches.map((match) => {
4058
+ // `bikeshed_loadRoute` encapsulates the route.lazy, executing the
4059
+ // loader/action, and mapping return values/thrown errors to a
4060
+ // HandlerResult. Users can pass a callback to take fine-grained control
4061
+ // over the execution of the loader/action
4062
+ let bikeshed_loadRoute: DataStrategyMatch["bikeshed_loadRoute"] = (
4063
+ handlerOverride
4064
+ ) => {
4065
+ loadedMatches.add(match.route.id);
4066
+ return routeIdsToLoad.has(match.route.id)
4067
+ ? callLoaderOrAction(
4068
+ type,
4069
+ request,
4070
+ match,
4071
+ manifest,
4072
+ mapRouteProperties,
4073
+ handlerOverride,
4074
+ requestContext
4075
+ )
4076
+ : // TODO: What's the best thing to do here - return an empty "success" result?
4077
+ // Or return a success result with the current route loader/action data?
4078
+ // We strip these results out if the route didn't need to be revalidated in
4079
+ // `callDataStrategy` so it doesn't matter for us. It's more of a question
4080
+ // of whether exposing the current data to the user is useful?
4081
+ Promise.resolve({ type: ResultType.data, result: undefined });
4082
+ };
4040
4083
 
4041
- if (!loadRoutePromise) {
4042
- loadRoutePromise = Promise.resolve(match.route);
4043
- }
4084
+ return {
4085
+ ...match,
4086
+ bikeshed_loadRoute,
4087
+ };
4088
+ }),
4089
+ request,
4090
+ params: matches[0].params,
4091
+ });
4044
4092
 
4045
- loadRoutePromise.catch(() => {});
4093
+ // Throw if any loadRoute implementations not called since they are what
4094
+ // ensures a route is fully loaded
4095
+ // Throw if any loadRoute implementations not called since they are what
4096
+ // ensure a route is fully loaded
4097
+ matches.forEach((m) =>
4098
+ invariant(
4099
+ loadedMatches.has(m.route.id),
4100
+ `\`match.bikeshed_loadRoute()\` was not called for route id "${m.route.id}". ` +
4101
+ "You must call `match.bikeshed_loadRoute()` on every match passed to " +
4102
+ "`dataStrategy` to ensure all routes are properly loaded."
4103
+ )
4104
+ );
4046
4105
 
4047
- return {
4048
- ...match,
4049
- route: Object.assign(
4050
- loadRoutePromise,
4051
- match.route
4052
- ) as unknown as LazyRoutePromise,
4053
- };
4106
+ // Filter out any middleware-only matches for which we didn't need to run handlers
4107
+ return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id));
4054
4108
  }
4055
4109
 
4056
- async function callLoaderOrActionImplementation(
4110
+ // Default logic for calling a loader/action is the user has no specified a dataStrategy
4111
+ async function callLoaderOrAction(
4057
4112
  type: "loader" | "action",
4058
4113
  request: Request,
4059
- match: AgnosticDataStrategyMatch,
4060
- matches: AgnosticDataRouteMatch[],
4061
- basename: string,
4062
- v7_relativeSplatPath: boolean,
4063
- opts: {
4064
- isStaticRequest?: boolean;
4065
- isRouteRequest?: boolean;
4066
- requestContext?: unknown;
4067
- } = {}
4068
- ): Promise<DataResult> {
4069
- let resultType;
4114
+ match: AgnosticDataRouteMatch,
4115
+ manifest: RouteManifest,
4116
+ mapRouteProperties: MapRoutePropertiesFunction,
4117
+ handlerOverride: Parameters<DataStrategyMatch["bikeshed_loadRoute"]>[0],
4118
+ staticContext?: unknown
4119
+ ): Promise<HandlerResult> {
4070
4120
  let result;
4071
4121
  let onReject: (() => void) | undefined;
4072
4122
 
4073
- let runHandler = (handler: ActionFunction | LoaderFunction) => {
4123
+ let runHandler = (
4124
+ handler: AgnosticRouteObject["loader"] | AgnosticRouteObject["action"]
4125
+ ) => {
4074
4126
  // Setup a promise we can race against so that abort signals short circuit
4075
4127
  let reject: () => void;
4076
4128
  let abortPromise = new Promise((_, r) => (reject = r));
4077
4129
  onReject = () => reject();
4078
4130
  request.signal.addEventListener("abort", onReject);
4079
- return Promise.race([
4080
- handler({
4081
- request,
4082
- params: match.params,
4083
- context: opts.requestContext,
4084
- }),
4085
- abortPromise,
4086
- ]);
4131
+
4132
+ let runHandlerForReal = (ctx?: unknown) => {
4133
+ if (typeof handler !== "function") {
4134
+ return Promise.reject(
4135
+ new Error(
4136
+ `You cannot call the handler for a route which defines a boolean ` +
4137
+ `"${type}" [routeId: ${match.route.id}]`
4138
+ )
4139
+ );
4140
+ }
4141
+ return handler(
4142
+ {
4143
+ request,
4144
+ params: match.params,
4145
+ context: staticContext,
4146
+ },
4147
+ ...(ctx !== undefined ? [ctx] : [])
4148
+ );
4149
+ };
4150
+
4151
+ let handlerPromise = handlerOverride
4152
+ ? handlerOverride(async (ctx: unknown) => runHandlerForReal(ctx))
4153
+ : runHandlerForReal();
4154
+
4155
+ return Promise.race([handlerPromise, abortPromise]);
4087
4156
  };
4088
4157
 
4089
4158
  try {
@@ -4100,7 +4169,7 @@ async function callLoaderOrActionImplementation(
4100
4169
  runHandler(handler).catch((e) => {
4101
4170
  handlerError = e;
4102
4171
  }),
4103
- match.route,
4172
+ loadLazyRouteModule(match.route, mapRouteProperties, manifest),
4104
4173
  ]);
4105
4174
  if (handlerError) {
4106
4175
  throw handlerError;
@@ -4108,11 +4177,11 @@ async function callLoaderOrActionImplementation(
4108
4177
  result = values[0];
4109
4178
  } else {
4110
4179
  // Load lazy route module, then run any returned handler
4111
- let route = await match.route;
4180
+ await loadLazyRouteModule(match.route, mapRouteProperties, manifest);
4112
4181
 
4113
- handler = route[type];
4182
+ handler = match.route[type];
4114
4183
  if (handler) {
4115
- // Handler still run even if we got interrupted to maintain consistency
4184
+ // Handler still runs even if we got interrupted to maintain consistency
4116
4185
  // with un-abortable behavior of handler execution on non-lazy or
4117
4186
  // previously-lazy-loaded routes
4118
4187
  result = await runHandler(handler);
@@ -4127,7 +4196,7 @@ async function callLoaderOrActionImplementation(
4127
4196
  } else {
4128
4197
  // lazy() route has no loader to run. Short circuit here so we don't
4129
4198
  // hit the invariant below that errors on returning undefined.
4130
- return { type: ResultType.data, data: undefined };
4199
+ return { type: ResultType.data, result: undefined };
4131
4200
  }
4132
4201
  }
4133
4202
  } else if (!handler) {
@@ -4147,82 +4216,22 @@ async function callLoaderOrActionImplementation(
4147
4216
  `function. Please return a value or \`null\`.`
4148
4217
  );
4149
4218
  } catch (e) {
4150
- resultType = ResultType.error;
4151
- result = e;
4219
+ return { type: ResultType.error, result: e };
4152
4220
  } finally {
4153
4221
  if (onReject) {
4154
4222
  request.signal.removeEventListener("abort", onReject);
4155
4223
  }
4156
4224
  }
4157
4225
 
4158
- if (isResponse(result)) {
4159
- let status = result.status;
4160
-
4161
- // Process redirects
4162
- if (redirectStatusCodes.has(status)) {
4163
- let location = result.headers.get("Location");
4164
- invariant(
4165
- location,
4166
- "Redirects returned/thrown from loaders/actions must have a Location header"
4167
- );
4168
-
4169
- // Support relative routing in internal redirects
4170
- if (!ABSOLUTE_URL_REGEX.test(location)) {
4171
- location = normalizeTo(
4172
- new URL(request.url),
4173
- matches.slice(
4174
- 0,
4175
- matches.findIndex((m) => m.route.id === match.route.id) + 1
4176
- ),
4177
- basename,
4178
- true,
4179
- location,
4180
- v7_relativeSplatPath
4181
- );
4182
- } else if (!opts.isStaticRequest) {
4183
- // Strip off the protocol+origin for same-origin + same-basename absolute
4184
- // redirects. If this is a static request, we can let it go back to the
4185
- // browser as-is
4186
- let currentUrl = new URL(request.url);
4187
- let url = location.startsWith("//")
4188
- ? new URL(currentUrl.protocol + location)
4189
- : new URL(location);
4190
- let isSameBasename = stripBasename(url.pathname, basename) != null;
4191
- if (url.origin === currentUrl.origin && isSameBasename) {
4192
- location = url.pathname + url.search + url.hash;
4193
- }
4194
- }
4195
-
4196
- // Don't process redirects in the router during static requests requests.
4197
- // Instead, throw the Response and let the server handle it with an HTTP
4198
- // redirect. We also update the Location header in place in this flow so
4199
- // basename and relative routing is taken into account
4200
- if (opts.isStaticRequest) {
4201
- result.headers.set("Location", location);
4202
- throw result;
4203
- }
4204
-
4205
- return {
4206
- type: ResultType.redirect,
4207
- status,
4208
- location,
4209
- revalidate: result.headers.get("X-Remix-Revalidate") !== null,
4210
- reloadDocument: result.headers.get("X-Remix-Reload-Document") !== null,
4211
- };
4212
- }
4226
+ return { type: ResultType.data, result };
4227
+ }
4213
4228
 
4214
- // For SSR single-route requests, we want to hand Responses back directly
4215
- // without unwrapping. We do this with the QueryRouteResponse wrapper
4216
- // interface so we can know whether it was returned or thrown
4217
- if (opts.isRouteRequest) {
4218
- let queryRouteResponse: QueryRouteResponse = {
4219
- type:
4220
- resultType === ResultType.error ? ResultType.error : ResultType.data,
4221
- response: result,
4222
- };
4223
- throw queryRouteResponse;
4224
- }
4229
+ async function convertHandlerResultToDataResult(
4230
+ handlerResult: HandlerResult
4231
+ ): Promise<DataResult> {
4232
+ let { result, type } = handlerResult;
4225
4233
 
4234
+ if (isResponse(result)) {
4226
4235
  let data: any;
4227
4236
 
4228
4237
  try {
@@ -4230,7 +4239,11 @@ async function callLoaderOrActionImplementation(
4230
4239
  // Check between word boundaries instead of startsWith() due to the last
4231
4240
  // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type
4232
4241
  if (contentType && /\bapplication\/json\b/.test(contentType)) {
4233
- data = await result.json();
4242
+ if (result.body == null) {
4243
+ data = null;
4244
+ } else {
4245
+ data = await result.json();
4246
+ }
4234
4247
  } else {
4235
4248
  data = await result.text();
4236
4249
  }
@@ -4238,24 +4251,23 @@ async function callLoaderOrActionImplementation(
4238
4251
  return { type: ResultType.error, error: e };
4239
4252
  }
4240
4253
 
4241
- if (resultType === ResultType.error) {
4254
+ if (type === ResultType.error) {
4242
4255
  return {
4243
- type: resultType,
4244
- error: new ErrorResponseImpl(status, result.statusText, data),
4245
- headers: result.headers,
4256
+ type,
4257
+ error: new ErrorResponseImpl(result.status, result.statusText, data),
4258
+ response: result,
4246
4259
  };
4247
4260
  }
4248
4261
 
4249
4262
  return {
4250
4263
  type: ResultType.data,
4251
4264
  data,
4252
- statusCode: result.status,
4253
- headers: result.headers,
4265
+ response: result,
4254
4266
  };
4255
4267
  }
4256
4268
 
4257
- if (resultType === ResultType.error) {
4258
- return { type: resultType, error: result };
4269
+ if (type === ResultType.error) {
4270
+ return { type, error: result };
4259
4271
  }
4260
4272
 
4261
4273
  if (isDeferredData(result)) {
@@ -4270,6 +4282,40 @@ async function callLoaderOrActionImplementation(
4270
4282
  return { type: ResultType.data, data: result };
4271
4283
  }
4272
4284
 
4285
+ // Support relative routing in internal redirects
4286
+ function normalizeRelativeRoutingRedirectResponse(
4287
+ response: Response,
4288
+ request: Request,
4289
+ routeId: string,
4290
+ matches: AgnosticDataRouteMatch[],
4291
+ basename: string,
4292
+ v7_relativeSplatPath: boolean
4293
+ ) {
4294
+ let location = response.headers.get("Location");
4295
+ invariant(
4296
+ location,
4297
+ "Redirects returned/thrown from loaders/actions must have a Location header"
4298
+ );
4299
+
4300
+ if (!ABSOLUTE_URL_REGEX.test(location)) {
4301
+ let trimmedMatches = matches.slice(
4302
+ 0,
4303
+ matches.findIndex((m) => m.route.id === routeId) + 1
4304
+ );
4305
+ location = normalizeTo(
4306
+ new URL(request.url),
4307
+ trimmedMatches,
4308
+ basename,
4309
+ true,
4310
+ location,
4311
+ v7_relativeSplatPath
4312
+ );
4313
+ response.headers.set("Location", location);
4314
+ }
4315
+
4316
+ return response;
4317
+ }
4318
+
4273
4319
  // Utility method for creating the Request instances for loaders/actions during
4274
4320
  // client-side navigations and fetches. During SSR we will always have a
4275
4321
  // Request instance from the static handler (query/queryRoute)
@@ -4388,28 +4434,35 @@ function processRouteLoaderData(
4388
4434
  ? result.error.status
4389
4435
  : 500;
4390
4436
  }
4391
- if (result.headers) {
4392
- loaderHeaders[id] = result.headers;
4437
+ if (result.response) {
4438
+ loaderHeaders[id] = result.response.headers;
4393
4439
  }
4394
4440
  } else {
4395
4441
  if (isDeferredResult(result)) {
4396
4442
  activeDeferreds.set(id, result.deferredData);
4397
4443
  loaderData[id] = result.deferredData.data;
4444
+ // Error status codes always override success status codes, but if all
4445
+ // loaders are successful we take the deepest status code.
4446
+ if (
4447
+ result.statusCode != null &&
4448
+ result.statusCode !== 200 &&
4449
+ !foundError
4450
+ ) {
4451
+ statusCode = result.statusCode;
4452
+ }
4453
+ if (result.headers) {
4454
+ loaderHeaders[id] = result.headers;
4455
+ }
4398
4456
  } else {
4399
4457
  loaderData[id] = result.data;
4400
- }
4401
-
4402
- // Error status codes always override success status codes, but if all
4403
- // loaders are successful we take the deepest status code.
4404
- if (
4405
- result.statusCode != null &&
4406
- result.statusCode !== 200 &&
4407
- !foundError
4408
- ) {
4409
- statusCode = result.statusCode;
4410
- }
4411
- if (result.headers) {
4412
- loaderHeaders[id] = result.headers;
4458
+ // Error status codes always override success status codes, but if all
4459
+ // loaders are successful we take the deepest status code.
4460
+ if (result.response) {
4461
+ if (result.response.status !== 200 && !foundError) {
4462
+ statusCode = result.response.status;
4463
+ }
4464
+ loaderHeaders[id] = result.response.headers;
4465
+ }
4413
4466
  }
4414
4467
  }
4415
4468
  });
@@ -4655,6 +4708,22 @@ function isHashChangeOnly(a: Location, b: Location): boolean {
4655
4708
  return false;
4656
4709
  }
4657
4710
 
4711
+ function isHandlerResult(result: unknown): result is HandlerResult {
4712
+ return (
4713
+ result != null &&
4714
+ typeof result === "object" &&
4715
+ "type" in result &&
4716
+ "result" in result &&
4717
+ (result.type === ResultType.data || result.type === ResultType.error)
4718
+ );
4719
+ }
4720
+
4721
+ function isRedirectHandlerResult(result: HandlerResult) {
4722
+ return (
4723
+ isResponse(result.result) && redirectStatusCodes.has(result.result.status)
4724
+ );
4725
+ }
4726
+
4658
4727
  function isDeferredResult(result: DataResult): result is DeferredResult {
4659
4728
  return result.type === ResultType.deferred;
4660
4729
  }
@@ -4699,14 +4768,6 @@ function isRedirectResponse(result: any): result is Response {
4699
4768
  return status >= 300 && status <= 399 && location != null;
4700
4769
  }
4701
4770
 
4702
- function isQueryRouteResponse(obj: any): obj is QueryRouteResponse {
4703
- return (
4704
- obj &&
4705
- isResponse(obj.response) &&
4706
- (obj.type === ResultType.data || obj.type === ResultType.error)
4707
- );
4708
- }
4709
-
4710
4771
  function isValidMethod(method: string): method is FormMethod | V7_FormMethod {
4711
4772
  return validRequestMethods.has(method.toLowerCase() as FormMethod);
4712
4773
  }