@bleedingdev/modern-js-plugin-tanstack 3.2.0-ultramodern.99 → 3.4.0-ultramodern.1

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 (127) hide show
  1. package/dist/cjs/cli/index.js +80 -34
  2. package/dist/cjs/cli/routeSplitting.js +13 -41
  3. package/dist/cjs/cli/tanstackTypes.js +114 -200
  4. package/dist/cjs/cli.js +12 -8
  5. package/dist/cjs/runtime/basepathRewrite.js +12 -8
  6. package/dist/cjs/runtime/dataMutation.js +9 -5
  7. package/dist/cjs/runtime/hooks.js +20 -19
  8. package/dist/cjs/runtime/hydrationBoundary.js +12 -7
  9. package/dist/cjs/runtime/index.js +66 -54
  10. package/dist/cjs/runtime/lifecycle.js +21 -91
  11. package/dist/cjs/runtime/loaderBridge.js +173 -0
  12. package/dist/cjs/runtime/outlet.js +58 -0
  13. package/dist/cjs/runtime/plugin.js +190 -110
  14. package/dist/cjs/runtime/plugin.node.js +25 -40
  15. package/dist/cjs/runtime/plugin.worker.js +9 -5
  16. package/dist/cjs/runtime/pluginCore.js +55 -0
  17. package/dist/cjs/runtime/prefetchLink.js +10 -6
  18. package/dist/cjs/runtime/register.js +56 -0
  19. package/dist/cjs/runtime/routeTree.js +30 -212
  20. package/dist/cjs/runtime/router.js +41 -0
  21. package/dist/cjs/runtime/rsc/ClientSlot.js +9 -5
  22. package/dist/cjs/runtime/rsc/CompositeComponent.js +9 -5
  23. package/dist/cjs/runtime/rsc/ReplayableStream.js +14 -9
  24. package/dist/cjs/runtime/rsc/RscNodeRenderer.js +9 -5
  25. package/dist/cjs/runtime/rsc/SlotContext.js +9 -5
  26. package/dist/cjs/runtime/rsc/client.js +9 -5
  27. package/dist/cjs/runtime/rsc/createRscProxy.js +9 -5
  28. package/dist/cjs/runtime/rsc/index.js +9 -5
  29. package/dist/cjs/runtime/rsc/payloadRouter.js +44 -6
  30. package/dist/cjs/runtime/rsc/server.js +9 -5
  31. package/dist/cjs/runtime/rsc/slotUsageSanitizer.js +9 -5
  32. package/dist/cjs/runtime/rsc/symbols.js +20 -15
  33. package/dist/cjs/runtime/state.js +45 -0
  34. package/dist/cjs/runtime/types.js +13 -9
  35. package/dist/cjs/runtime/utils.js +9 -11
  36. package/dist/cjs/runtime.js +9 -5
  37. package/dist/esm/cli/index.mjs +73 -28
  38. package/dist/esm/cli/routeSplitting.mjs +1 -30
  39. package/dist/esm/cli/tanstackTypes.mjs +100 -190
  40. package/dist/esm/runtime/hooks.mjs +1 -8
  41. package/dist/esm/runtime/hydrationBoundary.mjs +3 -2
  42. package/dist/esm/runtime/index.mjs +4 -2
  43. package/dist/esm/runtime/lifecycle.mjs +1 -82
  44. package/dist/esm/runtime/loaderBridge.mjs +114 -0
  45. package/dist/esm/runtime/outlet.mjs +17 -0
  46. package/dist/esm/runtime/plugin.mjs +183 -107
  47. package/dist/esm/runtime/plugin.node.mjs +19 -38
  48. package/dist/esm/runtime/pluginCore.mjs +14 -0
  49. package/dist/esm/runtime/prefetchLink.mjs +1 -1
  50. package/dist/esm/runtime/register.mjs +18 -0
  51. package/dist/esm/runtime/routeTree.mjs +15 -198
  52. package/dist/esm/runtime/router.mjs +2 -0
  53. package/dist/esm/runtime/rsc/payloadRouter.mjs +35 -1
  54. package/dist/esm/runtime/state.mjs +7 -0
  55. package/dist/esm/runtime/utils.mjs +0 -6
  56. package/dist/esm-node/cli/index.mjs +73 -28
  57. package/dist/esm-node/cli/routeSplitting.mjs +1 -30
  58. package/dist/esm-node/cli/tanstackTypes.mjs +100 -190
  59. package/dist/esm-node/runtime/hooks.mjs +1 -8
  60. package/dist/esm-node/runtime/hydrationBoundary.mjs +3 -2
  61. package/dist/esm-node/runtime/index.mjs +4 -2
  62. package/dist/esm-node/runtime/lifecycle.mjs +1 -82
  63. package/dist/esm-node/runtime/loaderBridge.mjs +115 -0
  64. package/dist/esm-node/runtime/outlet.mjs +18 -0
  65. package/dist/esm-node/runtime/plugin.mjs +183 -107
  66. package/dist/esm-node/runtime/plugin.node.mjs +19 -38
  67. package/dist/esm-node/runtime/pluginCore.mjs +15 -0
  68. package/dist/esm-node/runtime/prefetchLink.mjs +1 -1
  69. package/dist/esm-node/runtime/register.mjs +19 -0
  70. package/dist/esm-node/runtime/routeTree.mjs +15 -198
  71. package/dist/esm-node/runtime/router.mjs +3 -0
  72. package/dist/esm-node/runtime/rsc/payloadRouter.mjs +35 -1
  73. package/dist/esm-node/runtime/state.mjs +8 -0
  74. package/dist/esm-node/runtime/utils.mjs +0 -6
  75. package/dist/types/cli/index.d.ts +11 -2
  76. package/dist/types/cli/routeSplitting.d.ts +6 -15
  77. package/dist/types/cli/tanstackTypes.d.ts +21 -1
  78. package/dist/types/runtime/hooks.d.ts +8 -33
  79. package/dist/types/runtime/index.d.ts +6 -3
  80. package/dist/types/runtime/lifecycle.d.ts +7 -22
  81. package/dist/types/runtime/loaderBridge.d.ts +48 -0
  82. package/dist/types/runtime/outlet.d.ts +2 -0
  83. package/dist/types/runtime/plugin.d.ts +1 -14
  84. package/dist/types/runtime/plugin.node.d.ts +1 -14
  85. package/dist/types/runtime/pluginCore.d.ts +21 -0
  86. package/dist/types/runtime/register.d.ts +9 -0
  87. package/dist/types/runtime/routeTree.d.ts +0 -2
  88. package/dist/types/runtime/router.d.ts +14 -0
  89. package/dist/types/runtime/state.d.ts +16 -0
  90. package/dist/types/runtime/types.d.ts +7 -53
  91. package/package.json +41 -39
  92. package/rstest.config.mts +6 -0
  93. package/src/cli/index.ts +146 -24
  94. package/src/cli/routeSplitting.ts +6 -44
  95. package/src/cli/tanstackTypes.ts +203 -208
  96. package/src/runtime/hooks.ts +10 -27
  97. package/src/runtime/hydrationBoundary.tsx +5 -5
  98. package/src/runtime/index.tsx +12 -14
  99. package/src/runtime/lifecycle.ts +16 -151
  100. package/src/runtime/loaderBridge.ts +257 -0
  101. package/src/runtime/outlet.tsx +48 -0
  102. package/src/runtime/plugin.node.tsx +28 -83
  103. package/src/runtime/plugin.tsx +350 -202
  104. package/src/runtime/pluginCore.ts +48 -0
  105. package/src/runtime/prefetchLink.tsx +1 -1
  106. package/src/runtime/register.ts +58 -0
  107. package/src/runtime/routeTree.ts +41 -365
  108. package/src/runtime/router.ts +15 -0
  109. package/src/runtime/rsc/payloadRouter.ts +45 -2
  110. package/src/runtime/ssr-shim.d.ts +1 -3
  111. package/src/runtime/state.ts +29 -0
  112. package/src/runtime/types.ts +20 -67
  113. package/src/runtime/utils.tsx +3 -7
  114. package/tests/router/cli.test.ts +373 -31
  115. package/tests/router/hooks.test.ts +26 -0
  116. package/tests/router/loaderBridge.test.ts +211 -0
  117. package/tests/router/packageSurface.test.ts +24 -0
  118. package/tests/router/prefetchLink.test.tsx +43 -7
  119. package/tests/router/register.test.ts +46 -0
  120. package/tests/router/routeTree.test.ts +176 -139
  121. package/tests/router/rsc.test.tsx +70 -0
  122. package/tests/router/tanstackTypes.test.ts +395 -7
  123. package/dist/cjs/runtime/DefaultNotFound.js +0 -47
  124. package/dist/esm/runtime/DefaultNotFound.mjs +0 -13
  125. package/dist/esm-node/runtime/DefaultNotFound.mjs +0 -14
  126. package/dist/types/runtime/DefaultNotFound.d.ts +0 -2
  127. package/src/runtime/DefaultNotFound.tsx +0 -15
