@tanstack/start-plugin-core 1.20.3-alpha.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 (111) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -0
  3. package/dist/cjs/compilers.cjs +402 -0
  4. package/dist/cjs/compilers.cjs.map +1 -0
  5. package/dist/cjs/compilers.d.cts +21 -0
  6. package/dist/cjs/extractHtmlScripts.cjs +35 -0
  7. package/dist/cjs/extractHtmlScripts.cjs.map +1 -0
  8. package/dist/cjs/extractHtmlScripts.d.cts +4 -0
  9. package/dist/cjs/index.cjs +15 -0
  10. package/dist/cjs/index.cjs.map +1 -0
  11. package/dist/cjs/index.d.cts +7 -0
  12. package/dist/cjs/nitro/build-nitro.cjs +18 -0
  13. package/dist/cjs/nitro/build-nitro.cjs.map +1 -0
  14. package/dist/cjs/nitro/build-nitro.d.cts +2 -0
  15. package/dist/cjs/nitro/build-sitemap.cjs +54 -0
  16. package/dist/cjs/nitro/build-sitemap.cjs.map +1 -0
  17. package/dist/cjs/nitro/build-sitemap.d.cts +9 -0
  18. package/dist/cjs/nitro/dev-server-plugin.cjs +128 -0
  19. package/dist/cjs/nitro/dev-server-plugin.cjs.map +1 -0
  20. package/dist/cjs/nitro/dev-server-plugin.d.cts +5 -0
  21. package/dist/cjs/nitro/nitro-plugin.cjs +128 -0
  22. package/dist/cjs/nitro/nitro-plugin.cjs.map +1 -0
  23. package/dist/cjs/nitro/nitro-plugin.d.cts +3 -0
  24. package/dist/cjs/plugin.cjs +117 -0
  25. package/dist/cjs/plugin.cjs.map +1 -0
  26. package/dist/cjs/plugin.d.cts +2713 -0
  27. package/dist/cjs/prerender.cjs +171 -0
  28. package/dist/cjs/prerender.cjs.map +1 -0
  29. package/dist/cjs/prerender.d.cts +8 -0
  30. package/dist/cjs/queue.cjs +131 -0
  31. package/dist/cjs/queue.cjs.map +1 -0
  32. package/dist/cjs/queue.d.cts +32 -0
  33. package/dist/cjs/routesManifestPlugin.cjs +165 -0
  34. package/dist/cjs/routesManifestPlugin.cjs.map +1 -0
  35. package/dist/cjs/routesManifestPlugin.d.cts +3 -0
  36. package/dist/cjs/schema.cjs +136 -0
  37. package/dist/cjs/schema.cjs.map +1 -0
  38. package/dist/cjs/schema.d.cts +8128 -0
  39. package/dist/cjs/start-compiler-plugin.cjs +72 -0
  40. package/dist/cjs/start-compiler-plugin.cjs.map +1 -0
  41. package/dist/cjs/start-compiler-plugin.d.cts +13 -0
  42. package/dist/cjs/start-server-routes-plugin/config.d.cts +49 -0
  43. package/dist/cjs/start-server-routes-plugin/plugin.cjs +608 -0
  44. package/dist/cjs/start-server-routes-plugin/plugin.cjs.map +1 -0
  45. package/dist/cjs/start-server-routes-plugin/plugin.d.cts +3 -0
  46. package/dist/cjs/start-server-routes-plugin/template.cjs +111 -0
  47. package/dist/cjs/start-server-routes-plugin/template.cjs.map +1 -0
  48. package/dist/cjs/start-server-routes-plugin/template.d.cts +34 -0
  49. package/dist/esm/compilers.d.ts +21 -0
  50. package/dist/esm/compilers.js +384 -0
  51. package/dist/esm/compilers.js.map +1 -0
  52. package/dist/esm/extractHtmlScripts.d.ts +4 -0
  53. package/dist/esm/extractHtmlScripts.js +18 -0
  54. package/dist/esm/extractHtmlScripts.js.map +1 -0
  55. package/dist/esm/index.d.ts +7 -0
  56. package/dist/esm/index.js +15 -0
  57. package/dist/esm/index.js.map +1 -0
  58. package/dist/esm/nitro/build-nitro.d.ts +2 -0
  59. package/dist/esm/nitro/build-nitro.js +18 -0
  60. package/dist/esm/nitro/build-nitro.js.map +1 -0
  61. package/dist/esm/nitro/build-sitemap.d.ts +9 -0
  62. package/dist/esm/nitro/build-sitemap.js +54 -0
  63. package/dist/esm/nitro/build-sitemap.js.map +1 -0
  64. package/dist/esm/nitro/dev-server-plugin.d.ts +5 -0
  65. package/dist/esm/nitro/dev-server-plugin.js +128 -0
  66. package/dist/esm/nitro/dev-server-plugin.js.map +1 -0
  67. package/dist/esm/nitro/nitro-plugin.d.ts +3 -0
  68. package/dist/esm/nitro/nitro-plugin.js +128 -0
  69. package/dist/esm/nitro/nitro-plugin.js.map +1 -0
  70. package/dist/esm/plugin.d.ts +2713 -0
  71. package/dist/esm/plugin.js +117 -0
  72. package/dist/esm/plugin.js.map +1 -0
  73. package/dist/esm/prerender.d.ts +8 -0
  74. package/dist/esm/prerender.js +171 -0
  75. package/dist/esm/prerender.js.map +1 -0
  76. package/dist/esm/queue.d.ts +32 -0
  77. package/dist/esm/queue.js +131 -0
  78. package/dist/esm/queue.js.map +1 -0
  79. package/dist/esm/routesManifestPlugin.d.ts +3 -0
  80. package/dist/esm/routesManifestPlugin.js +165 -0
  81. package/dist/esm/routesManifestPlugin.js.map +1 -0
  82. package/dist/esm/schema.d.ts +8128 -0
  83. package/dist/esm/schema.js +136 -0
  84. package/dist/esm/schema.js.map +1 -0
  85. package/dist/esm/start-compiler-plugin.d.ts +13 -0
  86. package/dist/esm/start-compiler-plugin.js +72 -0
  87. package/dist/esm/start-compiler-plugin.js.map +1 -0
  88. package/dist/esm/start-server-routes-plugin/config.d.ts +49 -0
  89. package/dist/esm/start-server-routes-plugin/plugin.d.ts +3 -0
  90. package/dist/esm/start-server-routes-plugin/plugin.js +608 -0
  91. package/dist/esm/start-server-routes-plugin/plugin.js.map +1 -0
  92. package/dist/esm/start-server-routes-plugin/template.d.ts +34 -0
  93. package/dist/esm/start-server-routes-plugin/template.js +111 -0
  94. package/dist/esm/start-server-routes-plugin/template.js.map +1 -0
  95. package/package.json +72 -0
  96. package/src/compilers.ts +759 -0
  97. package/src/extractHtmlScripts.ts +19 -0
  98. package/src/index.ts +15 -0
  99. package/src/nitro/build-nitro.ts +27 -0
  100. package/src/nitro/build-sitemap.ts +79 -0
  101. package/src/nitro/dev-server-plugin.ts +159 -0
  102. package/src/nitro/nitro-plugin.ts +161 -0
  103. package/src/plugin.ts +145 -0
  104. package/src/prerender.ts +245 -0
  105. package/src/queue.ts +153 -0
  106. package/src/routesManifestPlugin.ts +216 -0
  107. package/src/schema.ts +193 -0
  108. package/src/start-compiler-plugin.ts +111 -0
  109. package/src/start-server-routes-plugin/config.ts +8 -0
  110. package/src/start-server-routes-plugin/plugin.ts +890 -0
  111. package/src/start-server-routes-plugin/template.ts +164 -0
