@remix-run/router 0.0.0-experimental-e7e9ce6e → 0.0.0-experimental-5f6f59a6

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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @remix-run/router v0.0.0-experimental-e7e9ce6e
2
+ * @remix-run/router v0.0.0-experimental-5f6f59a6
3
3
  *
4
4
  * Copyright (c) Remix Software Inc.
5
5
  *
@@ -92,7 +92,7 @@ function createMemoryHistory(options) {
92
92
  }
93
93
 
94
94
  let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
95
- warning$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
95
+ warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
96
96
  return location;
97
97
  }
98
98
 
@@ -283,7 +283,7 @@ function createHashHistory(options) {
283
283
  }
284
284
 
285
285
  function validateHashLocation(location, to) {
286
- warning$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
286
+ warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
287
287
  }
288
288
 
289
289
  return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
@@ -301,8 +301,7 @@ function invariant(value, message) {
301
301
  throw new Error(message);
302
302
  }
303
303
  }
304
-
305
- function warning$1(cond, message) {
304
+ function warning(cond, message) {
306
305
  if (!cond) {
307
306
  // eslint-disable-next-line no-console
308
307
  if (typeof console !== "undefined") console.warn(message);
@@ -565,40 +564,54 @@ let ResultType;
565
564
  ResultType["error"] = "error";
566
565
  })(ResultType || (ResultType = {}));
567
566
 
567
+ const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]);
568
+ /**
569
+ * lazy() function to load a route definition, which can add non-matching
570
+ * related properties to a route
571
+ */
572
+
568
573
  function isIndexRoute(route) {
569
574
  return route.index === true;
570
575
  } // Walk the route tree generating unique IDs where necessary so we are working
571
576
  // solely with AgnosticDataRouteObject's within the Router
572
577
 
573
578
 
574
- function convertRoutesToDataRoutes(routes, parentPath, allIds) {
579
+ function convertRoutesToDataRoutes(routes, detectErrorBoundary, parentPath, manifest) {
575
580
  if (parentPath === void 0) {
576
581
  parentPath = [];
577
582
  }
578
583
 
579
- if (allIds === void 0) {
580
- allIds = new Set();
584
+ if (manifest === void 0) {
585
+ manifest = {};
581
586
  }
582
587
 
583
588
  return routes.map((route, index) => {
584
589
  let treePath = [...parentPath, index];
585
590
  let id = typeof route.id === "string" ? route.id : treePath.join("-");
586
591
  invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
587
- invariant(!allIds.has(id), "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages");
588
- allIds.add(id);
592
+ invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages");
589
593
 
590
594
  if (isIndexRoute(route)) {
591
595
  let indexRoute = _extends({}, route, {
596
+ hasErrorBoundary: detectErrorBoundary(route),
592
597
  id
593
598
  });
594
599
 
600
+ manifest[id] = indexRoute;
595
601
  return indexRoute;
596
602
  } else {
597
603
  let pathOrLayoutRoute = _extends({}, route, {
598
604
  id,
599
- children: route.children ? convertRoutesToDataRoutes(route.children, treePath, allIds) : undefined
605
+ hasErrorBoundary: detectErrorBoundary(route),
606
+ children: undefined
600
607
  });
601
608
 
609
+ manifest[id] = pathOrLayoutRoute;
610
+
611
+ if (route.children) {
612
+ pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, detectErrorBoundary, treePath, manifest);
613
+ }
614
+
602
615
  return pathOrLayoutRoute;
603
616
  }
604
617
  });
@@ -845,45 +858,42 @@ function generatePath(originalPath, params) {
845
858
  if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
846
859
  warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\"."));
847
860
  path = path.replace(/\*$/, "/*");
848
- }
861
+ } // ensure `/` is added at the beginning if the path is absolute
849
862
 
