@bleedingdev/modern-js-plugin-tanstack 3.9.0-ultramodern.10 → 3.9.0-ultramodern.12

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.
Files changed (68) hide show
  1. package/dist/cjs/cli/artifacts.js +2 -1
  2. package/dist/cjs/cli/tanstackTypes/canonicalRoutes.js +7 -7
  3. package/dist/cjs/cli/tanstackTypes/shared.js +0 -14
  4. package/dist/cjs/cli/tanstackTypes/source.js +28 -63
  5. package/dist/cjs/runtime/lifecycle.js +0 -3
  6. package/dist/cjs/runtime/loaderBridge.js +10 -4
  7. package/dist/cjs/runtime/navigation.js +102 -0
  8. package/dist/cjs/runtime/plugin.js +6 -1
  9. package/dist/cjs/runtime/plugin.node.js +82 -64
  10. package/dist/cjs/runtime/routeTree/construction.js +19 -61
  11. package/dist/cjs/runtime/routeTree/loaders.js +1 -1
  12. package/dist/cjs/runtime/routeTree/paths.js +0 -6
  13. package/dist/cjs/runtime/utils.js +1 -0
  14. package/dist/cjs/shared/routeDescriptor.js +60 -0
  15. package/dist/esm/cli/artifacts.mjs +2 -1
  16. package/dist/esm/cli/tanstackTypes/canonicalRoutes.mjs +7 -7
  17. package/dist/esm/cli/tanstackTypes/shared.mjs +1 -9
  18. package/dist/esm/cli/tanstackTypes/source.mjs +29 -64
  19. package/dist/esm/runtime/lifecycle.mjs +1 -1
  20. package/dist/esm/runtime/loaderBridge.mjs +8 -5
  21. package/dist/esm/runtime/navigation.mjs +64 -0
  22. package/dist/esm/runtime/plugin.mjs +6 -1
  23. package/dist/esm/runtime/plugin.node.mjs +83 -65
  24. package/dist/esm/runtime/routeTree/construction.mjs +19 -61
  25. package/dist/esm/runtime/routeTree/loaders.mjs +2 -2
  26. package/dist/esm/runtime/routeTree/paths.mjs +1 -4
  27. package/dist/esm/runtime/utils.mjs +1 -0
  28. package/dist/esm/shared/routeDescriptor.mjs +22 -0
  29. package/dist/esm-node/cli/artifacts.mjs +2 -1
  30. package/dist/esm-node/cli/tanstackTypes/canonicalRoutes.mjs +7 -7
  31. package/dist/esm-node/cli/tanstackTypes/shared.mjs +1 -9
  32. package/dist/esm-node/cli/tanstackTypes/source.mjs +29 -64
  33. package/dist/esm-node/runtime/lifecycle.mjs +1 -1
  34. package/dist/esm-node/runtime/loaderBridge.mjs +8 -5
  35. package/dist/esm-node/runtime/navigation.mjs +65 -0
  36. package/dist/esm-node/runtime/plugin.mjs +6 -1
  37. package/dist/esm-node/runtime/plugin.node.mjs +83 -65
  38. package/dist/esm-node/runtime/routeTree/construction.mjs +19 -61
  39. package/dist/esm-node/runtime/routeTree/loaders.mjs +2 -2
  40. package/dist/esm-node/runtime/routeTree/paths.mjs +1 -4
  41. package/dist/esm-node/runtime/utils.mjs +1 -0
  42. package/dist/esm-node/shared/routeDescriptor.mjs +23 -0
  43. package/dist/types/cli/tanstackTypes/shared.d.ts +0 -2
  44. package/dist/types/runtime/lifecycle.d.ts +1 -1
  45. package/dist/types/runtime/loaderBridge.d.ts +1 -0
  46. package/dist/types/runtime/navigation.d.ts +4 -0
  47. package/dist/types/runtime/routeTree/paths.d.ts +0 -2
  48. package/dist/types/shared/routeDescriptor.d.ts +26 -0
  49. package/package.json +12 -12
  50. package/src/cli/artifacts.ts +6 -1
  51. package/src/cli/tanstackTypes/canonicalRoutes.ts +17 -12
  52. package/src/cli/tanstackTypes/shared.ts +0 -14
  53. package/src/cli/tanstackTypes/source.ts +43 -119
  54. package/src/runtime/lifecycle.ts +0 -1
  55. package/src/runtime/loaderBridge.ts +9 -9
  56. package/src/runtime/navigation.ts +78 -0
  57. package/src/runtime/plugin.node.tsx +111 -89
  58. package/src/runtime/plugin.tsx +6 -0
  59. package/src/runtime/routeTree/construction.ts +32 -112
  60. package/src/runtime/routeTree/loaders.ts +2 -4
  61. package/src/runtime/routeTree/paths.ts +0 -6
  62. package/src/runtime/utils.tsx +1 -0
  63. package/src/shared/routeDescriptor.ts +46 -0
  64. package/tests/router/generateRouteArtifacts.test.ts +36 -2
  65. package/tests/router/localisedIdentity.test.tsx +1 -0
  66. package/tests/router/prefetchLink.test.tsx +29 -0
  67. package/tests/router/serverPlugin.test.ts +145 -0
  68. package/tests/router/tanstackTypes.test.ts +120 -2