@@ -0,0 +1,608 @@
1
+ import path, { normalize, join, isAbsolute } from "node:path";
2
+ import fs from "node:fs";
3
+ import fsp from "node:fs/promises";
4
+ import { logging, virtualGetRouteNodes, physicalGetRouteNodes, rootPathId, multiSortBy, writeIfDifferent, format, removeExt, resetRegex, trimPathLeft, removeUnderscores, routePathToVariable, replaceBackslash } from "@tanstack/router-generator";
5
+ import { rootRouteId } from "@tanstack/router-core";
6
+ import { getTargetTemplate, fillTemplate } from "./template.js";
7
+ let lock = false;
8
+ const checkLock = () => lock;
9
+ const setLock = (bool) => {
10
+ lock = bool;
11
+ };
12
+ function TanStackStartServerRoutesVite(config) {
13
+ let ROOT = process.cwd();
14
+ const getRoutesDirectoryPath = () => {
15
+ return isAbsolute(config.routesDirectory) ? config.routesDirectory : join(ROOT, config.routesDirectory);
16
+ };
17
+ const generate = async () => {
18
+ if (checkLock()) {
19
+ return;
20
+ }
21
+ setLock(true);
22
+ try {
23
+ await generator(config, ROOT);
24
+ } catch (err) {
25
+ console.error(err);
26
+ console.info();
27
+ } finally {
28
+ setLock(false);
29
+ }
30
+ };
31
+ const handleFile = async (file) => {
32
+ const filePath = normalize(file);
33
+ const routesDirectoryPath = getRoutesDirectoryPath();
34
+ if (filePath.startsWith(routesDirectoryPath)) {
35
+ await generate();
36
+ }
37
+ };
38
+ return {
39
+ name: "tanstack-start-server-routes-plugin",
40
+ configureServer(server) {
41
+ server.watcher.on("all", (event, path2) => {
42
+ handleFile(path2);
43
+ });
44
+ },
45
+ configResolved(config2) {
46
+ ROOT = config2.root;
47
+ },
48
+ async buildStart() {
49
+ await generate();
50
+ },
51
+ sharedDuringBuild: true,
52
+ resolveId(id) {
53
+ if (id === "tanstack:server-routes") {
54
+ const generatedRouteTreePath = getGeneratedRouteTreePath(ROOT);
55
+ return generatedRouteTreePath;
56
+ }
57
+ return null;
58
+ }
59
+ };
60
+ }
61
+ let latestTask = 0;
62
+ const routeGroupPatternRegex = /\(.+\)/g;
63
+ const possiblyNestedRouteGroupPatternRegex = /\([^/]+\)\/?/g;
64
+ function getGeneratedRouteTreePath(root) {
65
+ return path.resolve(root, ".tanstack-start/server-routes/routeTree.gen.ts");
66
+ }
67
+ async function generator(config, root) {
68
+ const generatedServerRouteTreePath = getGeneratedRouteTreePath(root);
69
+ const ROUTE_TEMPLATE = getTargetTemplate(config.target);
70
+ const logger = logging({ disabled: config.disableLogging });
71
+ const taskId = latestTask + 1;
72
+ latestTask = taskId;
73
+ const checkLatest = () => {
74
+ if (latestTask !== taskId) {
75
+ return false;
76
+ }
77
+ return true;
78
+ };
79
+ let getRouteNodesResult;
80
+ if (config.virtualRouteConfig) {
81
+ getRouteNodesResult = await virtualGetRouteNodes(config, root);
82
+ } else {
83
+ getRouteNodesResult = await physicalGetRouteNodes(config, root);
84
+ }
85
+ const { rootRouteNode, routeNodes: beforeRouteNodes } = getRouteNodesResult;
86
+ if (rootRouteNode === void 0) {
87
+ let errorMessage = `rootRouteNode must not be undefined. Make sure you've added your root route into the route-tree.`;
88
+ if (!config.virtualRouteConfig) {
89
+ errorMessage += `
90
+ Make sure that you add a "${rootPathId}.tsx" file to your routes directory.
91
+ Add the file in: "${config.routesDirectory}/${rootPathId}.tsx"`;
92
+ }
93
+ throw new Error(errorMessage);
94
+ }
95
+ const preRouteNodes = multiSortBy(beforeRouteNodes, [
96
+ (d) => d.routePath === "/" ? -1 : 1,
97
+ (d) => {
98
+ var _a;
99
+ return (_a = d.routePath) == null ? void 0 : _a.split("/").length;
100
+ },
101
+ (d) => d.filePath.match(new RegExp(`[./]${config.indexToken}[.]`)) ? 1 : -1,
102
+ (d) => d.filePath.match(
103
+ /[./](component|errorComponent|pendingComponent|loader|lazy)[.]/
104
+ ) ? 1 : -1,
105
+ (d) => d.filePath.match(new RegExp(`[./]${config.routeToken}[.]`)) ? -1 : 1,
106
+ (d) => {
107
+ var _a;
108
+ return ((_a = d.routePath) == null ? void 0 : _a.endsWith("/")) ? -1 : 1;
109
+ },
110
+ (d) => d.routePath
111
+ ]).filter((d) => ![`/${rootPathId}`].includes(d.routePath || ""));
112
+ const routeTree = [];
113
+ const routeNodes = [];
114
+ const handleRootNode = async (node) => {
115
+ if (!node) {
116
+ return;
117
+ }
118
+ const routeCode = fs.readFileSync(node.fullPath, "utf-8");
119
+ if (!routeCode) {
120
+ const _rootTemplate = ROUTE_TEMPLATE.rootRoute;
121
+ const replaced = await fillTemplate(config, _rootTemplate.template(), {
122
+ tsrImports: _rootTemplate.imports.tsrImports(),
123
+ tsrPath: rootPathId,
124
+ tsrExportStart: _rootTemplate.imports.tsrExportStart(),
125
+ tsrExportEnd: _rootTemplate.imports.tsrExportEnd()
126
+ });
127
+ await writeIfDifferent(
128
+ node.fullPath,
129
+ "",
130
+ // Empty string because the file doesn't exist yet
131
+ replaced,
132
+ {
133
+ beforeWrite: () => {
134
+ }
135
+ }
136
+ );
137
+ }
138
+ };
139
+ await handleRootNode(rootRouteNode);
140
+ const handleNode = async (node) => {
141
+ var _a;
142
+ resetRegex(routeGroupPatternRegex);
143
+ let parentRoute = hasParentRoute(routeNodes, node, node.routePath);
144
+ if ((parentRoute == null ? void 0 : parentRoute.isVirtualParentRoute) && ((_a = parentRoute.children) == null ? void 0 : _a.length)) {
145
+ const possibleParentRoute = hasParentRoute(
146
+ parentRoute.children,
147
+ node,
148
+ node.routePath
149
+ );
150
+ if (possibleParentRoute) {
151
+ parentRoute = possibleParentRoute;
152
+ }
153
+ }
154
+ if (parentRoute) node.parent = parentRoute;
155
+ node.path = determineNodePath(node);
156
+ const trimmedPath = trimPathLeft(node.path ?? "");
157
+ const split = trimmedPath.split("/");
158
+ const lastRouteSegment = split[split.length - 1] ?? trimmedPath;
159
+ node.isNonPath = lastRouteSegment.startsWith("_") || routeGroupPatternRegex.test(lastRouteSegment);
160
+ node.cleanedPath = removeGroups(
161
+ removeUnderscores(removeLayoutSegments(node.path)) ?? ""
162
+ );
163
+ const routeCode = fs.readFileSync(node.fullPath, "utf-8");
164
+ if (!node.isVirtualParentRoute && !node.isVirtual) ;
165
+ const cleanedPathIsEmpty = (node.cleanedPath || "").length === 0;
166
+ const nonPathRoute = node._fsRouteType === "pathless_layout" && node.isNonPath;
167
+ node.isVirtualParentRequired = node._fsRouteType === "pathless_layout" || nonPathRoute ? !cleanedPathIsEmpty : false;
168
+ if (!node.isVirtual && node.isVirtualParentRequired) {
169
+ const parentRoutePath = removeLastSegmentFromPath(node.routePath) || "/";
170
+ const parentVariableName = routePathToVariable(parentRoutePath);
171
+ const anchorRoute = routeNodes.find(
172
+ (d) => d.routePath === parentRoutePath
173
+ );
174
+ if (!anchorRoute) {
175
+ const parentNode = {
176
+ ...node,
177
+ path: removeLastSegmentFromPath(node.path) || "/",
178
+ filePath: removeLastSegmentFromPath(node.filePath) || "/",
179
+ fullPath: removeLastSegmentFromPath(node.fullPath) || "/",
180
+ routePath: parentRoutePath,
181
+ variableName: parentVariableName,
182
+ isVirtual: true,
183
+ _fsRouteType: "layout",
184
+ // layout since this route will wrap other routes
185
+ isVirtualParentRoute: true,
186
+ isVirtualParentRequired: false
187
+ };
188
+ parentNode.children = parentNode.children ?? [];
189
+ parentNode.children.push(node);
190
+ node.parent = parentNode;
191
+ if (node._fsRouteType === "pathless_layout") {
192
+ node.path = determineNodePath(node);
193
+ }
194
+ await handleNode(parentNode);
195
+ } else {
196
+ anchorRoute.children = anchorRoute.children ?? [];
197
+ anchorRoute.children.push(node);
198
+ node.parent = anchorRoute;
199
+ }
200
+ }
201
+ if (!routeCode.split("\n").some((line) => line.trim().startsWith("export const ServerRoute"))) {
202
+ return;
203
+ }
204
+ if (node.parent) {
205
+ if (!node.isVirtualParentRequired) {
206
+ node.parent.children = node.parent.children ?? [];
207
+ node.parent.children.push(node);
208
+ }
209
+ } else {
210
+ routeTree.push(node);
211
+ }
212
+ routeNodes.push(node);
213
+ };
214
+ for (const node of preRouteNodes) {
215
+ await handleNode(node);
216
+ }
217
+ checkRouteFullPathUniqueness(routeNodes, config);
218
+ function buildRouteTreeConfig(nodes, depth = 1) {
219
+ const children = nodes.map((node) => {
220
+ var _a, _b;
221
+ if (node._fsRouteType === "__root") {
222
+ return;
223
+ }
224
+ if (node._fsRouteType === "pathless_layout" && !((_a = node.children) == null ? void 0 : _a.length)) {
225
+ return;
226
+ }
227
+ const route = `${node.variableName}Route`;
228
+ if ((_b = node.children) == null ? void 0 : _b.length) {
229
+ const childConfigs = buildRouteTreeConfig(node.children, depth + 1);
230
+ const childrenDeclaration = `interface ${route}Children {
231
+ ${node.children.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(",")}
232
+ }`;
233
+ const children2 = `const ${route}Children: ${route}Children = {
234
+ ${node.children.map((child) => `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`).join(",")}
235
+ }`;
236
+ const routeWithChildren = `const ${route}WithChildren = ${route}._addFileChildren(${route}Children)`;
237
+ return [
238
+ childConfigs,
239
+ childrenDeclaration,
240
+ children2,
241
+ routeWithChildren
242
+ ].join("\n\n");
243
+ }
244
+ return void 0;
245
+ });
246
+ return children.filter(Boolean).join("\n\n");
247
+ }
248
+ const routeConfigChildrenText = buildRouteTreeConfig(routeTree);
249
+ const sortedRouteNodes = multiSortBy(routeNodes, [
250
+ (d) => {
251
+ var _a;
252
+ return ((_a = d.routePath) == null ? void 0 : _a.includes(`/${rootPathId}`)) ? -1 : 1;
253
+ },
254
+ (d) => {
255
+ var _a;
256
+ return (_a = d.routePath) == null ? void 0 : _a.split("/").length;
257
+ },
258
+ (d) => {
259
+ var _a;
260
+ return ((_a = d.routePath) == null ? void 0 : _a.endsWith(config.indexToken)) ? -1 : 1;
261
+ },
262
+ (d) => d
263
+ ]);
264
+ const imports = Object.entries({
265
+ createFileRoute: sortedRouteNodes.some((d) => d.isVirtual)
266
+ }).filter((d) => d[1]).map((d) => d[0]);
267
+ const virtualRouteNodes = sortedRouteNodes.filter((d) => d.isVirtual);
268
+ function getImportPath(node) {
269
+ return replaceBackslash(
270
+ removeExt(
271
+ path.relative(
272
+ path.dirname(generatedServerRouteTreePath),
273
+ path.resolve(config.routesDirectory, node.filePath)
274
+ )
275
+ )
276
+ );
277
+ }
278
+ const rootRouteExists = fs.existsSync(rootRouteNode.fullPath);
279
+ const rootRouteCode = rootRouteExists ? fs.readFileSync(rootRouteNode.fullPath, "utf-8") : "";
280
+ const hasServerRootRoute = rootRouteExists && rootRouteCode.includes("export const ServerRoute");
281
+ const routeImports = [
282
+ ...config.routeTreeFileHeader,
283
+ `// This file was automatically generated by TanStack Router.
284
+ // You should NOT make any changes in this file as it will be overwritten.
285
+ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.`,
286
+ imports.length ? `import { ${imports.join(", ")} } from '${ROUTE_TEMPLATE.fullPkg}'
287
+ ` : "",
288
+ "// Import Routes",
289
+ [
290
+ `import type { FileRoutesByPath, CreateServerFileRoute } from '${ROUTE_TEMPLATE.fullPkg}'`,
291
+ `import { createServerRoute, createServerFileRoute } from '${ROUTE_TEMPLATE.fullPkg}'`,
292
+ hasServerRootRoute ? `import { ServerRoute as rootRouteImport } from './${getImportPath(rootRouteNode)}'` : "",
293
+ ...sortedRouteNodes.filter((d) => !d.isVirtual).map((node) => {
294
+ return `import { ServerRoute as ${node.variableName}RouteImport } from './${getImportPath(node)}'`;
295
+ })
296
+ ].join("\n"),
297
+ virtualRouteNodes.length ? "// Create Virtual Routes" : "",
298
+ virtualRouteNodes.map((node) => {
299
+ return `const ${node.variableName}RouteImport = createFileRoute('${node.routePath}')()`;
300
+ }).join("\n"),
301
+ "// Create/Update Routes",
302
+ !hasServerRootRoute ? `
303
+ const rootRoute = createServerRoute()
304
+ ` : "",
305
+ sortedRouteNodes.map((node) => {
306
+ var _a;
307
+ return [
308
+ [
309
+ `const ${node.variableName}Route = ${node.variableName}RouteImport.update({
310
+ ${[
311
+ `id: '${node.path}'`,
312
+ !node.isNonPath ? `path: '${node.cleanedPath}'` : void 0,
313
+ `getParentRoute: () => ${((_a = node.parent) == null ? void 0 : _a.variableName) ?? "root"}Route`
314
+ ].filter(Boolean).join(",")}
315
+ } as any)`
316
+ ].join("")
317
+ ].join("\n\n");
318
+ }).join("\n\n"),
319
+ "",
320
+ "// Populate the FileRoutesByPath interface",
321
+ `declare module '${ROUTE_TEMPLATE.fullPkg}' {
322
+ interface FileRoutesByPath {
323
+ ${routeNodes.map((routeNode) => {
324
+ var _a, _b;
325
+ const filePathId = routeNode.routePath;
326
+ return `'${filePathId}': {
327
+ id: '${filePathId}'
328
+ path: '${inferPath(routeNode)}'
329
+ fullPath: '${inferFullPath(routeNode)}'
330
+ preLoaderRoute: typeof ${routeNode.variableName}RouteImport
331
+ parentRoute: typeof ${routeNode.isVirtualParentRequired ? `${(_a = routeNode.parent) == null ? void 0 : _a.variableName}Route` : ((_b = routeNode.parent) == null ? void 0 : _b.variableName) ? `${routeNode.parent.variableName}RouteImport` : "rootRoute"}
332
+ }`;
333
+ }).join("\n")}
334
+ }
335
+ }`,
336
+ `// Add type-safety to the createFileRoute function across the route tree`,
337
+ routeNodes.map((routeNode) => {
338
+ var _a;
339
+ return `declare module './${getImportPath(routeNode)}' {
340
+ const createServerFileRoute: CreateServerFileRoute<
341
+ FileRoutesByPath['${routeNode.routePath}']['parentRoute'],
342
+ FileRoutesByPath['${routeNode.routePath}']['id'],
343
+ FileRoutesByPath['${routeNode.routePath}']['path'],
344
+ FileRoutesByPath['${routeNode.routePath}']['fullPath'],
345
+ ${((_a = routeNode.children) == null ? void 0 : _a.length) ? `${routeNode.variableName}RouteChildren` : "unknown"}
346
+ >
347
+ }`;
348
+ }).join("\n"),
349
+ "// Create and export the route tree",
350
+ routeConfigChildrenText,
351
+ `export interface FileRoutesByFullPath {
352
+ ${[...createRouteNodesByFullPath(routeNodes).entries()].map(
353
+ ([fullPath, routeNode]) => {
354
+ return `'${fullPath}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`;
355
+ }
356
+ )}
357
+ }`,
358
+ `export interface FileRoutesByTo {
359
+ ${[...createRouteNodesByTo(routeNodes).entries()].map(([to, routeNode]) => {
360
+ return `'${to}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`;
361
+ })}
362
+ }`,
363
+ `export interface FileRoutesById {
364
+ '${rootRouteId}': typeof rootRoute,
365
+ ${[...createRouteNodesById(routeNodes).entries()].map(([id, routeNode]) => {
366
+ return `'${id}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`;
367
+ })}
368
+ }`,
369
+ `export interface FileRouteTypes {
370
+ fileRoutesByFullPath: FileRoutesByFullPath
371
+ fullPaths: ${routeNodes.length > 0 ? [...createRouteNodesByFullPath(routeNodes).keys()].map((fullPath) => `'${fullPath}'`).join("|") : "never"}
372
+ fileRoutesByTo: FileRoutesByTo
373
+ to: ${routeNodes.length > 0 ? [...createRouteNodesByTo(routeNodes).keys()].map((to) => `'${to}'`).join("|") : "never"}
374
+ id: ${[`'${rootRouteId}'`, ...[...createRouteNodesById(routeNodes).keys()].map((id) => `'${id}'`)].join("|")}
375
+ fileRoutesById: FileRoutesById
376
+ }`,
377
+ `export interface RootRouteChildren {
378
+ ${routeTree.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(",")}
379
+ }`,
380
+ `const rootRouteChildren: RootRouteChildren = {
381
+ ${routeTree.map((child) => `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`).join(",")}
382
+ }`,
383
+ `export const routeTree = rootRoute._addFileChildren(rootRouteChildren)._addFileTypes<FileRouteTypes>()`
384
+ ].filter(Boolean).join("\n\n");
385
+ const createRouteManifest = () => {
386
+ const routesManifest = {
387
+ [rootRouteId]: {
388
+ filePath: rootRouteNode.filePath,
389
+ children: routeTree.map((d) => d.routePath)
390
+ },
391
+ ...Object.fromEntries(
392
+ routeNodes.map((d) => {
393
+ var _a, _b;
394
+ const filePathId = d.routePath;
395
+ return [
396
+ filePathId,
397
+ {
398
+ filePath: d.filePath,
399
+ parent: ((_a = d.parent) == null ? void 0 : _a.routePath) ? d.parent.routePath : void 0,
400
+ children: (_b = d.children) == null ? void 0 : _b.map((childRoute) => childRoute.routePath)
401
+ }
402
+ ];
403
+ })
404
+ )
405
+ };
406
+ return JSON.stringify(
407
+ {
408
+ routes: routesManifest
409
+ },
410
+ null,
411
+ 2
412
+ );
413
+ };
414
+ const includeManifest = ["react", "solid"];
415
+ const routeConfigFileContent = !includeManifest.includes(config.target) ? routeImports : [
416
+ routeImports,
417
+ "\n",
418
+ "/* ROUTE_MANIFEST_START",
419
+ createRouteManifest(),
420
+ "ROUTE_MANIFEST_END */"
421
+ ].join("\n");
422
+ if (!checkLatest()) return;
423
+ const existingRouteTreeContent = await fsp.readFile(path.resolve(generatedServerRouteTreePath), "utf-8").catch((err) => {
424
+ if (err.code === "ENOENT") {
425
+ return "";
426
+ }
427
+ throw err;
428
+ });
429
+ if (!checkLatest()) return;
430
+ await fsp.mkdir(path.dirname(path.resolve(generatedServerRouteTreePath)), {
431
+ recursive: true
432
+ });
433
+ if (!checkLatest()) return;
434
+ const routeTreeWriteResult = await writeIfDifferent(
435
+ path.resolve(generatedServerRouteTreePath),
436
+ await format(existingRouteTreeContent, config),
437
+ await format(routeConfigFileContent, config),
438
+ {
439
+ beforeWrite: () => {
440
+ }
441
+ }
442
+ );
443
+ const startDeclarationFilePath = path.join(
444
+ path.resolve(root, config.srcDirectory),
445
+ "tanstack-start.d.ts"
446
+ );
447
+ const serverRoutesRelativePath = removeExt(
448
+ path.relative(
449
+ path.dirname(startDeclarationFilePath),
450
+ generatedServerRouteTreePath
451
+ )
452
+ );
453
+ const startDeclarationFileContent = buildStartDeclarationFile({
454
+ serverRoutesRelativePath
455
+ });
456
+ if (!fs.existsSync(startDeclarationFilePath)) {
457
+ await writeIfDifferent(
458
+ startDeclarationFilePath,
459
+ "",
460
+ startDeclarationFileContent,
461
+ {
462
+ beforeWrite: () => {
463
+ logger.log(`🟡 Creating tanstack-start.d.ts`);
464
+ }
465
+ }
466
+ );
467
+ } else {
468
+ const existingDeclarationFileContent = await fsp.readFile(startDeclarationFilePath, "utf-8").catch((err) => {
469
+ if (err.code === "ENOENT") {
470
+ return "";
471
+ }
472
+ throw err;
473
+ });
474
+ await writeIfDifferent(
475
+ startDeclarationFilePath,
476
+ existingDeclarationFileContent,
477
+ startDeclarationFileContent,
478
+ {
479
+ beforeWrite: () => {
480
+ logger.log(`🟡 Updating tanstack-start.d.ts`);
481
+ }
482
+ }
483
+ );
484
+ }
485
+ if (routeTreeWriteResult && !checkLatest()) {
486
+ return;
487
+ }
488
+ }
489
+ function buildStartDeclarationFile({
490
+ serverRoutesRelativePath
491
+ }) {
492
+ return [`import '${serverRoutesRelativePath}'`].join("\n") + "\n";
493
+ }
494
+ function removeGroups(s) {
495
+ return s.replace(possiblyNestedRouteGroupPatternRegex, "");
496
+ }
497
+ function determineNodePath(node) {
498
+ var _a;
499
+ return node.path = node.parent ? ((_a = node.routePath) == null ? void 0 : _a.replace(node.parent.routePath ?? "", "")) || "/" : node.routePath;
500
+ }
501
+ function removeLastSegmentFromPath(routePath = "/") {
502
+ const segments = routePath.split("/");
503
+ segments.pop();
504
+ return segments.join("/");
505
+ }
506
+ function removeLayoutSegments(routePath = "/") {
507
+ const segments = routePath.split("/");
508
+ const newSegments = segments.filter((segment) => !segment.startsWith("_"));
509
+ return newSegments.join("/");
510
+ }
511
+ function hasParentRoute(routes, node, routePathToCheck) {
512
+ if (!routePathToCheck || routePathToCheck === "/") {
513
+ return null;
514
+ }
515
+ const sortedNodes = multiSortBy(routes, [
516
+ (d) => d.routePath.length * -1,
517
+ (d) => d.variableName
518
+ ]).filter((d) => d.routePath !== `/${rootPathId}`);
519
+ for (const route of sortedNodes) {
520
+ if (route.routePath === "/") continue;
521
+ if (routePathToCheck.startsWith(`${route.routePath}/`) && route.routePath !== routePathToCheck) {
522
+ return route;
523
+ }
524
+ }
525
+ const segments = routePathToCheck.split("/");
526
+ segments.pop();
527
+ const parentRoutePath = segments.join("/");
528
+ return hasParentRoute(routes, node, parentRoutePath);
529
+ }
530
+ const getResolvedRouteNodeVariableName = (routeNode) => {
531
+ var _a;
532
+ return ((_a = routeNode.children) == null ? void 0 : _a.length) ? `${routeNode.variableName}RouteWithChildren` : `${routeNode.variableName}Route`;
533
+ };
534
+ const createRouteNodesByFullPath = (routeNodes) => {
535
+ return new Map(
536
+ routeNodes.map((routeNode) => [inferFullPath(routeNode), routeNode])
537
+ );
538
+ };
539
+ const createRouteNodesByTo = (routeNodes) => {
540
+ return new Map(
541
+ dedupeBranchesAndIndexRoutes(routeNodes).map((routeNode) => [
542
+ inferTo(routeNode),
543
+ routeNode
544
+ ])
545
+ );
546
+ };
547
+ const createRouteNodesById = (routeNodes) => {
548
+ return new Map(
549
+ routeNodes.map((routeNode) => {
550
+ const id = routeNode.routePath ?? "";
551
+ return [id, routeNode];
552
+ })
553
+ );
554
+ };
555
+ const inferFullPath = (routeNode) => {
556
+ const fullPath = removeGroups(
557
+ removeUnderscores(removeLayoutSegments(routeNode.routePath)) ?? ""
558
+ );
559
+ return routeNode.cleanedPath === "/" ? fullPath : fullPath.replace(/\/$/, "");
560
+ };
561
+ const inferPath = (routeNode) => {
562
+ var _a;
563
+ return routeNode.cleanedPath === "/" ? routeNode.cleanedPath : ((_a = routeNode.cleanedPath) == null ? void 0 : _a.replace(/\/$/, "")) ?? "";
564
+ };
565
+ const inferTo = (routeNode) => {
566
+ const fullPath = inferFullPath(routeNode);
567
+ if (fullPath === "/") return fullPath;
568
+ return fullPath.replace(/\/$/, "");
569
+ };
570
+ const dedupeBranchesAndIndexRoutes = (routes) => {
571
+ return routes.filter((route) => {
572
+ var _a;
573
+ if ((_a = route.children) == null ? void 0 : _a.find((child) => child.cleanedPath === "/")) return false;
574
+ return true;
575
+ });
576
+ };
577
+ function checkUnique(routes, key) {
578
+ const keys = routes.map((d) => d[key]);
579
+ const uniqueKeys = new Set(keys);
580
+ if (keys.length !== uniqueKeys.size) {
581
+ const duplicateKeys = keys.filter((d, i) => keys.indexOf(d) !== i);
582
+ const conflictingFiles = routes.filter(
583
+ (d) => duplicateKeys.includes(d[key])
584
+ );
585
+ return conflictingFiles;
586
+ }
587
+ return void 0;
588
+ }
589
+ function checkRouteFullPathUniqueness(_routes, config) {
590
+ const routes = _routes.map((d) => {
591
+ const inferredFullPath = inferFullPath(d);
592
+ return { ...d, inferredFullPath };
593
+ });
594
+ const conflictingFiles = checkUnique(routes, "inferredFullPath");
595
+ if (conflictingFiles !== void 0) {
596
+ const errorMessage = `Conflicting configuration paths were found for the following route${conflictingFiles.length > 1 ? "s" : ""}: ${conflictingFiles.map((p) => `"${p.inferredFullPath}"`).join(", ")}.
597
+ Please ensure each Server Route has a unique full path.
598
+ Conflicting files:
599
+ ${conflictingFiles.map((d) => path.resolve(config.routesDirectory, d.filePath)).join("\n ")}
600
+ `;
601
+ console.error(errorMessage);
602
+ process.exit(1);
603
+ }
604
+ }
605
+ export {
606
+ TanStackStartServerRoutesVite
607
+ };
608
+ //# sourceMappingURL=plugin.js.map