850
- return path.replace(/^:(\w+)(\??)/g, (_, key, optional) => {
851
- let param = params[key];
852
863
 
853
- if (optional === "?") {
854
- return param == null ? "" : param;
855
- }
864
+ const prefix = path.startsWith("/") ? "/" : "";
865
+ const segments = path.split(/\/+/).map((segment, index, array) => {
866
+ const isLastSegment = index === array.length - 1; // only apply the splat if it's the last segment
856
867
 
857
- if (param == null) {
858
- invariant(false, "Missing \":" + key + "\" param");
868
+ if (isLastSegment && segment === "*") {
869
+ const star = "*";
870
+ const starParam = params[star]; // Apply the splat
871
+
872
+ return starParam;
859
873
  }
860
874
 
861
- return param;
862
- }).replace(/\/:(\w+)(\??)/g, (_, key, optional) => {
863
- let param = params[key];
875
+ const keyMatch = segment.match(/^:(\w+)(\??)$/);
864
876
 
865
- if (optional === "?") {
866
- return param == null ? "" : "/" + param;
867
- }
877
+ if (keyMatch) {
878
+ const [, key, optional] = keyMatch;
879
+ let param = params[key];
868
880
 
869
- if (param == null) {
870
- invariant(false, "Missing \":" + key + "\" param");
871
- }
881
+ if (optional === "?") {
882
+ return param == null ? "" : param;
883
+ }
872
884
 
873
- return "/" + param;
874
- }) // Remove any optional markers from optional static segments
875
- .replace(/\?/g, "").replace(/(\/?)\*/, (_, prefix, __, str) => {
876
- const star = "*";
885
+ if (param == null) {
886
+ invariant(false, "Missing \":" + key + "\" param");
887
+ }
877
888
 
878
- if (params[star] == null) {
879
- // If no splat was provided, trim the trailing slash _unless_ it's
880
- // the entire path
881
- return str === "/*" ? "/" : "";
882
- } // Apply the splat
889
+ return param;
890
+ } // Remove any optional markers from optional static segments
883
891
 
884
892
 
885
- return "" + prefix + params[star];
886
- });
893
+ return segment.replace(/\?$/g, "");
894
+ }) // Remove empty segments
895
+ .filter(segment => !!segment);
896
+ return prefix + segments.join("/");
887
897
  }
888
898
  /**
889
899
  * A PathPattern is used to match on some portion of a URL pathname.
@@ -1011,25 +1021,6 @@ function stripBasename(pathname, basename) {
1011
1021
 
1012
1022
  return pathname.slice(startIndex) || "/";
1013
1023
  }
1014
- /**
1015
- * @private
1016
- */
1017
-
1018
- function warning(cond, message) {
1019
- if (!cond) {
1020
- // eslint-disable-next-line no-console
1021
- if (typeof console !== "undefined") console.warn(message);
1022
-
1023
- try {
1024
- // Welcome to debugging @remix-run/router!
1025
- //
1026
- // This error is thrown as a convenience so you can more easily
1027
- // find the source for a warning that appears in the console by
1028
- // enabling "pause on exceptions" in your JavaScript debugger.
1029
- throw new Error(message); // eslint-disable-next-line no-empty
1030
- } catch (e) {}
1031
- }
1032
- }
1033
1024
  /**
1034
1025
  * Returns a resolved path object relative to the given pathname.
1035
1026
  *
@@ -1478,7 +1469,9 @@ const IDLE_BLOCKER = {
1478
1469
  };
1479
1470
  const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
1480
1471
  const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
1481
- const isServer = !isBrowser; //#endregion
1472
+ const isServer = !isBrowser;
1473
+
1474
+ const defaultDetectErrorBoundary = route => Boolean(route.hasErrorBoundary); //#endregion
1482
1475
  ////////////////////////////////////////////////////////////////////////////////
1483
1476
  //#region createRouter
1484
1477
  ////////////////////////////////////////////////////////////////////////////////
@@ -1487,9 +1480,14 @@ const isServer = !isBrowser; //#endregion
1487
1480
  * Create a router and listen to history POP navigations
1488
1481
  */
1489
1482
 