@@ -8,7 +8,8 @@ import { useContext } from "react";
8
8
  import { createModernBasepathRewrite } from "./basepathRewrite.mjs";
9
9
  import { routerProviderRegistryHooks } from "./hooks.mjs";
10
10
  import { wrapTanstackSsrHydrationBoundary } from "./hydrationBoundary.mjs";
11
- import { applyRouterServerPrepareResult, createRouterServerSnapshot, getRouterRuntimeState } from "./lifecycle.mjs";
11
+ import { applyRouterRuntimeState, applyRouterServerPrepareResult, getRouterRuntimeState, getRouterServerSnapshot } from "./lifecycle.mjs";
12
+ import { createTanstackNavigation } from "./navigation.mjs";
12
13
  import { createTanstackRouteObjects, getTanstackRouteConfig, joinBasename } from "./pluginShared.mjs";
13
14
  import { Link } from "./prefetchLink.mjs";
14
15
  import { createRouteTreeFromRouteObjects, getModernRouteIdsFromMatches } from "./routeTree/index.mjs";
@@ -87,76 +88,93 @@ const tanstackRouterPlugin = (userConfig = {})=>{
87
88
  });
88
89
  const serverRouter = tanstackRouter;
89
90
  if (enableRsc) setTanstackRscRouter(serverRouter);
90
- await attachServerSsrUtils(serverRouter);
91
- const end = time();
92
- try {
93
- await tanstackRouter.load({
94
- sync: true
95
- });
96
- } finally{
97
- const cost = end();
98
- context.ssrContext?.onTiming?.(LOADER_REPORTER_NAME, cost);
99
- }
100
- const serverLoadResult = serverRouter._serverResult;
101
- if (!serverLoadResult) {
102
- try {
103
- serverRouter.serverSsr?.cleanup?.();
104
- } catch {}
105
- throw new Error('TanStack Router completed an SSR load without a server result.');
106
- }
107
- if ('redirect' === serverLoadResult.type) {
108
- const { redirect } = serverLoadResult;
109
- try {
110
- serverRouter.serverSsr?.cleanup?.();
111
- } catch {}
112
- return interrupt(isRSCNavigation ? handleTanstackRscRedirect(redirect.headers, _basename, redirect.status) : redirect);
113
- }
114
- const routerErrors = collectRouterErrors(tanstackRouter);
115
- if (routerErrors && 'clientRender' === loaderFailureMode) {
116
- context.ssrContext?.response?.status(200);
117
- try {
118
- serverRouter.serverSsr?.cleanup?.();
119
- } catch {}
120
- throw Object.values(routerErrors)[0];
121
- }
122
- await preloadMatchedRouteComponents(serverRouter);
123
- context.ssrContext?.response?.status(serverLoadResult.status);
124
- await serverRouter.serverSsr?.dehydrate?.();
125
- if (enableRsc) {
126
- if (isRSCNavigation) await waitForRouterSerialization(serverRouter);
127
- setTanstackRscServerPayload(createTanstackRscServerPayload(serverRouter, {
128
- omitClientLoaderData: isRSCNavigation
129
- }));
130
- }
131
- const ssrScriptTags = serverRouter.serverSsr?.takeBufferedScripts?.();
132
- const hydrationScripts = routerManagedTagsToHtml(ssrScriptTags);
133
- const matchedRouteIds = getModernRouteIdsFromMatches(serverRouter);
134
- const routerServerSnapshot = createRouterServerSnapshot({
91
+ let disposed = false;
92
+ let prepared = false;
93
+ const onAbort = ()=>controller.abort(rawRequest.signal.reason);
94
+ const cleanup = ()=>{
95
+ if (disposed) return;
96
+ disposed = true;
97
+ rawRequest.signal.removeEventListener('abort', onAbort);
98
+ controller.abort();
99
+ serverRouter.serverSsr?.cleanup?.();
100
+ };
101
+ applyRouterRuntimeState(context, {
135
102
  framework: 'tanstack',
136
103
  basename: _basename,
137
- statusCode: serverLoadResult.status,
138
- errors: routerErrors,
139
- matchedRouteIds,
140
- hydrationScripts
104
+ instance: serverRouter,
105
+ cleanup
106
+ });
107
+ rawRequest.signal.addEventListener('abort', onAbort, {
108
+ once: true
141
109
  });
142
- const runtimeContext = applyRouterServerPrepareResult(context, {
143
- snapshot: routerServerSnapshot,
144
- cleanup: ()=>serverRouter.serverSsr?.cleanup?.(),
145
- state: {
110
+ try {
111
+ rawRequest.signal.throwIfAborted();
112
+ await attachServerSsrUtils(serverRouter);
113
+ rawRequest.signal.throwIfAborted();
114
+ const end = time();
115
+ try {
116
+ await tanstackRouter.load({
117
+ sync: true
118
+ });
119
+ } finally{
120
+ const cost = end();
121
+ context.ssrContext?.onTiming?.(LOADER_REPORTER_NAME, cost);
122
+ }
123
+ rawRequest.signal.throwIfAborted();
124
+ const serverLoadResult = serverRouter._serverResult;
125
+ if (!serverLoadResult) throw new Error('TanStack Router completed an SSR load without a server result.');
126
+ if ('redirect' === serverLoadResult.type) {
127
+ const { redirect } = serverLoadResult;
128
+ return interrupt(isRSCNavigation ? handleTanstackRscRedirect(redirect.headers, _basename, redirect.status) : redirect);
129
+ }
130
+ const routerErrors = collectRouterErrors(tanstackRouter);
131
+ if (routerErrors && 'clientRender' === loaderFailureMode) {
132
+ context.ssrContext?.response?.status(200);
133
+ throw Object.values(routerErrors)[0];
134
+ }
135
+ await preloadMatchedRouteComponents(serverRouter);
136
+ context.ssrContext?.response?.status(serverLoadResult.status);
137
+ await serverRouter.serverSsr?.dehydrate?.();
138
+ if (enableRsc) {
139
+ if (isRSCNavigation) await waitForRouterSerialization(serverRouter);
140
+ setTanstackRscServerPayload(createTanstackRscServerPayload(serverRouter, {
141
+ omitClientLoaderData: isRSCNavigation
142
+ }));
143
+ }
144
+ const ssrScriptTags = serverRouter.serverSsr?.takeBufferedScripts?.();
145
+ const hydrationScripts = routerManagedTagsToHtml(ssrScriptTags);
146
+ const matchedRouteIds = getModernRouteIdsFromMatches(serverRouter);
147
+ const routerServerSnapshot = {
146
148
  framework: 'tanstack',
147
149
  basename: _basename,
148
- instance: serverRouter,
149
- hydrationScripts,
150
+ statusCode: serverLoadResult.status,
151
+ errors: routerErrors,
150
152
  matchedRouteIds,
151
- serverSnapshot: routerServerSnapshot
152
- }
153
- });
154
- hooks.onAfterCreateRouter.call({
155
- ...routerLifecycleContext,
156
- router: serverRouter,
157
- serverSnapshot: routerServerSnapshot,
158
- runtimeContext
159
- });
153
+ hydrationScripts
154
+ };
155
+ const runtimeContext = applyRouterServerPrepareResult(context, {
156
+ snapshot: routerServerSnapshot,
157
+ cleanup,
158
+ state: {
159
+ framework: 'tanstack',
160
+ basename: _basename,
161
+ instance: serverRouter,
162
+ navigation: createTanstackNavigation(tanstackRouter)
163
+ }
164
+ });
165
+ rawRequest.signal.throwIfAborted();
166
+ hooks.onAfterCreateRouter.call({
167
+ ...routerLifecycleContext,
168
+ router: serverRouter,
169
+ serverSnapshot: getRouterServerSnapshot(runtimeContext),
170
+ runtimeContext
171
+ });
172
+ prepared = true;
173
+ } finally{
174
+ if (!prepared) try {
175
+ cleanup();
176
+ } catch {}
177
+ }
160
178
  });