@@ -1,18 +1,7 @@
1
1
  import "node:module";
2
- import { findExists, formatImportPath, fs, slash } from "@modern-js/utils";
2
+ import { getPathWithoutExt, makeLegalIdentifier } from "@modern-js/runtime/cli";
3
+ import { findExists, formatImportPath, slash } from "@modern-js/utils";
3
4
  import path from "path";
4
- const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
5
- const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
6
- const forbidList = new Set(`${reservedWords} ${builtins}`.split(' '));
7
- function makeLegalIdentifier(str) {
8
- const identifier = str.replace(/-(\w)/g, (_, letter)=>letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, '_');
9
- if (/\d/.test(identifier[0]) || forbidList.has(identifier)) return `_${identifier}`;
10
- return identifier || '_';
11
- }
12
- function getPathWithoutExt(filename) {
13
- const extname = path.extname(filename);
14
- return extname ? filename.slice(0, -extname.length) : filename;
15
- }
16
5
  const JS_OR_TS_EXTS = [
17
6
  '.js',
18
7
  '.jsx',
@@ -78,16 +67,78 @@ function createRouteStaticDataSnippet(opts) {
78
67
  if (!staticDataLines.length) return null;
79
68
  return `staticData: createRouteStaticData({\n ${staticDataLines.join('\n ')}\n }),`;
80
69
  }
81
- async function isTanstackRouterFrameworkEnabled(appContext) {
82
- const runtimeConfigBase = path.join(appContext.srcDirectory, appContext.runtimeConfigFile);
83
- const runtimeConfigFile = findExists(JS_OR_TS_EXTS.map((ext)=>`${runtimeConfigBase}${ext}`));
84
- if (!runtimeConfigFile) return false;
85
- try {
86
- const content = await fs.readFile(runtimeConfigFile, 'utf-8');
87
- return /framework\s*:\s*['"]tanstack['"]/.test(content);
88
- } catch {
89
- return false;
70
+ const LOCALE_PARAM_SEGMENTS = new Set([
71
+ ':lang',
72
+ ':locale',
73
+ ':language',
74
+ '$lang',
75
+ '$locale',
76
+ '$language'
77
+ ]);
78
+ function paramsTypeForCanonicalPath(canonicalPath) {
79
+ const fields = [];
80
+ for (const segment of canonicalPath.split('/'))if (segment) {
81
+ if ('*' === segment || '$' === segment) {
82
+ fields.push("'_splat'?: string");
83
+ continue;
84
+ }
85
+ if (segment.startsWith('{-$') && segment.endsWith('}')) {
86
+ fields.push(`${JSON.stringify(segment.slice(3, -1))}?: string`);
87
+ continue;
88
+ }
89
+ if (segment.startsWith('$')) {
90
+ fields.push(`${JSON.stringify(segment.slice(1))}: string`);
91
+ continue;
92
+ }
93
+ if (segment.startsWith(':')) {
94
+ const optional = segment.endsWith('?');
95
+ const name = segment.slice(1, optional ? void 0 : segment.length);
96
+ fields.push(`${JSON.stringify(optional ? name.slice(0, -1) : name)}${optional ? '?' : ''}: string`);
97
+ }
90
98
  }
99
+ return fields.length > 0 ? `{ ${fields.join('; ')} }` : 'Record<string, never>';
100
+ }
101
+ function collectCanonicalRoutesForEntry(routes, options = {}) {
102
+ const { localeParamHeuristic = true } = options;
103
+ const canonicalParams = new Map();
104
+ let hasI18nSurface = false;
105
+ const normalizeJoined = (joined)=>{
106
+ const collapsed = joined.replace(/\/+/g, '/');
107
+ const withLeading = collapsed.startsWith('/') ? collapsed : `/${collapsed}`;
108
+ return withLeading.length > 1 ? withLeading.replace(/\/+$/, '') : withLeading;
109
+ };
110
+ const record = (canonicalPath)=>{
111
+ const normalized = normalizeJoined(canonicalPath || '/');
112
+ const key = toTanstackPath(normalized);
113
+ if (!canonicalParams.has(key)) canonicalParams.set(key, paramsTypeForCanonicalPath(normalized));
114
+ };
115
+ const visit = (route, parentPath)=>{
116
+ let currentPath = parentPath;
117
+ if ('string' == typeof route.modernCanonicalPath) {
118
+ hasI18nSurface = true;
119
+ currentPath = normalizeJoined(route.modernCanonicalPath);
120
+ } else if ('string' == typeof route.path && route.path.length > 0) {
121
+ const segments = route.path.replace(/\[(.+?)\]/g, ':$1').split('/').filter(Boolean);
122
+ if (localeParamHeuristic && '' === parentPath && LOCALE_PARAM_SEGMENTS.has(segments[0])) {
123
+ hasI18nSurface = true;
124
+ segments.shift();
125
+ }
126
+ currentPath = segments.length ? normalizeJoined(`${parentPath}/${segments.join('/')}`) : parentPath;
127
+ }
128
+ const children = route.children;
129
+ if (children && children.length > 0) {
130
+ for (const child of children)visit(child, currentPath);
131
+ return;
132
+ }
133
+ record(currentPath || '/');
134
+ };
135
+ const rootModern = routes.find((route)=>route.isRoot);
136
+ const topLevel = rootModern ? rootModern.children ?? [] : routes;
137
+ for (const route of topLevel)visit(route, '');
138
+ if (!hasI18nSurface || 0 === canonicalParams.size) return null;
139
+ return Object.fromEntries([
140
+ ...canonicalParams.entries()
141
+ ].sort(([a], [b])=>a.localeCompare(b)));
91
142
  }
92
143
  async function generateTanstackRouterTypesSourceForEntry(opts) {
93
144
  const { appContext, entryName, generatedDirName = 'modern-tanstack', routes } = opts;
@@ -97,12 +148,30 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
97
148
  const imports = [];
98
149
  const statements = [];
99
150
  const loaderImportMap = new Map();
151
+ const componentImportMap = new Map();
100
152
  const searchContractImportMap = new Map();
101
153
  const usedRouteVarNames = new Set();
102
154
  let loaderIndex = 0;
155
+ let componentIndex = 0;
103
156
  let validateSearchIndex = 0;
104
157
  let loaderDepsIndex = 0;
105
158
  let routeIndex = 0;
159
+ const getImportNameForComponent = (componentPath)=>{
160
+ if ('string' != typeof componentPath || 0 === componentPath.length) return Promise.resolve(null);
161
+ let pendingImportName = componentImportMap.get(componentPath);
162
+ if (!pendingImportName) {
163
+ pendingImportName = (async ()=>{
164
+ const resolvedNoExt = await resolveRouteModuleNoExt(componentPath);
165
+ if (!resolvedNoExt) return null;
166
+ const relImport = normalizeRelativeImport(path.relative(outDir, resolvedNoExt));
167
+ const componentName = `component_${componentIndex++}`;
168
+ imports.push(`import ${componentName} from ${quote(relImport)};`);
169
+ return componentName;
170
+ })();
171
+ componentImportMap.set(componentPath, pendingImportName);
172
+ }
173
+ return pendingImportName;
174
+ };
106
175
  const resolveRouteModuleNoExt = async (aliasedNoExtPath)=>{
107
176
  const prefix = `${appContext.internalSrcAlias}/`;
108
177
  let absNoExt;
@@ -177,6 +246,8 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
177
246
  const routeOpts = [
178
247
  `getParentRoute: () => ${parentVar},`
179
248
  ];
249
+ const componentName = await getImportNameForComponent(route._component);
250
+ if (componentName) routeOpts.push(`component: ${componentName},`);
180
251
  if (isPathlessLayout(route)) {
181
252
  const id = route.id;
182
253
  routeOpts.push(`id: ${quote(id || 'pathless')},`);
@@ -219,6 +290,8 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
219
290
  route
220
291
  })));
221
292
  const rootOpts = [];
293
+ const rootComponentName = await getImportNameForComponent(rootModern?._component);
294
+ if (rootComponentName) rootOpts.push(`component: ${rootComponentName},`);
222
295
  if (rootLoaderName) rootOpts.push(`loader: modernLoaderToTanstack({ hasSplat: false }, ${rootLoaderName}),`);
223
296
  if (rootValidateSearchName) rootOpts.push(`validateSearch: ${rootValidateSearchName},`);
224
297
  if (rootLoaderDepsName) rootOpts.push(`loaderDeps: ${rootLoaderDepsName},`);
@@ -227,178 +300,15 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
227
300
 
228
301
  import {
229
302
  createMemoryHistory,
230
- modernTanstackRouterFastDefaults,
231
303
  createRootRouteWithContext,
232
304
  createRoute,
233
305
  createRouter,
234
- notFound,
235
- redirect,
306
+ createRouteStaticData,
307
+ type ModernRouterContext,
308
+ modernLoaderToTanstack,
309
+ modernTanstackRouterFastDefaults,
236
310
  } from '@modern-js/plugin-tanstack/runtime';
237
311
 
238
- type ModernRouterContext = {
239
- request?: Request;
240
- requestContext?: unknown;
241
- };
242
-
243
- function isResponse(value: unknown): value is Response {
244
- return (
245
- value != null &&
246
- typeof value === 'object' &&
247
- typeof (value as any).status === 'number' &&
248
- typeof (value as any).headers === 'object'
249
- );
250
- }
251
-
252
- const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
253
- function isRedirectResponse(res: Response) {
254
- return redirectStatusCodes.has(res.status);
255
- }
256
-
257
- function throwTanstackRedirect(location: string) {
258
- const target = location.length > 0 ? location : '/';
259
- try {
260
- void new URL(target);
261
- throw redirect({ href: target });
262
- } catch {
263
- throw redirect({ to: target });
264
- }
265
- }
266
-
267
- function mapParamsForModernLoader(params: Record<string, string>, hasSplat: boolean) {
268
- if (!hasSplat) {
269
- return params;
270
- }
271
-
272
- const { _splat, ...rest } = params as any;
273
- if (typeof _splat !== 'undefined') {
274
- return { ...rest, '*': _splat };
275
- }
276
- return rest;
277
- }
278
-
279
- function createRouteStaticData(opts: {
280
- modernRouteId?: string;
281
- modernRouteAction?: unknown;
282
- modernRouteLoader?: unknown;
283
- }) {
284
- const staticData: {
285
- modernRouteId?: string;
286
- modernRouteAction?: unknown;
287
- modernRouteLoader?: unknown;
288
- } = {};
289
-
290
- if (typeof opts.modernRouteId === 'string' && opts.modernRouteId.length > 0) {
291
- staticData.modernRouteId = opts.modernRouteId;
292
- }
293
-
294
- if (typeof opts.modernRouteLoader !== 'undefined') {
295
- staticData.modernRouteLoader = opts.modernRouteLoader;
296
- }
297
-
298
- if (typeof opts.modernRouteAction !== 'undefined') {
299
- staticData.modernRouteAction = opts.modernRouteAction;
300
- }
301
-
302
- return staticData;
303
- }
304
-
305
- function getLoaderSignal(ctx: any): AbortSignal {
306
- const abortSignal = ctx?.abortController?.signal;
307
- if (abortSignal instanceof AbortSignal) {
308
- return abortSignal;
309
- }
310
- if (ctx?.signal instanceof AbortSignal) {
311
- return ctx.signal;
312
- }
313
- return new AbortController().signal;
314
- }
315
-
316
- function getLoaderHref(ctx: any): string {
317
- if (typeof ctx?.location === 'string') {
318
- return ctx.location;
319
- }
320
-
321
- const publicHref = ctx?.location?.publicHref;
322
- if (typeof publicHref === 'string') {
323
- return publicHref;
324
- }
325
-
326
- const href = ctx?.location?.href;
327
- if (typeof href === 'string') {
328
- return href;
329
- }
330
-
331
- const urlHref = ctx?.location?.url?.href;
332
- return typeof urlHref === 'string' ? urlHref : '';
333
- }
334
-
335
- function getLoaderParams(ctx: any): Record<string, string> {
336
- return typeof ctx?.params === 'object' && ctx.params !== null ? ctx.params : {};
337
- }
338
-
339
- function handleModernLoaderResult<LoaderResult>(result: LoaderResult): LoaderResult {
340
- if (isResponse(result)) {
341
- if (isRedirectResponse(result)) {
342
- const location = result.headers.get('Location') ?? '/';
343
- throwTanstackRedirect(location);
344
- }
345
- if (result.status === 404) {
346
- throw notFound();
347
- }
348
- }
349
-
350
- return result;
351
- }
352
-
353
- function handleModernLoaderError(err: unknown): never {
354
- if (isResponse(err)) {
355
- if (isRedirectResponse(err)) {
356
- const location = err.headers.get('Location') ?? '/';
357
- throwTanstackRedirect(location);
358
- }
359
- if (err.status === 404) {
360
- throw notFound();
361
- }
362
- }
363
-
364
- throw err;
365
- }
366
-
367
- function modernLoaderToTanstack<TLoader extends (args: any) => any>(
368
- opts: { hasSplat: boolean },
369
- modernLoader: TLoader,
370
- ) {
371
- type LoaderResult = Awaited<ReturnType<TLoader>>;
372
-
373
- return (ctx: any): Promise<LoaderResult> => {
374
- try {
375
- const signal = getLoaderSignal(ctx);
376
- const baseRequest: Request | undefined =
377
- ctx?.context?.request instanceof Request ? ctx.context.request : undefined;
378
-
379
- const href = getLoaderHref(ctx);
380
-
381
- const request = baseRequest !== undefined
382
- ? new Request(baseRequest, { signal })
383
- : new Request(href, { signal });
384
-
385
- const params = mapParamsForModernLoader(getLoaderParams(ctx), opts.hasSplat);
386
-
387
- return Promise.resolve(
388
- (modernLoader as any)({
389
- request,
390
- params,
391
- context: ctx?.context?.requestContext,
392
- }),
393
- )
394
- .then((result: LoaderResult) => handleModernLoaderResult(result))
395
- .catch(handleModernLoaderError);
396
- } catch (err) {
397
- handleModernLoaderError(err);
398
- }
399
- };
400
- }
401
-
402
312
  ${imports.join('\n')}
403
313
 
404
314
  export const rootRoute = createRootRouteWithContext<ModernRouterContext>()({
@@ -427,4 +337,4 @@ export const router = createRouter({
427
337
  routerGenTs
428
338
  };
429
339
  }
430
- export { generateTanstackRouterTypesSourceForEntry, isTanstackRouterFrameworkEnabled };
340
+ export { collectCanonicalRoutesForEntry, generateTanstackRouterTypesSourceForEntry };
@@ -1,9 +1,2 @@
1
1
  import "node:module";
2
- import { createSyncHook } from "@modern-js/plugin";
3
- const modifyRoutes = createSyncHook();
4
- const onBeforeCreateRoutes = createSyncHook();
5
- const onBeforeCreateRouter = createSyncHook();
6
- const onAfterCreateRouter = createSyncHook();
7
- const onBeforeHydrateRouter = createSyncHook();
8
- const onAfterHydrateRouter = createSyncHook();
9
- export { modifyRoutes, onAfterCreateRouter, onAfterHydrateRouter, onBeforeCreateRouter, onBeforeCreateRoutes, onBeforeHydrateRouter };
2
+ export { modifyRoutes, onAfterCreateRouter, onAfterHydrateRouter, onBeforeCreateRouter, onBeforeCreateRoutes, onBeforeHydrateRouter, routerProviderRegistryHooks } from "@modern-js/runtime/context";
@@ -2,9 +2,10 @@ import "node:module";
2
2
  import { jsx } from "react/jsx-runtime";
3
3
  import { Suspense } from "react";
4
4
  function wrapTanstackSsrHydrationBoundary(routerContent, shouldWrap) {
5
- return shouldWrap ? /*#__PURE__*/ jsx(Suspense, {
5
+ if (shouldWrap) return /*#__PURE__*/ jsx(Suspense, {
6
6
  fallback: null,
7
7
  children: routerContent
8
- }) : routerContent;
8
+ });
9
+ return routerContent;
9
10
  }
10
11
  export { wrapTanstackSsrHydrationBoundary };
@@ -1,8 +1,10 @@
1
1
  import "node:module";
2
+ import "./register.mjs";
2
3
  export * from "@tanstack/react-router";
3
- export { Outlet, useLocation, useMatch, useMatches, useNavigate, useRouter } from "@tanstack/react-router";
4
4
  export { Form, RouteActionResponseError, useFetcher } from "./dataMutation.mjs";
5
+ export { createRouteStaticData, isAbsoluteUrl, modernLoaderToTanstack, throwTanstackRedirect } from "./loaderBridge.mjs";
6
+ export { Outlet } from "./outlet.mjs";
5
7
  export { tanstackRouterPlugin as default, tanstackRouterPlugin } from "./plugin.mjs";
6
8
  export { Link, NavLink } from "./prefetchLink.mjs";
7
- export { CompositeComponent } from "./rsc/client.mjs";
9
+ export { getTanstackRouterState } from "./state.mjs";
8
10
  export { getModernTanstackRouterFastDefaults, modernTanstackRouterFastDefaults } from "./types.mjs";
@@ -1,83 +1,2 @@
1
1
  import "node:module";
2
- function toHydrationScripts(state) {
3
- if (state.hydrationScripts?.length) return state.hydrationScripts;
4
- return state.hydrationScript ? [
5
- state.hydrationScript
6
- ] : void 0;
7
- }
8
- function getMatchedRouteIdsFromMatches(matches) {
9
- const routeIds = matches?.map((match)=>match.assetRouteId ?? match.routeId).filter((routeId)=>'string' == typeof routeId);
10
- return routeIds?.length ? routeIds : void 0;
11
- }
12
- function createRouterServerSnapshot(state) {
13
- const hydrationScripts = toHydrationScripts(state);
14
- const matchedRouteIds = state.matchedRouteIds ?? getMatchedRouteIdsFromMatches(state.matches);
15
- return {
16
- ...state,
17
- ...hydrationScripts?.length ? {
18
- hydrationScript: state.hydrationScript ?? hydrationScripts[0],
19
- hydrationScripts
20
- } : {},
21
- ...matchedRouteIds ? {
22
- matchedRouteIds
23
- } : {}
24
- };
25
- }
26
- function createRouterRuntimeState(state) {
27
- const hasSnapshotState = Boolean(state.serverSnapshot) || Boolean(state.hydrationScript) || Boolean(state.hydrationScripts?.length) || Boolean(state.matchedRouteIds?.length) || Boolean(state.matches?.length);
28
- const serverSnapshot = state.serverSnapshot ? createRouterServerSnapshot({
29
- ...state.serverSnapshot,
30
- framework: state.serverSnapshot.framework ?? state.framework,
31
- basename: state.serverSnapshot.basename ?? state.basename,
32
- hydrationScript: state.serverSnapshot.hydrationScript ?? state.hydrationScript,
33
- hydrationScripts: state.serverSnapshot.hydrationScripts ?? state.hydrationScripts,
34
- matchedRouteIds: state.serverSnapshot.matchedRouteIds ?? state.matchedRouteIds,
35
- matches: state.serverSnapshot.matches ?? state.matches
36
- }) : hasSnapshotState ? createRouterServerSnapshot({
37
- framework: state.framework,
38
- basename: state.basename,
39
- hydrationScript: state.hydrationScript,
40
- hydrationScripts: state.hydrationScripts,
41
- matchedRouteIds: state.matchedRouteIds,
42
- matches: state.matches
43
- }) : void 0;
44
- const hydrationScripts = toHydrationScripts({
45
- hydrationScript: state.hydrationScript ?? serverSnapshot?.hydrationScript,
46
- hydrationScripts: state.hydrationScripts ?? serverSnapshot?.hydrationScripts
47
- });
48
- const matchedRouteIds = state.matchedRouteIds ?? serverSnapshot?.matchedRouteIds ?? getMatchedRouteIdsFromMatches(state.matches);
49
- return {
50
- ...state,
51
- ...hydrationScripts?.length ? {
52
- hydrationScript: state.hydrationScript ?? hydrationScripts[0],
53
- hydrationScripts
54
- } : {},
55
- ...matchedRouteIds ? {
56
- matchedRouteIds
57
- } : {},
58
- ...serverSnapshot ? {
59
- serverSnapshot
60
- } : {}
61
- };
62
- }
63
- function applyRouterRuntimeState(runtimeContext, state) {
64
- const normalized = createRouterRuntimeState(state);
65
- const mutableRuntimeContext = runtimeContext;
66
- mutableRuntimeContext.routerFramework = normalized.framework;
67
- mutableRuntimeContext.routerInstance = normalized.instance;
68
- mutableRuntimeContext.routerHydrationScript = normalized.hydrationScript;
69
- mutableRuntimeContext.routerMatchedRouteIds = normalized.matchedRouteIds;
70
- mutableRuntimeContext.routerRuntime = normalized;
71
- if (normalized.serverSnapshot) mutableRuntimeContext.routerServerSnapshot = normalized.serverSnapshot;
72
- return runtimeContext;
73
- }
74
- function applyRouterServerPrepareResult(runtimeContext, result) {
75
- const state = createRouterRuntimeState({
76
- ...result.state,
77
- cleanup: result.cleanup ?? result.state.cleanup,
78
- serverSnapshot: result.snapshot ?? result.state.serverSnapshot
79
- });
80
- applyRouterRuntimeState(runtimeContext, state);
81
- return runtimeContext;
82
- }
83
- export { applyRouterRuntimeState, applyRouterServerPrepareResult, createRouterRuntimeState, createRouterServerSnapshot };
2
+ export { applyRouterRuntimeState, applyRouterServerPrepareResult, createRouterRuntimeState, createRouterServerSnapshot, getRouterRuntimeState, getRouterServerSnapshot } from "@modern-js/runtime/context";
@@ -0,0 +1,115 @@
1
+ import "node:module";
2
+ import { notFound, redirect } from "@tanstack/react-router";
3
+ function isResponse(value) {
4
+ const record = value;
5
+ return null != record && 'object' == typeof record && 'number' == typeof record.status && 'object' == typeof record.headers;
6
+ }
7
+ const redirectStatusCodes = new Set([
8
+ 301,
9
+ 302,
10
+ 303,
11
+ 307,
12
+ 308
13
+ ]);
14
+ function isRedirectResponse(res) {
15
+ return redirectStatusCodes.has(res.status);
16
+ }
17
+ function isTanstackRedirect(value) {
18
+ return isResponse(value) && 'object' == typeof value.options;
19
+ }
20
+ function isAbsoluteUrl(value) {
21
+ try {
22
+ new URL(value);
23
+ return true;
24
+ } catch {
25
+ return false;
26
+ }
27
+ }
28
+ function throwTanstackRedirect(location) {
29
+ const target = location || '/';
30
+ if (isAbsoluteUrl(target)) throw redirect({
31
+ href: target
32
+ });
33
+ throw redirect({
34
+ to: target
35
+ });
36
+ }
37
+ function mapSplatParamsForModernLoader(params, hasSplat) {
38
+ if (!hasSplat) return params;
39
+ const { _splat, ...rest } = params;
40
+ if (void 0 !== _splat) return {
41
+ ...rest,
42
+ '*': _splat
43
+ };
44
+ return rest;
45
+ }
46
+ function createRouteStaticData(opts) {
47
+ const staticData = {};
48
+ if ('string' == typeof opts.modernRouteId && opts.modernRouteId.length > 0) staticData.modernRouteId = opts.modernRouteId;
49
+ if (void 0 !== opts.modernRouteLoader) staticData.modernRouteLoader = opts.modernRouteLoader;
50
+ if (void 0 !== opts.modernRouteAction) staticData.modernRouteAction = opts.modernRouteAction;
51
+ return staticData;
52
+ }
53
+ function getLoaderSignal(ctx) {
54
+ const abortSignal = ctx?.abortController?.signal;
55
+ if (abortSignal instanceof AbortSignal) return abortSignal;
56
+ if (ctx?.signal instanceof AbortSignal) return ctx.signal;
57
+ return new AbortController().signal;
58
+ }
59
+ function getLoaderHref(ctx) {
60
+ if ('string' == typeof ctx?.location) return ctx.location;
61
+ const publicHref = ctx?.location?.publicHref;
62
+ if ('string' == typeof publicHref) return publicHref;
63
+ const href = ctx?.location?.href;
64
+ if ('string' == typeof href) return href;
65
+ const urlHref = ctx?.location?.url?.href;
66
+ return 'string' == typeof urlHref ? urlHref : '';
67
+ }
68
+ function getLoaderParams(ctx) {
69
+ return 'object' == typeof ctx?.params && null !== ctx.params ? ctx.params : {};
70
+ }
71
+ function handleModernLoaderResult(result) {
72
+ if (isResponse(result)) {
73
+ if (isRedirectResponse(result)) {
74
+ const location = result.headers.get('Location') ?? '/';
75
+ throwTanstackRedirect(location);
76
+ }
77
+ if (404 === result.status) throw notFound();
78
+ }
79
+ return result;
80
+ }
81
+ function handleModernLoaderError(err) {
82
+ if (isResponse(err)) {
83
+ if (isTanstackRedirect(err)) throw err;
84
+ if (isRedirectResponse(err)) {
85
+ const location = err.headers.get('Location') ?? '/';
86
+ throwTanstackRedirect(location);
87
+ }
88
+ if (404 === err.status) throw notFound();
89
+ }
90
+ throw err;
91
+ }
92
+ function modernLoaderToTanstack(opts, modernLoader) {
93
+ return (rawCtx)=>{
94
+ const ctx = rawCtx;
95
+ try {
96
+ const signal = getLoaderSignal(ctx);
97
+ const baseRequest = ctx?.context?.request instanceof Request ? ctx.context.request : void 0;
98
+ const href = getLoaderHref(ctx);
99
+ const request = void 0 !== baseRequest ? new Request(baseRequest, {
100
+ signal
101
+ }) : new Request(href, {
102
+ signal
103
+ });
104
+ const params = mapSplatParamsForModernLoader(getLoaderParams(ctx), opts.hasSplat);
105
+ return Promise.resolve(modernLoader({
106
+ request,
107
+ params,
108
+ context: ctx?.context?.requestContext
109
+ })).then((result)=>handleModernLoaderResult(result)).catch(handleModernLoaderError);
110
+ } catch (err) {
111
+ handleModernLoaderError(err);
112
+ }
113
+ };
114
+ }
115
+ export { createRouteStaticData, isAbsoluteUrl, isRedirectResponse, isResponse, isTanstackRedirect, mapSplatParamsForModernLoader, modernLoaderToTanstack, throwTanstackRedirect };
@@ -0,0 +1,18 @@
1
+ import "node:module";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import { Outlet } from "@tanstack/react-router";
4
+ import { createElement, memo } from "react";
5
+ const outlet_Outlet = /*#__PURE__*/ memo(function() {
6
+ return /*#__PURE__*/ jsx(Outlet, {});
7
+ });
8
+ function withModernRouteMatchContext(component, _routeId) {
9
+ if (null == component) return component;
10
+ const Component = component;
11
+ const WrappedRouteComponent = (props)=>/*#__PURE__*/ createElement(Component, props);
12
+ const preloadable = component;
13
+ if ('function' == typeof preloadable.load) WrappedRouteComponent.load = preloadable.load.bind(preloadable);
14
+ if ('function' == typeof preloadable.preload) WrappedRouteComponent.preload = preloadable.preload.bind(preloadable);
15
+ else if ('function' == typeof preloadable.load) WrappedRouteComponent.preload = WrappedRouteComponent.load;
16
+ return WrappedRouteComponent;
17
+ }
18
+ export { outlet_Outlet as Outlet, withModernRouteMatchContext };