1483
+
1490
1484
  function createRouter(init) {
1491
1485
  invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
1492
- let dataRoutes = convertRoutesToDataRoutes(init.routes);
1486
+ let detectErrorBoundary = init.detectErrorBoundary || defaultDetectErrorBoundary; // Routes keyed by ID
1487
+
1488
+ let manifest = {}; // Routes in tree format for matching
1489
+
1490
+ let dataRoutes = convertRoutesToDataRoutes(init.routes, detectErrorBoundary, undefined, manifest);
1493
1491
  let inFlightDataRoutes; // Cleanup function for history
1494
1492
 
1495
1493
  let unlistenHistory = null; // Externally-provided functions to call on all state changes
@@ -1527,7 +1525,10 @@ function createRouter(init) {
1527
1525
  };
1528
1526
  }
1529
1527
 
1530
- let initialized = !initialMatches.some(m => m.route.loader) || init.hydrationData != null;
1528
+ let initialized = // All initialMatches need to be loaded before we're ready. If we have lazy
1529
+ // functions around still then we'll need to run them in initialize()
1530
+ !initialMatches.some(m => m.route.lazy) && ( // And we have to either have no loaders or have been provided hydrationData
1531
+ !initialMatches.some(m => m.route.loader) || init.hydrationData != null);
1531
1532
  let router;
1532
1533
  let state = {
1533
1534
  historyAction: init.history.action,
@@ -1651,12 +1652,35 @@ function createRouter(init) {
1651
1652
  }
1652
1653
 
1653
1654
  return startNavigation(historyAction, location);
1654
- }); // Kick off initial data load if needed. Use Pop to avoid modifying history
1655
+ });
1655
1656
 
1656
- if (!state.initialized) {
1657
- startNavigation(exports.Action.Pop, state.location);
1657
+ if (state.initialized) {
1658
+ return router;
1658
1659
  }
1659
1660
 
1661
+ let lazyMatches = state.matches.filter(m => m.route.lazy);
1662
+
1663
+ if (lazyMatches.length === 0) {
1664
+ // Kick off initial data load if needed. Use Pop to avoid modifying history
1665
+ startNavigation(exports.Action.Pop, state.location);
1666
+ return router;
1667
+ } // Load lazy modules, then kick off initial data load if needed
1668
+
1669
+
1670
+ let lazyPromises = lazyMatches.map(m => loadLazyRouteModule(m.route, detectErrorBoundary, manifest));
1671
+ Promise.all(lazyPromises).then(() => {
1672
+ let initialized = !state.matches.some(m => m.route.loader) || init.hydrationData != null;
1673
+
1674
+ if (initialized) {
1675
+ // We already have required loaderData so we can just set initialized
1676
+ updateState({
1677
+ initialized: true
1678
+ });
1679
+ } else {
1680
+ // We still need to kick off initial data loads
1681
+ startNavigation(exports.Action.Pop, state.location);
1682
+ }
1683
+ });
1660
1684
  return router;
1661
1685
  } // Clean up a router and it's side effects
1662
1686
 