161
179
  api.wrapRoot((App)=>{
162
180
  const getRouteApp = ()=>{
@@ -1,23 +1,19 @@
1
- import { canonicaliseLocalisedRoutes } from "@modern-js/i18n-runtime-extensions";
2
1
  import { DefaultNotFound } from "@modern-js/runtime/context";
3
2
  import { rootRouteId } from "@tanstack/react-router";
3
+ import { describeRouteTree } from "../../shared/routeDescriptor.mjs";
4
4
  import { createRouteStaticData } from "../../shared/routeStaticData.mjs";
5
5
  import { withModernRouteMatchContext } from "../outlet.mjs";
6
6
  import { toErrorComponent, toPendingComponent, toRouteComponent } from "./components.mjs";
7
7
  import { createModernShouldReload, wrapRouteObjectLoader } from "./loaders.mjs";
8
- import { isRouteObjectPathlessLayout, toTanstackPath } from "./paths.mjs";
9
8
  import { mergeModernRouteHandle } from "./staticData.mjs";
10
9
  import { createTanstackRootRoute, createTanstackRoute, wrapRouteComponentWithModernContext } from "./tanstackRoutes.mjs";
11
- function createRouteFromRouteObject(opts) {
12
- const { options = {}, parent, pathlessFallbackId = 'pathless', routeObject } = opts;
10
+ function createRouteOptions(routeObject, options) {
13
11
  const modernRouteObject = routeObject;
14
12
  const revalidationState = {};
15
13
  const shouldRevalidate = modernRouteObject.shouldRevalidate;
16
14
  const shouldReload = createModernShouldReload(shouldRevalidate, revalidationState);
17
- const stableFallbackId = routeObject.id || modernRouteObject.file || pathlessFallbackId;
18
15
  const component = toRouteComponent(routeObject);
19
16
  const base = {
20
- getParentRoute: ()=>parent,
21
17
  component,
22
18
  pendingComponent: toPendingComponent(routeObject),
23
19
  errorComponent: toErrorComponent(routeObject),
@@ -38,67 +34,29 @@ function createRouteFromRouteObject(opts) {
38
34
  };
39
35
  if (modernRouteObject.inValidSSRRoute) base.ssr = false;
40
36
  if (shouldReload) base.shouldReload = shouldReload;
41
- if (isRouteObjectPathlessLayout(routeObject)) base.id = stableFallbackId;
42
- else base.path = routeObject.index ? '/' : toTanstackPath(routeObject.path || '');
43
- const route = createTanstackRoute(base);
44
- wrapRouteComponentWithModernContext(route, component, routeObject.id);
45
- const children = routeObject.children;
46
- if (children && children.length > 0) {
47
- const childRoutes = children.map((child, index)=>createRouteFromRouteObject({
48
- options,
49
- parent: route,
50
- pathlessFallbackId: `pathless-${index}`,
51
- routeObject: child
52
- }));
53
- route.addChildren(childRoutes);
54
- }
55
- return route;
37
+ return base;
56
38
  }
57
- function getRootLikeRouteObject(routes) {
58
- return routes.find((route)=>'/' === route.path && !route.index);
39
+ function createRouteFromDescriptor(descriptor, parent, options) {
40
+ const { source, location, children } = descriptor;
41
+ const routeOptions = createRouteOptions(source, options);
42
+ const route = createTanstackRoute({
43
+ ...routeOptions,
44
+ ...location,
45
+ getParentRoute: ()=>parent
46
+ });
47
+ wrapRouteComponentWithModernContext(route, routeOptions.component, source.id);
48
+ if (children.length) route.addChildren(children.map((child)=>createRouteFromDescriptor(child, route, options)));
49
+ return route;
59
50
  }
60
51
  function createRouteTreeFromRouteObjects(routes, options = {}) {
61
- routes = canonicaliseLocalisedRoutes(routes);
62
- const rootLikeRoute = getRootLikeRouteObject(routes);
63
- const rootRevalidationState = {};
64
- const rootShouldRevalidate = rootLikeRoute?.shouldRevalidate;
65
- const rootShouldReload = createModernShouldReload(rootShouldRevalidate, rootRevalidationState);
66
- const rootComponent = rootLikeRoute ? toRouteComponent(rootLikeRoute) : void 0;
52
+ const { root, children } = describeRouteTree(routes);
67
53
  const rootRouteOptions = {
68
- component: rootComponent,
69
- pendingComponent: rootLikeRoute ? toPendingComponent(rootLikeRoute) : void 0,
70
- errorComponent: rootLikeRoute ? toErrorComponent(rootLikeRoute) : void 0,
71
- validateSearch: rootLikeRoute?.validateSearch,
72
- loaderDeps: rootLikeRoute?.loaderDeps,
73
- notFoundComponent: DefaultNotFound,
74
- staticData: createRouteStaticData({
75
- modernRouteId: rootLikeRoute?.id,
76
- modernRouteAction: rootLikeRoute?.action,
77
- modernRouteHandle: rootLikeRoute ? mergeModernRouteHandle(rootLikeRoute) : void 0,
78
- modernRouteHasAction: rootLikeRoute?.hasAction || Boolean(rootLikeRoute?.action),
79
- modernRouteHasClientLoader: rootLikeRoute?.hasClientLoader || void 0 !== rootLikeRoute?.clientData,
80
- modernRouteHasLoader: rootLikeRoute?.hasLoader || 'function' == typeof rootLikeRoute?.loader,
81
- modernRouteIsClientComponent: rootLikeRoute?.isClientComponent,
82
- modernRouteLoader: rootLikeRoute?.loader,
83
- modernRouteShouldRevalidate: rootShouldRevalidate
84
- }),
85
- loader: rootLikeRoute ? wrapRouteObjectLoader(rootLikeRoute, rootRevalidationState, options) : void 0
54
+ ...root ? createRouteOptions(root, options) : {},
55
+ notFoundComponent: DefaultNotFound
86
56
  };
87
- if (rootShouldReload) rootRouteOptions.shouldReload = rootShouldReload;
88
- if (rootLikeRoute?.inValidSSRRoute) rootRouteOptions.ssr = false;
89
57
  const rootRoute = createTanstackRootRoute(rootRouteOptions);
90
- if (rootComponent) rootRoute.options.component = withModernRouteMatchContext(rootComponent, rootRouteId);
91
- const topLevel = rootLikeRoute ? [
92
- ...rootLikeRoute.children || [],
93
- ...routes.filter((route)=>route !== rootLikeRoute)
94
- ] : routes;
95
- const childRoutes = topLevel.map((routeObject, index)=>createRouteFromRouteObject({
96
- options,
97
- parent: rootRoute,
98
- pathlessFallbackId: `pathless-${index}`,
99
- routeObject
100
- }));
101
- rootRoute.addChildren(childRoutes);
58
+ if (rootRouteOptions.component) rootRoute.options.component = withModernRouteMatchContext(rootRouteOptions.component, rootRouteId);
59
+ rootRoute.addChildren(children.map((child)=>createRouteFromDescriptor(child, rootRoute, options)));
102
60
  return rootRoute;
103
61
  }
104
62
  function getModernRouteIdsFromMatches(router) {
@@ -1,4 +1,4 @@
1
- import { getLoaderHref, handleModernLoaderError, handleModernLoaderResult, mapSplatParamsForModernLoader } from "../loaderBridge.mjs";
1
+ import { getLoaderHref, getLoaderSignal, handleModernLoaderError, handleModernLoaderResult, mapSplatParamsForModernLoader } from "../loaderBridge.mjs";
2
2
  import { isTanstackRscPayloadNavigationEnabled, loadTanstackRscRouteData } from "../rsc/payloadRouter.mjs";
3
3
  function isModernDeferredData(value) {
4
4
  if (!value || 'object' != typeof value) return false;
@@ -49,7 +49,7 @@ function wrapRouteObjectLoader(route, revalidationState, options = {}) {
49
49
  if ('function' == typeof modernRoute.lazyImport) try {
50
50
  await modernRoute.lazyImport();
51
51
  } catch {}
52
- const signal = ctx?.abortController?.signal || ctx?.signal || new AbortController().signal;
52
+ const signal = getLoaderSignal(ctx);
53
53
  const baseRequest = ctx?.context?.request instanceof Request ? ctx.context.request : void 0;
54
54
  const href = getLoaderHref(ctx);
55
55
  const request = void 0 !== baseRequest ? new Request(baseRequest, {
@@ -10,7 +10,4 @@ function toTanstackPath(pathname) {
10
10
  return segment;
11
11
  }).join('/');
12
12
  }
13
- function isRouteObjectPathlessLayout(route) {
14
- return !route.path && !route.index;
15
- }
16
- export { isRouteObjectPathlessLayout, toTanstackPath };
13
+ export { toTanstackPath };
@@ -14,6 +14,7 @@ function withGlobalLayout(Component, globalApp) {
14
14
  function toTanstackRouteObject(route, globalApp) {
15
15
  if ('nested' === route.type) return {
16
16
  modernLocalisedRoute: Reflect.get(route, 'modernLocalisedRoute'),
17
+ isRoot: Reflect.get(route, 'isRoot'),
17
18
  path: route.path,
18
19
  id: route.id,
19
20
  loader: route.loader,
@@ -0,0 +1,22 @@
1
+ import { toTanstackPath } from "../runtime/routeTree/paths.mjs";
2
+ function describeRouteTree(routes) {
3
+ const root = routes.find((route)=>true === route.isRoot || '/' === route.path && true !== route.index);
4
+ const describe = (route, index)=>({
5
+ source: route,
6
+ location: 0 === (route.path ?? '').length && true !== route.index ? {
7
+ id: route.id || route.file || `pathless-${index}`
8
+ } : {
9
+ path: true === route.index ? '/' : toTanstackPath(route.path || '')
10
+ },
11
+ hasSplat: Boolean(route.path?.includes('*')),
12
+ children: (route.children ?? []).map(describe)
13
+ });
14
+ return {
15
+ root,
16
+ children: (void 0 !== root ? [
17
+ ...root.children ?? [],
18
+ ...routes.filter((route)=>route !== root)
19
+ ] : routes).map(describe)
20
+ };
21
+ }
22
+ export { describeRouteTree };
@@ -96,9 +96,10 @@ async function generateTanstackRouteArtifacts(opts) {
96
96
  version: opts.version || process.env.MODERN_JS_VERSION || '0.0.0-routes-generate',
97
97
  internalPlugins: utils.INTERNAL_RUNTIME_PLUGINS
98
98
  });
99
- await cli.init({
99
+ const { appContext } = await cli.init({
100
100
  ...runOptions,
101
101
  command: 'build'
102
102
  });
103
+ await appContext.hooks.onBeforeExit.call();
103
104
  }
104
105
  export { generateTanstackRouteArtifacts, writeTanstackRegisterFile, writeTanstackRouterTypesForEntries };
@@ -1,4 +1,5 @@
1
1
  import "node:module";
2
+ import { describeRouteTree } from "../../shared/routeDescriptor.mjs";
2
3
  import { toTanstackPath } from "./shared.mjs";
3
4
  const LOCALE_PARAM_SEGMENTS = new Set([
4
5
  ':lang',
@@ -45,11 +46,13 @@ function collectCanonicalRoutesForEntry(routes, options = {}) {
45
46
  const key = toTanstackPath(normalized);
46
47
  if (!canonicalParams.has(key)) canonicalParams.set(key, paramsTypeForCanonicalPath(normalized));
47
48
  };
48
- const visit = (route, parentPath)=>{
49
+ const visit = (descriptor, parentPath)=>{
50
+ const { source: route, children } = descriptor;
49
51
  let currentPath = parentPath;
50
- if ('string' == typeof route.modernCanonicalPath) {
52
+ const canonicalPath = route.modernLocalisedRoute?.canonicalPath ?? route.modernCanonicalPath;
53
+ if ('string' == typeof canonicalPath) {
51
54
  hasI18nSurface = true;
52
- currentPath = normalizeJoined(route.modernCanonicalPath);
55
+ currentPath = canonicalPath ? normalizeJoined(canonicalPath) : '';
53
56
  } else if ('string' == typeof route.path && route.path.length > 0) {
54
57
  const segments = route.path.replace(/\[(.+?)\]/g, ':$1').split('/').filter(Boolean);
55
58
  if (localeParamHeuristic && '' === parentPath && LOCALE_PARAM_SEGMENTS.has(segments[0])) {
@@ -58,16 +61,13 @@ function collectCanonicalRoutesForEntry(routes, options = {}) {
58
61
  }
59
62
  currentPath = segments.length ? normalizeJoined(`${parentPath}/${segments.join('/')}`) : parentPath;
60
63
  }
61
- const children = route.children;
62
64
  if (children && children.length > 0) {
63
65
  for (const child of children)visit(child, currentPath);
64
66
  return;
65
67
  }
66
68
  record(currentPath || '/');
67
69
  };
68
- const rootModern = routes.find((route)=>route.isRoot);
69
- const topLevel = rootModern ? rootModern.children ?? [] : routes;
70
- for (const route of topLevel)visit(route, '');
70
+ for (const route of describeRouteTree(routes).children)visit(route, '');
71
71
  if (!hasI18nSurface || 0 === canonicalParams.size) return null;
72
72
  return Object.fromEntries([
73
73
  ...canonicalParams.entries()
@@ -43,14 +43,6 @@ function pickRouteSearchContractModules(route) {
43
43
  loaderDepsPath: 'string' == typeof loaderDepsPath ? loaderDepsPath : null
44
44
  };
45
45
  }
46
- function isPathlessLayout(route) {
47
- const extras = route;
48
- return 'nested' === extras.type && 'boolean' != typeof extras.index && void 0 === extras.path;
49
- }
50
- function isIndexRoute(route) {
51
- const extras = route;
52
- return 'nested' === extras.type && Boolean(extras.index);
53
- }
54
46
  function createRouteStaticDataSnippet(opts) {
55
47
  const staticData = createRouteStaticData({
56
48
  modernRouteId: opts.modernRouteId && quote(opts.modernRouteId),
@@ -61,4 +53,4 @@ function createRouteStaticDataSnippet(opts) {
61
53
  return entries.length > 0 ? `staticData: createRouteStaticData({\n ${entries.map(([key, value])=>`${key}: ${value},`).join('\n ')}\n }),` : null;
62
54
  }
63
55
  export { toTanstackPath } from "../../runtime/routeTree/paths.mjs";
64
- export { createRouteStaticDataSnippet, isIndexRoute, isPathlessLayout, normalizeRelativeImport, pickModernLoaderModule, pickRouteSearchContractModules, quote, resolveFileNoExt };
56
+ export { createRouteStaticDataSnippet, normalizeRelativeImport, pickModernLoaderModule, pickRouteSearchContractModules, quote, resolveFileNoExt };
@@ -1,18 +1,12 @@
1
1
  import "node:module";
2
- import { canonicaliseLocalisedRoutes } from "@modern-js/i18n-runtime-extensions";
3
2
  import { makeLegalIdentifier } from "@modern-js/runtime/cli";
4
3
  import { upath } from "@modern-js/utils";
5
- import { createRouteStaticDataSnippet, isIndexRoute, isPathlessLayout, normalizeRelativeImport, pickModernLoaderModule, pickRouteSearchContractModules, quote, resolveFileNoExt, toTanstackPath } from "./shared.mjs";
4
+ import { describeRouteTree } from "../../shared/routeDescriptor.mjs";
5
+ import { createRouteStaticDataSnippet, normalizeRelativeImport, pickModernLoaderModule, pickRouteSearchContractModules, quote, resolveFileNoExt } from "./shared.mjs";
6
6
  async function generateTanstackRouterTypesSourceForEntry(opts) {
7
- const { appContext, entryName, generatedDirName = 'modern-tanstack', routes: rawRoutes } = opts;
8
- const routes = canonicaliseLocalisedRoutes(rawRoutes);
7
+ const { appContext, entryName, generatedDirName = 'modern-tanstack', routes } = opts;
9
8
  const outDir = upath.join(appContext.srcDirectory, generatedDirName, entryName);
10
- const rootModern = routes.find((r)=>{
11
- const extras = r;
12
- return r && 'nested' === extras.type && extras.isRoot;
13
- });
14
- const rootExtras = rootModern;
15
- const topLevel = rootModern ? rootExtras?.children || [] : routes;
9
+ const { root: rootModern, children: topLevel } = describeRouteTree(routes);
16
10
  const imports = [];
17
11
  const statements = [];
18
12
  const loaderImportMap = new Map();
@@ -29,9 +23,8 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
29
23
  let pendingImportName = componentImportMap.get(componentPath);
30
24
  if (!pendingImportName) {
31
25
  pendingImportName = (async ()=>{
32
- const resolvedNoExt = await resolveRouteModuleNoExt(componentPath);
33
- if (!resolvedNoExt) return null;
34
- const relImport = normalizeRelativeImport(upath.relative(outDir, resolvedNoExt));
26
+ const relImport = await resolveRouteImport(componentPath);
27
+ if (!relImport) return null;
35
28
  const componentName = `component_${componentIndex++}`;
36
29
  imports.push(`import ${componentName} from ${quote(relImport)};`);
37
30
  return componentName;
@@ -40,14 +33,15 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
40
33
  }
41
34
  return pendingImportName;
42
35
  };
43
- const resolveRouteModuleNoExt = async (aliasedNoExtPath)=>{
36
+ const resolveRouteImport = async (aliasedNoExtPath)=>{
44
37
  const prefix = `${appContext.internalSrcAlias}/`;
45
38
  let absNoExt;
46
39
  if (aliasedNoExtPath.startsWith(prefix)) {
47
40
  const rel = aliasedNoExtPath.slice(prefix.length);
48
41
  absNoExt = upath.join(appContext.srcDirectory, rel);
49
42
  } else absNoExt = upath.isAbsolute(aliasedNoExtPath) ? aliasedNoExtPath : upath.join(appContext.srcDirectory, aliasedNoExtPath);
50
- return resolveFileNoExt(absNoExt);
43
+ const resolvedNoExt = await resolveFileNoExt(absNoExt);
44
+ return resolvedNoExt ? normalizeRelativeImport(upath.relative(outDir, resolvedNoExt)) : null;
51
45
  };
52
46
  const getImportNamesForLoader = async (aliasedNoExtPath, inline, hasAction)=>{
53
47
  const key = `${inline ? 'inline' : 'default'}:${hasAction ? 'action' : 'loader'}:${aliasedNoExtPath}`;
@@ -56,9 +50,8 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
56
50
  loaderName: existing,
57
51
  actionName: hasAction ? existing.replace(/^loader_/, 'action_') : null
58
52
  };
59
- const resolvedNoExt = await resolveRouteModuleNoExt(aliasedNoExtPath);
60
- if (!resolvedNoExt) return null;
61
- const relImport = normalizeRelativeImport(upath.relative(outDir, resolvedNoExt));
53
+ const relImport = await resolveRouteImport(aliasedNoExtPath);
54
+ if (!relImport) return null;
62
55
  const importName = `loader_${loaderIndex++}`;
63
56
  const actionName = hasAction ? importName.replace(/^loader_/, 'action_') : null;
64
57
  if (inline) {
@@ -78,9 +71,8 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
78
71
  const key = `${exportName}:${aliasedNoExtPath}`;
79
72
  const existing = searchContractImportMap.get(key);
80
73
  if (existing) return existing;
81
- const resolvedNoExt = await resolveRouteModuleNoExt(aliasedNoExtPath);
82
- if (!resolvedNoExt) return null;
83
- const relImport = normalizeRelativeImport(upath.relative(outDir, resolvedNoExt));
74
+ const relImport = await resolveRouteImport(aliasedNoExtPath);
75
+ if (!relImport) return null;
84
76
  const importName = 'validateSearch' === exportName ? `validateSearch_${validateSearchIndex++}` : `loaderDeps_${loaderDepsIndex++}`;
85
77
  imports.push(`import { ${exportName} as ${importName} } from ${quote(relImport)};`);
86
78
  searchContractImportMap.set(key, importName);
@@ -98,9 +90,7 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
98
90
  const base = id ? makeLegalIdentifier(id) : `r_${routeIndex++}`;
99
91
  return reserveRouteVarName(`route_${base}`);
100
92
  };
101
- const buildRoute = async (opts)=>{
102
- const { parentVar, route } = opts;
103
- const varName = createRouteVarName(route);
93
+ const createRouteOptions = async (route, hasSplat)=>{
104
94
  const routeExtras = route;
105
95
  const loaderInfo = pickModernLoaderModule(route);
106
96
  const routeAction = routeExtras.action;
@@ -110,20 +100,9 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
110
100
  const searchContractInfo = pickRouteSearchContractModules(route);
111
101
  const validateSearchName = searchContractInfo.validateSearchPath ? await getImportNameForSearchContract(searchContractInfo.validateSearchPath, 'validateSearch') : null;
112
102
  const loaderDepsName = searchContractInfo.loaderDepsPath ? await getImportNameForSearchContract(searchContractInfo.loaderDepsPath, 'loaderDeps') : null;
113
- const rawPath = routeExtras.path;
114
- const hasSplat = 'string' == typeof rawPath && rawPath.includes('*');
115
- const routeOpts = [
116
- `getParentRoute: () => ${parentVar},`
117
- ];
103
+ const routeOpts = [];
118
104
  const componentName = await getImportNameForComponent(routeExtras._component);
119
105
  if (componentName) routeOpts.push(`component: ${componentName},`);
120
- if (isPathlessLayout(route)) {
121
- const id = routeExtras.id;
122
- routeOpts.push(`id: ${quote(id || 'pathless')},`);
123
- } else {
124
- const p = isIndexRoute(route) ? '/' : toTanstackPath(rawPath || '');
125
- routeOpts.push(`path: ${quote(p)},`);
126
- }
127
106
  if (loaderName) routeOpts.push(`loader: modernLoaderToTanstack({ hasSplat: ${hasSplat} }, ${loaderName}),`);
128
107
  if (validateSearchName) routeOpts.push(`validateSearch: ${validateSearchName},`);
129
108
  if (loaderDepsName) routeOpts.push(`loaderDeps: ${loaderDepsName},`);
@@ -133,39 +112,29 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
133
112
  actionName
134
113
  });
135
114
  if (staticDataSnippet) routeOpts.push(staticDataSnippet);
136
- const children = routeExtras.children;
115
+ return routeOpts;
116
+ };
117
+ const buildRoute = async (descriptor, parentVar)=>{
118
+ const { source: route, location, hasSplat, children } = descriptor;
119
+ const varName = createRouteVarName(route);
120
+ const routeOpts = [
121
+ `getParentRoute: () => ${parentVar},`,
122
+ ...Object.entries(location).map(([key, value])=>`${key}: ${quote(value)},`),
123
+ ...await createRouteOptions(route, hasSplat)
124
+ ];
137
125
  const hasChildren = Boolean(children && children.length > 0);
138
126
  const routeCtorVarName = hasChildren ? reserveRouteVarName(`${varName}__base`) : varName;
139
127
  statements.push(`const ${routeCtorVarName} = createRoute({\n ${routeOpts.join('\n ')}\n});`);
140
128
  if (children && children.length > 0) {
141
129
  const childVars = [];
142
- for (const child of children)childVars.push(await buildRoute({
143
- parentVar: routeCtorVarName,
144
- route: child
145
- }));
130
+ for (const child of children)childVars.push(await buildRoute(child, routeCtorVarName));
146
131
  statements.push(`const ${varName} = ${routeCtorVarName}.addChildren([${childVars.join(', ')}]);`);
147
132
  }
148
133
  return varName;
149
134
  };
150
- const rootLoaderInfo = rootModern ? pickModernLoaderModule(rootModern) : null;
151
- const rootAction = rootExtras?.action;
152
- const rootLoaderImports = rootLoaderInfo?.loaderPath ? await getImportNamesForLoader(rootLoaderInfo.loaderPath, rootLoaderInfo.inline, Boolean(rootLoaderInfo.inline && rootAction === rootLoaderInfo.loaderPath)) : null;
153
- const rootLoaderName = rootLoaderImports?.loaderName || null;
154
- const rootActionName = rootLoaderImports?.actionName || null;
155
- const rootSearchContractInfo = rootModern ? pickRouteSearchContractModules(rootModern) : null;
156
- const rootValidateSearchName = rootSearchContractInfo?.validateSearchPath ? await getImportNameForSearchContract(rootSearchContractInfo.validateSearchPath, 'validateSearch') : null;
157
- const rootLoaderDepsName = rootSearchContractInfo?.loaderDepsPath ? await getImportNameForSearchContract(rootSearchContractInfo.loaderDepsPath, 'loaderDeps') : null;
158
135
  const topLevelVars = [];
159
- for (const route of topLevel)topLevelVars.push(await buildRoute({
160
- parentVar: 'rootRoute',
161
- route
162
- }));
163
- const rootOpts = [];
164
- const rootComponentName = await getImportNameForComponent(rootExtras?._component);
165
- if (rootComponentName) rootOpts.push(`component: ${rootComponentName},`);
166
- if (rootLoaderName) rootOpts.push(`loader: modernLoaderToTanstack({ hasSplat: false }, ${rootLoaderName}),`);
167
- if (rootValidateSearchName) rootOpts.push(`validateSearch: ${rootValidateSearchName},`);
168
- if (rootLoaderDepsName) rootOpts.push(`loaderDeps: ${rootLoaderDepsName},`);
136
+ for (const route of topLevel)topLevelVars.push(await buildRoute(route, 'rootRoute'));
137
+ const rootOpts = rootModern ? await createRouteOptions(rootModern, false) : [];
169
138
  const routerGenTs = `// This file is auto-generated by Modern.js. Do not edit manually.
170
139
 
171
140
  import {
@@ -182,11 +151,7 @@ ${imports.join('\n')}
182
151
 
183
152
  export const rootRoute = createRootRouteWithContext<ModernRouterContext>()({
184
153
  ${rootOpts.join('\n ')}
185
- ${createRouteStaticDataSnippet({
186
- modernRouteId: rootExtras?.id,
187
- loaderName: rootLoaderName,
188
- actionName: rootActionName
189
- }) || ''}
154
+
190
155
  });
191
156
 
192
157
  ${statements.join('\n\n')}
@@ -1,2 +1,2 @@
1
1
  import "node:module";
2
- export { applyRouterRuntimeState, applyRouterServerPrepareResult, createRouterRuntimeState, createRouterServerSnapshot, getRouterRuntimeState, getRouterServerSnapshot } from "@modern-js/runtime-extensions/router-state";
2
+ export { applyRouterRuntimeState, applyRouterServerPrepareResult, createRouterServerSnapshot, getRouterRuntimeState, getRouterServerSnapshot } from "@modern-js/runtime-extensions/router-state";
@@ -37,10 +37,13 @@ function mapSplatParamsForModernLoader(params, hasSplat) {
37
37
  return rest;
38
38
  }
39
39
  function getLoaderSignal(ctx) {
40
- const abortSignal = ctx?.abortController?.signal;
41
- if (abortSignal instanceof AbortSignal) return abortSignal;
42
- if (ctx?.signal instanceof AbortSignal) return ctx.signal;
43
- return new AbortController().signal;
40
+ const matchSignal = ctx?.abortController?.signal ?? ctx?.signal;
41
+ const requestSignal = ctx?.context?.request?.signal;
42
+ const signals = [
43
+ matchSignal,
44
+ requestSignal
45
+ ].filter((signal)=>signal instanceof AbortSignal);
46
+ return AbortSignal.any(signals);
44
47
  }
45
48
  function getLoaderHref(ctx) {
46
49
  if ('string' == typeof ctx?.location) return ctx.location;
@@ -102,4 +105,4 @@ function modernLoaderToTanstack(opts, modernLoader) {
102
105
  };
103
106
  }
104
107
  export { createRouteStaticData } from "../shared/routeStaticData.mjs";
105
- export { getLoaderHref, handleModernLoaderError, handleModernLoaderResult, isAbsoluteUrl, isRedirectResponse, isResponse, isTanstackRedirect, mapSplatParamsForModernLoader, modernLoaderToTanstack, throwTanstackRedirect };
108
+ export { getLoaderHref, getLoaderSignal, handleModernLoaderError, handleModernLoaderResult, isAbsoluteUrl, isRedirectResponse, isResponse, isTanstackRedirect, mapSplatParamsForModernLoader, modernLoaderToTanstack, throwTanstackRedirect };