@@ -2002,7 +2026,7 @@ function createRouter(init) {
2002
2026
  let result;
2003
2027
  let actionMatch = getTargetMatch(matches, location);
2004
2028
 
2005
- if (!actionMatch.route.action) {
2029
+ if (!actionMatch.route.action && !actionMatch.route.lazy) {
2006
2030
  result = {
2007
2031
  type: ResultType.error,
2008
2032
  error: getInternalRouterError(405, {
@@ -2012,7 +2036,7 @@ function createRouter(init) {
2012
2036
  })
2013
2037
  };
2014
2038
  } else {
2015
- result = await callLoaderOrAction("action", request, actionMatch, matches, router.basename);
2039
+ result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, detectErrorBoundary, router.basename);
2016
2040
 
2017
2041
  if (request.signal.aborted) {
2018
2042
  return {
@@ -2137,8 +2161,7 @@ function createRouter(init) {
2137
2161
  formMethod: undefined,
2138
2162
  formAction: undefined,
2139
2163
  formEncType: undefined,
2140
- formData: undefined,
2141
- " _hasFetcherDoneAnything ": true
2164
+ formData: undefined
2142
2165
  };
2143
2166
  state.fetchers.set(rf.key, revalidatingFetcher);
2144
2167
  });
@@ -2258,7 +2281,7 @@ function createRouter(init) {
2258
2281
  interruptActiveLoads();
2259
2282
  fetchLoadMatches.delete(key);
2260
2283
 
2261
- if (!match.route.action) {
2284
+ if (!match.route.action && !match.route.lazy) {
2262
2285
  let error = getInternalRouterError(405, {
2263
2286
  method: submission.formMethod,
2264
2287
  pathname: path,
@@ -2274,8 +2297,7 @@ function createRouter(init) {
2274
2297
  let fetcher = _extends({
2275
2298
  state: "submitting"
2276
2299
  }, submission, {
2277
- data: existingFetcher && existingFetcher.data,
2278
- " _hasFetcherDoneAnything ": true
2300
+ data: existingFetcher && existingFetcher.data
2279
2301
  });
2280
2302
 
2281
2303
  state.fetchers.set(key, fetcher);
@@ -2286,7 +2308,7 @@ function createRouter(init) {
2286
2308
  let abortController = new AbortController();
2287
2309
  let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
2288
2310
  fetchControllers.set(key, abortController);
2289
- let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, router.basename);
2311
+ let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, manifest, detectErrorBoundary, router.basename);
2290
2312
 
2291
2313
  if (fetchRequest.signal.aborted) {
2292
2314
  // We can delete this so long as we weren't aborted by ou our own fetcher
@@ -2305,17 +2327,14 @@ function createRouter(init) {
2305
2327
  let loadingFetcher = _extends({
2306
2328
  state: "loading"
2307
2329
  }, submission, {
2308
- data: undefined,
2309
- " _hasFetcherDoneAnything ": true
2330
+ data: undefined
2310
2331
  });
2311
2332
 
2312
2333
  state.fetchers.set(key, loadingFetcher);
2313
2334
  updateState({
2314
2335
  fetchers: new Map(state.fetchers)
2315
2336
  });
2316
- return startRedirectNavigation(state, actionResult, {
2317
- isFetchActionRedirect: true
2318
- });
2337
+ return startRedirectNavigation(state, actionResult);
2319
2338
  } // Process any non-redirect errors thrown
2320
2339
 
2321
2340
 
@@ -2343,9 +2362,7 @@ function createRouter(init) {
2343
2362
  let loadFetcher = _extends({
2344
2363
  state: "loading",
2345
2364
  data: actionResult.data
2346
- }, submission, {
2347
- " _hasFetcherDoneAnything ": true
2348
- });
2365
+ }, submission);
2349
2366
 
2350
2367
  state.fetchers.set(key, loadFetcher);
2351
2368
  let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, fetchLoadMatches, routesToUse, init.basename, {
@@ -2364,8 +2381,7 @@ function createRouter(init) {
2364
2381
  formMethod: undefined,
2365
2382
  formAction: undefined,
2366
2383
  formEncType: undefined,
2367
- formData: undefined,
2368
- " _hasFetcherDoneAnything ": true
2384
+ formData: undefined
2369
2385
  };
2370
2386
  state.fetchers.set(staleKey, revalidatingFetcher);
2371
2387
  fetchControllers.set(staleKey, abortController);
@@ -2403,8 +2419,7 @@ function createRouter(init) {
2403
2419
  formMethod: undefined,
2404
2420
  formAction: undefined,
2405
2421
  formEncType: undefined,
2406
- formData: undefined,
2407
- " _hasFetcherDoneAnything ": true
2422
+ formData: undefined
2408
2423
  };
2409
2424
  state.fetchers.set(key, doneFetcher);
2410
2425
  let didAbortFetchLoads = abortStaleFetchLoads(loadId); // If we are currently in a navigation loading state and this fetcher is
@@ -2445,8 +2460,7 @@ function createRouter(init) {
2445
2460
  formEncType: undefined,
2446
2461
  formData: undefined
2447
2462
  }, submission, {
2448
- data: existingFetcher && existingFetcher.data,
2449
- " _hasFetcherDoneAnything ": true
2463
+ data: existingFetcher && existingFetcher.data
2450
2464
  });
2451
2465
 
2452
2466
  state.fetchers.set(key, loadingFetcher);
@@ -2457,7 +2471,7 @@ function createRouter(init) {
2457
2471
  let abortController = new AbortController();
2458
2472
  let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
2459
2473
  fetchControllers.set(key, abortController);
2460
- let result = await callLoaderOrAction("loader", fetchRequest, match, matches, router.basename); // Deferred isn't supported for fetcher loads, await everything and treat it
2474
+ let result = await callLoaderOrAction("loader", fetchRequest, match, matches, manifest, detectErrorBoundary, router.basename); // Deferred isn't supported for fetcher loads, await everything and treat it
2461
2475
  // as a normal load. resolveDeferredData will return undefined if this
2462
2476
  // fetcher gets aborted, so we just leave result untouched and short circuit
2463
2477
  // below if that happens
@@ -2506,8 +2520,7 @@ function createRouter(init) {
2506
2520
  formMethod: undefined,
2507
2521
  formAction: undefined,
2508
2522
  formEncType: undefined,
2509
- formData: undefined,
2510
- " _hasFetcherDoneAnything ": true
2523
+ formData: undefined
2511
2524
  };
2512
2525
  state.fetchers.set(key, doneFetcher);
2513
2526
  updateState({
@@ -2540,20 +2553,16 @@ function createRouter(init) {
2540
2553
 
2541
2554
  let {
2542
2555
  submission,
2543
- replace,
2544
- isFetchActionRedirect
2556
+ replace
2545
2557
  } = _temp === void 0 ? {} : _temp;
2546
2558
 
2547
2559
  if (redirect.revalidate) {
2548
2560
  isRevalidationRequired = true;
2549
2561
  }
2550
2562
 
2551
- let redirectLocation = createLocation(state.location, redirect.location, // TODO: This can be removed once we get rid of useTransition in Remix v2
2552
- _extends({
2563
+ let redirectLocation = createLocation(state.location, redirect.location, {
2553
2564
  _isRedirect: true
2554
- }, isFetchActionRedirect ? {
2555
- _isFetchActionRedirect: true
2556
- } : {}));
2565
+ });
2557
2566
  invariant(redirectLocation, "Expected a location on the redirect navigation"); // Check if this an absolute external redirect that goes to a new origin
2558
2567
 
2559
2568
  if (ABSOLUTE_URL_REGEX.test(redirect.location) && isBrowser && typeof ((_window = window) == null ? void 0 : _window.location) !== "undefined") {
@@ -2626,9 +2635,9 @@ function createRouter(init) {
2626
2635
  // Call all navigation loaders and revalidating fetcher loaders in parallel,
2627
2636
  // then slice off the results into separate arrays so we can handle them
2628
2637
  // accordingly
2629
- let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, router.basename)), ...fetchersToLoad.map(f => {
2638
+ let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, manifest, detectErrorBoundary, router.basename)), ...fetchersToLoad.map(f => {
2630
2639
  if (f.matches && f.match) {
2631
- return callLoaderOrAction("loader", createClientSideRequest(init.history, f.path, request.signal), f.match, f.matches, router.basename);
2640
+ return callLoaderOrAction("loader", createClientSideRequest(init.history, f.path, request.signal), f.match, f.matches, manifest, detectErrorBoundary, router.basename);
2632
2641
  } else {
2633
2642
  let error = {
2634
2643
  type: ResultType.error,
@@ -2699,8 +2708,7 @@ function createRouter(init) {
2699
2708
  formMethod: undefined,
2700
2709
  formAction: undefined,
2701
2710
  formEncType: undefined,
2702
- formData: undefined,
2703
- " _hasFetcherDoneAnything ": true
2711
+ formData: undefined
2704
2712
  };
2705
2713
  state.fetchers.set(key, doneFetcher);
2706
2714
  }
@@ -2920,7 +2928,9 @@ function createRouter(init) {
2920
2928
  const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
2921
2929
  function createStaticHandler(routes, opts) {
2922
2930
  invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
2923
- let dataRoutes = convertRoutesToDataRoutes(routes);
2931
+ let manifest = {};
2932
+ let detectErrorBoundary = (opts == null ? void 0 : opts.detectErrorBoundary) || defaultDetectErrorBoundary;
2933
+ let dataRoutes = convertRoutesToDataRoutes(routes, detectErrorBoundary, undefined, manifest);
2924
2934
  let basename = (opts ? opts.basename : null) || "/";
2925
2935
  /**
2926
2936
  * The query() method is intended for document requests, in which we want to
@@ -3142,7 +3152,7 @@ function createStaticHandler(routes, opts) {
3142
3152
  async function submit(request, matches, actionMatch, requestContext, isRouteRequest) {
3143
3153
  let result;
3144
3154
 
3145
- if (!actionMatch.route.action) {
3155
+ if (!actionMatch.route.action && !actionMatch.route.lazy) {
3146
3156
  let error = getInternalRouterError(405, {
3147
3157
  method: request.method,
3148
3158
  pathname: new URL(request.url).pathname,
@@ -3158,7 +3168,7 @@ function createStaticHandler(routes, opts) {
3158
3168
  error
3159
3169
  };
3160
3170
  } else {
3161
- result = await callLoaderOrAction("action", request, actionMatch, matches, basename, true, isRouteRequest, requestContext);
3171
+ result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, detectErrorBoundary, basename, true, isRouteRequest, requestContext);
3162
3172
 
3163
3173
  if (request.signal.aborted) {
3164
3174
  let method = isRouteRequest ? "queryRoute" : "query";
@@ -3256,7 +3266,7 @@ function createStaticHandler(routes, opts) {
3256
3266
  async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) {
3257
3267
  let isRouteRequest = routeMatch != null; // Short circuit if we have no loaders to run (queryRoute())
3258
3268
 
3259
- if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader)) {
3269
+ if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {
3260
3270
  throw getInternalRouterError(400, {
3261
3271
  method: request.method,
3262
3272
  pathname: new URL(request.url).pathname,
@@ -3265,7 +3275,7 @@ function createStaticHandler(routes, opts) {
3265
3275
  }
3266
3276
 
3267
3277
  let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]);
3268
- let matchesToLoad = requestMatches.filter(m => m.route.loader); // Short circuit if we have no loaders to run (query())
3278
+ let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy); // Short circuit if we have no loaders to run (query())
3269
3279
 
3270
3280
  if (matchesToLoad.length === 0) {
3271
3281
  return {
@@ -3281,7 +3291,7 @@ function createStaticHandler(routes, opts) {
3281
3291
  };
3282
3292
  }
3283
3293
 
3284
- let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, basename, true, isRouteRequest, requestContext))]);
3294
+ let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, manifest, detectErrorBoundary, basename, true, isRouteRequest, requestContext))]);
3285
3295
 
3286
3296
  if (request.signal.aborted) {
3287
3297
  let method = isRouteRequest ? "queryRoute" : "query";
@@ -3422,6 +3432,11 @@ function getMatchesToLoad(history, state, matches, submission, location, isReval
3422
3432
  let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;
3423
3433
  let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);
3424
3434
  let navigationMatches = boundaryMatches.filter((match, index) => {
3435
+ if (match.route.lazy) {
3436
+ // We haven't loaded this route yet so we don't know if it's got a loader!
3437
+ return true;
3438
+ }
3439
+
3425
3440
  if (match.route.loader == null) {
3426
3441
  return false;
3427
3442
  } // Always call the loader on new route instances and pending defer cancellations
@@ -3535,8 +3550,66 @@ function shouldRevalidateLoader(loaderMatch, arg) {
3535
3550
 
3536
3551
  return arg.defaultShouldRevalidate;
3537
3552
  }
3553
+ /**
3554
+ * Execute route.lazy() methods to lazily load route modules (loader, action,
3555
+ * shouldRevalidate) and update the routeManifest in place which shares objects
3556
+ * with dataRoutes so those get updated as well.
3557
+ */
3558
+
3559
+
3560
+ async function loadLazyRouteModule(route, detectErrorBoundary, manifest) {
3561
+ if (!route.lazy) {
3562
+ return;
3563
+ }
3564
+
3565
+ let lazyRoute = await route.lazy(); // If the lazy route function was executed and removed by another parallel
3566
+ // call then we can return - first lazy() to finish wins because the return
3567
+ // value of lazy is expected to be static
3568
+
3569
+ if (!route.lazy) {
3570
+ return;
3571
+ }
3572
+
3573
+ let routeToUpdate = manifest[route.id];
3574
+ invariant(routeToUpdate, "No route found in manifest"); // Update the route in place. This should be safe because there's no way
3575
+ // we could yet be sitting on this route as we can't get there without
3576
+ // resolving lazy() first.
3577
+ //
3578
+ // This is different than the HMR "update" use-case where we may actively be
3579
+ // on the route being updated. The main concern boils down to "does this
3580
+ // mutation affect any ongoing navigations or any current state.matches
3581
+ // values?". If not, it should be safe to update in place.
3582
+
3583
+ let routeUpdates = {};
3584
+
3585
+ for (let lazyRouteProperty in lazyRoute) {
3586
+ let staticRouteValue = routeToUpdate[lazyRouteProperty];
3587
+ let isPropertyStaticallyDefined = staticRouteValue !== undefined && // This property isn't static since it should always be updated based
3588
+ // on the route updates
3589
+ lazyRouteProperty !== "hasErrorBoundary";
3590
+ warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored."));
3591
+
3592
+ if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
3593
+ routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
3594
+ }
3595
+ } // Mutate the route with the provided updates. Do this first so we pass
3596
+ // the updated version to detectErrorBoundary
3538
3597
 
3539
- async function callLoaderOrAction(type, request, match, matches, basename, isStaticRequest, isRouteRequest, requestContext) {
3598
+
3599
+ Object.assign(routeToUpdate, routeUpdates); // Mutate the `hasErrorBoundary` property on the route based on the route
3600
+ // updates and remove the `lazy` function so we don't resolve the lazy
3601
+ // route again.
3602
+
3603
+ Object.assign(routeToUpdate, {
3604
+ // To keep things framework agnostic, we use the provided
3605
+ // `detectErrorBoundary` function to set the `hasErrorBoundary` route
3606
+ // property since the logic will differ between frameworks.
3607
+ hasErrorBoundary: detectErrorBoundary(_extends({}, routeToUpdate)),
3608
+ lazy: undefined
3609
+ });
3610
+ }
3611
+
3612
+ async function callLoaderOrAction(type, request, match, matches, manifest, detectErrorBoundary, basename, isStaticRequest, isRouteRequest, requestContext) {
3540
3613
  if (basename === void 0) {
3541
3614
  basename = "/";
3542
3615
  }
@@ -3550,29 +3623,70 @@ async function callLoaderOrAction(type, request, match, matches, basename, isSta
3550
3623
  }
3551
3624
 
3552
3625
  let resultType;
3553
- let result; // Setup a promise we can race against so that abort signals short circuit
3554
-
3555
- let reject;
3556
- let abortPromise = new Promise((_, r) => reject = r);
3626
+ let result;
3627
+ let onReject;
3557
3628
 
3558
- let onReject = () => reject();
3629
+ let runHandler = handler => {
3630
+ // Setup a promise we can race against so that abort signals short circuit
3631
+ let reject;
3632
+ let abortPromise = new Promise((_, r) => reject = r);
3559
3633
 
3560
- request.signal.addEventListener("abort", onReject);
3634
+ onReject = () => reject();
3561
3635
 
3562
- try {
3563
- let handler = match.route[type];
3564
- invariant(handler, "Could not find the " + type + " to run on the \"" + match.route.id + "\" route");
3565
- result = await Promise.race([handler({
3636
+ request.signal.addEventListener("abort", onReject);
3637
+ return Promise.race([handler({
3566
3638
  request,
3567
3639
  params: match.params,
3568
3640
  context: requestContext
3569
3641
  }), abortPromise]);
3642
+ };
3643
+
3644
+ try {
3645
+ let handler = match.route[type];
3646
+
3647
+ if (match.route.lazy) {
3648
+ if (handler) {
3649
+ // Run statically defined handler in parallel with lazy()
3650
+ let values = await Promise.all([runHandler(handler), loadLazyRouteModule(match.route, detectErrorBoundary, manifest)]);
3651
+ result = values[0];
3652
+ } else {
3653
+ // Load lazy route module, then run any returned handler
3654
+ await loadLazyRouteModule(match.route, detectErrorBoundary, manifest);
3655
+ handler = match.route[type];
3656
+
3657
+ if (handler) {
3658
+ // Handler still run even if we got interrupted to maintain consistency
3659
+ // with un-abortable behavior of handler execution on non-lazy or
3660
+ // previously-lazy-loaded routes
3661
+ result = await runHandler(handler);
3662
+ } else if (type === "action") {
3663
+ throw getInternalRouterError(405, {
3664
+ method: request.method,
3665
+ pathname: new URL(request.url).pathname,
3666
+ routeId: match.route.id
3667
+ });
3668
+ } else {
3669
+ // lazy() route has no loader to run. Short circuit here so we don't
3670
+ // hit the invariant below that errors on returning undefined.
3671
+ return {
3672
+ type: ResultType.data,
3673
+ data: undefined
3674
+ };
3675
+ }
3676
+ }
3677
+ } else {
3678
+ invariant(handler, "Could not find the " + type + " to run on the \"" + match.route.id + "\" route");
3679
+ result = await runHandler(handler);
3680
+ }
3681
+
3570
3682
  invariant(result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`.");
3571
3683
  } catch (e) {
3572
3684
  resultType = ResultType.error;
3573
3685
  result = e;
3574
3686
  } finally {
3575
- request.signal.removeEventListener("abort", onReject);
3687
+ if (onReject) {
3688
+ request.signal.removeEventListener("abort", onReject);
3689
+ }
3576
3690
  }
3577
3691
 
3578
3692
  if (isResponse(result)) {
@@ -3836,8 +3950,7 @@ function processLoaderData(state, matches, matchesToLoad, results, pendingError,
3836
3950
  formMethod: undefined,
3837
3951
  formAction: undefined,
3838
3952
  formEncType: undefined,
3839
- formData: undefined,
3840
- " _hasFetcherDoneAnything ": true
3953
+ formData: undefined
3841
3954
  };
3842
3955
  state.fetchers.set(key, doneFetcher);
3843
3956
  }
@@ -4099,6 +4212,7 @@ exports.UNSAFE_DeferredData = DeferredData;
4099
4212
  exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes;
4100
4213
  exports.UNSAFE_getPathContributingMatches = getPathContributingMatches;
4101
4214
  exports.UNSAFE_invariant = invariant;
4215
+ exports.UNSAFE_warning = warning;
4102
4216
  exports.createBrowserHistory = createBrowserHistory;
4103
4217
  exports.createHashHistory = createHashHistory;
4104
4218
  exports.createMemoryHistory = createMemoryHistory;
@@ -4120,5 +4234,4 @@ exports.redirect = redirect;
4120
4234
  exports.resolvePath = resolvePath;
4121
4235
  exports.resolveTo = resolveTo;
4122
4236
  exports.stripBasename = stripBasename;
4123
- exports.warning = warning;
4124
4237
  //# sourceMappingURL=router.cjs.js.map