@tanstack/router-generator 1.7.1 → 1.8.0

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.
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const path = require("path");
4
+ const fs = require("fs");
5
+ const zod = require("zod");
6
+ const configSchema = zod.z.object({
7
+ routeFilePrefix: zod.z.string().optional(),
8
+ routeFileIgnorePrefix: zod.z.string().optional().default("-"),
9
+ routesDirectory: zod.z.string().optional().default("./src/routes"),
10
+ generatedRouteTree: zod.z.string().optional().default("./src/routeTree.gen.ts"),
11
+ quoteStyle: zod.z.enum(["single", "double"]).optional().default("single"),
12
+ disableTypes: zod.z.boolean().optional().default(false)
13
+ });
14
+ const configFilePathJson = path.resolve(process.cwd(), "tsr.config.json");
15
+ async function getConfig() {
16
+ const exists = fs.existsSync(configFilePathJson);
17
+ let config;
18
+ if (exists) {
19
+ config = configSchema.parse(
20
+ JSON.parse(fs.readFileSync(configFilePathJson, "utf-8"))
21
+ );
22
+ } else {
23
+ config = configSchema.parse({});
24
+ }
25
+ if (config.disableTypes) {
26
+ config.generatedRouteTree = config.generatedRouteTree.replace(
27
+ /\.(ts|tsx)$/,
28
+ ".js"
29
+ );
30
+ }
31
+ return config;
32
+ }
33
+ exports.configSchema = configSchema;
34
+ exports.getConfig = getConfig;
35
+ //# sourceMappingURL=config.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.cjs","sources":["../../src/config.ts"],"sourcesContent":["import path from 'path'\nimport { readFileSync, existsSync } from 'fs'\nimport { z } from 'zod'\n\nexport const configSchema = z.object({\n routeFilePrefix: z.string().optional(),\n routeFileIgnorePrefix: z.string().optional().default('-'),\n routesDirectory: z.string().optional().default('./src/routes'),\n generatedRouteTree: z.string().optional().default('./src/routeTree.gen.ts'),\n quoteStyle: z.enum(['single', 'double']).optional().default('single'),\n disableTypes: z.boolean().optional().default(false),\n})\n\nexport type Config = z.infer<typeof configSchema>\n\nconst configFilePathJson = path.resolve(process.cwd(), 'tsr.config.json')\n\nexport async function getConfig(): Promise<Config> {\n const exists = existsSync(configFilePathJson)\n\n let config: Config\n\n if (exists) {\n config = configSchema.parse(\n JSON.parse(readFileSync(configFilePathJson, 'utf-8')),\n )\n } else {\n config = configSchema.parse({})\n }\n\n // If typescript is disabled, make sure the generated route tree is a .js file\n if (config.disableTypes) {\n config.generatedRouteTree = config.generatedRouteTree.replace(\n /\\.(ts|tsx)$/,\n '.js',\n )\n }\n\n return config\n}\n"],"names":["z","existsSync","readFileSync"],"mappings":";;;;;AAIa,MAAA,eAAeA,MAAE,OAAO;AAAA,EACnC,iBAAiBA,IAAA,EAAE,OAAO,EAAE,SAAS;AAAA,EACrC,uBAAuBA,IAAE,EAAA,OAAA,EAAS,SAAS,EAAE,QAAQ,GAAG;AAAA,EACxD,iBAAiBA,IAAE,EAAA,OAAA,EAAS,SAAS,EAAE,QAAQ,cAAc;AAAA,EAC7D,oBAAoBA,IAAE,EAAA,OAAA,EAAS,SAAS,EAAE,QAAQ,wBAAwB;AAAA,EAC1E,YAAYA,IAAAA,EAAE,KAAK,CAAC,UAAU,QAAQ,CAAC,EAAE,SAAA,EAAW,QAAQ,QAAQ;AAAA,EACpE,cAAcA,IAAE,EAAA,QAAA,EAAU,SAAS,EAAE,QAAQ,KAAK;AACpD,CAAC;AAID,MAAM,qBAAqB,KAAK,QAAQ,QAAQ,IAAA,GAAO,iBAAiB;AAExE,eAAsB,YAA6B;AAC3C,QAAA,SAASC,cAAW,kBAAkB;AAExC,MAAA;AAEJ,MAAI,QAAQ;AACV,aAAS,aAAa;AAAA,MACpB,KAAK,MAAMC,GAAAA,aAAa,oBAAoB,OAAO,CAAC;AAAA,IAAA;AAAA,EACtD,OACK;AACI,aAAA,aAAa,MAAM,CAAA,CAAE;AAAA,EAChC;AAGA,MAAI,OAAO,cAAc;AAChB,WAAA,qBAAqB,OAAO,mBAAmB;AAAA,MACpD;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAEO,SAAA;AACT;;;"}
@@ -1,16 +1,5 @@
1
- /**
2
- * @tanstack/router-generator/src/index.ts
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
1
  import { z } from 'zod';
12
-
13
- declare const configSchema: z.ZodObject<{
2
+ export declare const configSchema: z.ZodObject<{
14
3
  routeFilePrefix: z.ZodOptional<z.ZodString>;
15
4
  routeFileIgnorePrefix: z.ZodDefault<z.ZodOptional<z.ZodString>>;
16
5
  routesDirectory: z.ZodDefault<z.ZodOptional<z.ZodString>>;
@@ -32,9 +21,5 @@ declare const configSchema: z.ZodObject<{
32
21
  quoteStyle?: "single" | "double" | undefined;
33
22
  disableTypes?: boolean | undefined;
34
23
  }>;
35
- type Config = z.infer<typeof configSchema>;
36
- declare function getConfig(): Promise<Config>;
37
-
38
- declare function generator(config: Config): Promise<void>;
39
-
40
- export { type Config, configSchema, generator, getConfig };
24
+ export type Config = z.infer<typeof configSchema>;
25
+ export declare function getConfig(): Promise<Config>;
@@ -0,0 +1,417 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const path = require("path");
4
+ const fs = require("fs/promises");
5
+ const prettier = require("prettier");
6
+ const utils = require("./utils.cjs");
7
+ function _interopNamespaceDefault(e) {
8
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
9
+ if (e) {
10
+ for (const k in e) {
11
+ if (k !== "default") {
12
+ const d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: () => e[k]
16
+ });
17
+ }
18
+ }
19
+ }
20
+ n.default = e;
21
+ return Object.freeze(n);
22
+ }
23
+ const fs__namespace = /* @__PURE__ */ _interopNamespaceDefault(fs);
24
+ const prettier__namespace = /* @__PURE__ */ _interopNamespaceDefault(prettier);
25
+ let latestTask = 0;
26
+ const rootPathId = "__root";
27
+ async function getRouteNodes(config) {
28
+ const { routeFilePrefix, routeFileIgnorePrefix } = config;
29
+ let routeNodes = [];
30
+ async function recurse(dir) {
31
+ const fullDir = path.resolve(config.routesDirectory, dir);
32
+ let dirList = await fs__namespace.readdir(fullDir, { withFileTypes: true });
33
+ dirList = dirList.filter((d) => {
34
+ if (d.name.startsWith(".") || routeFileIgnorePrefix && d.name.startsWith(routeFileIgnorePrefix)) {
35
+ return false;
36
+ }
37
+ if (routeFilePrefix) {
38
+ return d.name.startsWith(routeFilePrefix);
39
+ }
40
+ return true;
41
+ });
42
+ await Promise.all(
43
+ dirList.map(async (dirent) => {
44
+ const fullPath = path.join(fullDir, dirent.name);
45
+ const relativePath = path.join(dir, dirent.name);
46
+ if (dirent.isDirectory()) {
47
+ await recurse(relativePath);
48
+ } else if (fullPath.match(/\.(tsx|ts|jsx|js)$/)) {
49
+ const filePath = replaceBackslash(path.join(dir, dirent.name));
50
+ const filePathNoExt = removeExt(filePath);
51
+ let routePath = utils.cleanPath(`/${filePathNoExt.split(".").join("/")}`) || "";
52
+ const variableName = routePathToVariable(routePath);
53
+ let isRoute = routePath == null ? void 0 : routePath.endsWith("/route");
54
+ let isComponent = routePath == null ? void 0 : routePath.endsWith("/component");
55
+ let isErrorComponent = routePath == null ? void 0 : routePath.endsWith("/errorComponent");
56
+ let isPendingComponent = routePath == null ? void 0 : routePath.endsWith("/pendingComponent");
57
+ let isLoader = routePath == null ? void 0 : routePath.endsWith("/loader");
58
+ routePath = routePath == null ? void 0 : routePath.replace(
59
+ /\/(component|errorComponent|pendingComponent|loader|route)$/,
60
+ ""
61
+ );
62
+ if (routePath === "index") {
63
+ routePath = "/";
64
+ }
65
+ routePath = routePath.replace(/\/index$/, "/") || "/";
66
+ routeNodes.push({
67
+ filePath,
68
+ fullPath,
69
+ routePath,
70
+ variableName,
71
+ isRoute,
72
+ isComponent,
73
+ isErrorComponent,
74
+ isPendingComponent,
75
+ isLoader
76
+ });
77
+ }
78
+ })
79
+ );
80
+ return routeNodes;
81
+ }
82
+ await recurse("./");
83
+ return routeNodes;
84
+ }
85
+ let first = false;
86
+ let skipMessage = false;
87
+ async function generator(config) {
88
+ console.log();
89
+ if (!first) {
90
+ console.log("🔄 Generating routes...");
91
+ first = true;
92
+ } else if (skipMessage) {
93
+ skipMessage = false;
94
+ } else {
95
+ console.log("♻️ Regenerating routes...");
96
+ }
97
+ const taskId = latestTask + 1;
98
+ latestTask = taskId;
99
+ const checkLatest = () => {
100
+ if (latestTask !== taskId) {
101
+ skipMessage = true;
102
+ return false;
103
+ }
104
+ return true;
105
+ };
106
+ const start = Date.now();
107
+ const routePathIdPrefix = config.routeFilePrefix ?? "";
108
+ const preRouteNodes = multiSortBy(await getRouteNodes(config), [
109
+ (d) => d.routePath === "/" ? -1 : 1,
110
+ (d) => {
111
+ var _a;
112
+ return (_a = d.routePath) == null ? void 0 : _a.split("/").length;
113
+ },
114
+ (d) => {
115
+ var _a;
116
+ return ((_a = d.filePath) == null ? void 0 : _a.match(/[./]index[.]/)) ? 1 : -1;
117
+ },
118
+ (d) => {
119
+ var _a;
120
+ return ((_a = d.filePath) == null ? void 0 : _a.match(
121
+ /[./](component|errorComponent|pendingComponent|loader)[.]/
122
+ )) ? 1 : -1;
123
+ },
124
+ (d) => {
125
+ var _a;
126
+ return ((_a = d.filePath) == null ? void 0 : _a.match(/[./]route[.]/)) ? -1 : 1;
127
+ },
128
+ (d) => {
129
+ var _a;
130
+ return ((_a = d.routePath) == null ? void 0 : _a.endsWith("/")) ? -1 : 1;
131
+ },
132
+ (d) => d.routePath
133
+ ]).filter(
134
+ (d) => ![`/${routePathIdPrefix + rootPathId}`].includes(d.routePath || "")
135
+ );
136
+ const routeTree = [];
137
+ const routePiecesByPath = {};
138
+ let routeNodes = [];
139
+ const handleNode = (node) => {
140
+ var _a;
141
+ const parentRoute = hasParentRoute(routeNodes, node.routePath);
142
+ if (parentRoute)
143
+ node.parent = parentRoute;
144
+ node.path = node.parent ? ((_a = node.routePath) == null ? void 0 : _a.replace(node.parent.routePath, "")) || "/" : node.routePath;
145
+ const trimmedPath = utils.trimPathLeft(node.path ?? "");
146
+ const split = (trimmedPath == null ? void 0 : trimmedPath.split("/")) ?? [];
147
+ let first2 = split[0] ?? trimmedPath ?? "";
148
+ node.isNonPath = first2.startsWith("_");
149
+ node.isNonLayout = first2.endsWith("_");
150
+ node.cleanedPath = removeUnderscores(node.path) ?? "";
151
+ if (!node.isVirtual && (node.isLoader || node.isComponent || node.isErrorComponent || node.isPendingComponent)) {
152
+ routePiecesByPath[node.routePath] = routePiecesByPath[node.routePath] || {};
153
+ routePiecesByPath[node.routePath][node.isLoader ? "loader" : node.isErrorComponent ? "errorComponent" : node.isPendingComponent ? "pendingComponent" : "component"] = node;
154
+ const anchorRoute = routeNodes.find((d) => d.routePath === node.routePath);
155
+ if (!anchorRoute) {
156
+ handleNode({
157
+ ...node,
158
+ isVirtual: true,
159
+ isLoader: false,
160
+ isComponent: false,
161
+ isErrorComponent: false,
162
+ isPendingComponent: false
163
+ });
164
+ }
165
+ return;
166
+ }
167
+ if (node.parent) {
168
+ node.parent.children = node.parent.children ?? [];
169
+ node.parent.children.push(node);
170
+ } else {
171
+ routeTree.push(node);
172
+ }
173
+ routeNodes.push(node);
174
+ };
175
+ preRouteNodes.forEach((node) => handleNode(node));
176
+ async function buildRouteConfig(nodes, depth = 1) {
177
+ const children = nodes.map(async (node) => {
178
+ var _a, _b;
179
+ const routeCode = await fs__namespace.readFile(node.fullPath, "utf-8");
180
+ if (node.isRoot) {
181
+ return;
182
+ }
183
+ const escapedRoutePath = removeTrailingUnderscores(
184
+ ((_a = node.routePath) == null ? void 0 : _a.replaceAll("$", "$$")) ?? ""
185
+ );
186
+ config.quoteStyle === "single" ? `'` : `"`;
187
+ const replaced = routeCode.replace(
188
+ /(FileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
189
+ (match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`
190
+ );
191
+ if (replaced !== routeCode) {
192
+ await fs__namespace.writeFile(node.fullPath, replaced);
193
+ }
194
+ const route = `${node.variableName}Route`;
195
+ if ((_b = node.children) == null ? void 0 : _b.length) {
196
+ const childConfigs = await buildRouteConfig(node.children, depth + 1);
197
+ return `${route}.addChildren([${spaces(depth * 4)}${childConfigs}])`;
198
+ }
199
+ return route;
200
+ });
201
+ return (await Promise.all(children)).filter(Boolean).join(`,`);
202
+ }
203
+ const routeConfigChildrenText = await buildRouteConfig(routeTree);
204
+ const sortedRouteNodes = multiSortBy(routeNodes, [
205
+ (d) => {
206
+ var _a;
207
+ return ((_a = d.routePath) == null ? void 0 : _a.includes(`/${routePathIdPrefix + rootPathId}`)) ? -1 : 1;
208
+ },
209
+ (d) => {
210
+ var _a;
211
+ return (_a = d.routePath) == null ? void 0 : _a.split("/").length;
212
+ },
213
+ (d) => {
214
+ var _a;
215
+ return ((_a = d.routePath) == null ? void 0 : _a.endsWith("index'")) ? -1 : 1;
216
+ },
217
+ (d) => d
218
+ ]);
219
+ const imports = Object.entries({
220
+ FileRoute: sortedRouteNodes.some((d) => d.isVirtual),
221
+ lazyFn: sortedRouteNodes.some(
222
+ (node) => {
223
+ var _a;
224
+ return (_a = routePiecesByPath[node.routePath]) == null ? void 0 : _a.loader;
225
+ }
226
+ ),
227
+ lazyRouteComponent: sortedRouteNodes.some(
228
+ (node) => {
229
+ var _a, _b, _c;
230
+ return ((_a = routePiecesByPath[node.routePath]) == null ? void 0 : _a.component) || ((_b = routePiecesByPath[node.routePath]) == null ? void 0 : _b.errorComponent) || ((_c = routePiecesByPath[node.routePath]) == null ? void 0 : _c.pendingComponent);
231
+ }
232
+ )
233
+ }).filter((d) => d[1]).map((d) => d[0]);
234
+ const virtualRouteNodes = sortedRouteNodes.filter((d) => d.isVirtual);
235
+ const routeImports = [
236
+ "// This file is auto-generated by TanStack Router",
237
+ imports.length ? `import { ${imports.join(", ")} } from '@tanstack/react-router'
238
+ ` : "",
239
+ "// Import Routes",
240
+ [
241
+ `import { Route as rootRoute } from './${replaceBackslash(
242
+ path.relative(
243
+ path.dirname(config.generatedRouteTree),
244
+ path.resolve(config.routesDirectory, routePathIdPrefix + rootPathId)
245
+ )
246
+ )}'`,
247
+ ...sortedRouteNodes.filter((d) => !d.isVirtual).map((node) => {
248
+ return `import { Route as ${node.variableName}Import } from './${replaceBackslash(
249
+ removeExt(
250
+ path.relative(
251
+ path.dirname(config.generatedRouteTree),
252
+ path.resolve(config.routesDirectory, node.filePath)
253
+ )
254
+ )
255
+ )}'`;
256
+ })
257
+ ].join("\n"),
258
+ virtualRouteNodes.length ? "// Create Virtual Routes" : "",
259
+ virtualRouteNodes.map((node) => {
260
+ return `const ${node.variableName}Import = new FileRoute('${removeTrailingUnderscores(
261
+ node.routePath
262
+ )}').createRoute()`;
263
+ }).join("\n"),
264
+ "// Create/Update Routes",
265
+ sortedRouteNodes.map((node) => {
266
+ var _a, _b, _c, _d, _e;
267
+ const loaderNode = (_a = routePiecesByPath[node.routePath]) == null ? void 0 : _a.loader;
268
+ const componentNode = (_b = routePiecesByPath[node.routePath]) == null ? void 0 : _b.component;
269
+ const errorComponentNode = (_c = routePiecesByPath[node.routePath]) == null ? void 0 : _c.errorComponent;
270
+ const pendingComponentNode = (_d = routePiecesByPath[node.routePath]) == null ? void 0 : _d.pendingComponent;
271
+ return [
272
+ `const ${node.variableName}Route = ${node.variableName}Import.update({
273
+ ${[
274
+ node.isNonPath ? `id: '${node.path}'` : `path: '${node.cleanedPath}'`,
275
+ `getParentRoute: () => ${((_e = node.parent) == null ? void 0 : _e.variableName) ?? "root"}Route`
276
+ ].filter(Boolean).join(",")}
277
+ }${config.disableTypes ? "" : "as any"})`,
278
+ loaderNode ? `.updateLoader({ loader: lazyFn(() => import('./${replaceBackslash(
279
+ removeExt(
280
+ path.relative(
281
+ path.dirname(config.generatedRouteTree),
282
+ path.resolve(config.routesDirectory, loaderNode.filePath)
283
+ )
284
+ )
285
+ )}'), 'loader') })` : "",
286
+ componentNode || errorComponentNode || pendingComponentNode ? `.update({
287
+ ${[
288
+ ["component", componentNode],
289
+ ["errorComponent", errorComponentNode],
290
+ ["pendingComponent", pendingComponentNode]
291
+ ].filter((d) => d[1]).map((d) => {
292
+ return `${d[0]}: lazyRouteComponent(() => import('./${replaceBackslash(
293
+ removeExt(
294
+ path.relative(
295
+ path.dirname(config.generatedRouteTree),
296
+ path.resolve(config.routesDirectory, d[1].filePath)
297
+ )
298
+ )
299
+ )}'), '${d[0]}')`;
300
+ }).join("\n,")}
301
+ })` : ""
302
+ ].join("");
303
+ }).join("\n\n"),
304
+ ...config.disableTypes ? [] : [
305
+ "// Populate the FileRoutesByPath interface",
306
+ `declare module '@tanstack/react-router' {
307
+ interface FileRoutesByPath {
308
+ ${routeNodes.map((routeNode) => {
309
+ var _a, _b;
310
+ return `'${removeTrailingUnderscores(routeNode.routePath)}': {
311
+ preLoaderRoute: typeof ${routeNode.variableName}Import
312
+ parentRoute: typeof ${((_a = routeNode.parent) == null ? void 0 : _a.variableName) ? `${(_b = routeNode.parent) == null ? void 0 : _b.variableName}Import` : "rootRoute"}
313
+ }`;
314
+ }).join("\n")}
315
+ }
316
+ }`
317
+ ],
318
+ "// Create and export the route tree",
319
+ `export const routeTree = rootRoute.addChildren([${routeConfigChildrenText}])`
320
+ ].filter(Boolean).join("\n\n");
321
+ const routeConfigFileContent = await prettier__namespace.format(routeImports, {
322
+ semi: false,
323
+ singleQuote: config.quoteStyle === "single",
324
+ parser: "typescript"
325
+ });
326
+ const routeTreeContent = await fs__namespace.readFile(path.resolve(config.generatedRouteTree), "utf-8").catch((err) => {
327
+ if (err.code === "ENOENT") {
328
+ return void 0;
329
+ }
330
+ throw err;
331
+ });
332
+ if (!checkLatest())
333
+ return;
334
+ if (routeTreeContent !== routeConfigFileContent) {
335
+ await fs__namespace.mkdir(path.dirname(path.resolve(config.generatedRouteTree)), {
336
+ recursive: true
337
+ });
338
+ if (!checkLatest())
339
+ return;
340
+ await fs__namespace.writeFile(
341
+ path.resolve(config.generatedRouteTree),
342
+ routeConfigFileContent
343
+ );
344
+ }
345
+ console.log(
346
+ `🌲 Processed ${routeNodes.length} routes in ${Date.now() - start}ms`
347
+ );
348
+ }
349
+ function routePathToVariable(d) {
350
+ var _a, _b, _c, _d;
351
+ return ((_d = (_c = (_b = (_a = removeUnderscores(d)) == null ? void 0 : _a.replace(/\/\$\//g, "/splat/")) == null ? void 0 : _b.replace(/\$$/g, "splat")) == null ? void 0 : _c.replace(/\$/g, "")) == null ? void 0 : _d.split(/[/-]/g).map((d2, i) => i > 0 ? capitalize(d2) : d2).join("").replace(/([^a-zA-Z0-9]|[\.])/gm, "")) ?? "";
352
+ }
353
+ function removeExt(d) {
354
+ return d.substring(0, d.lastIndexOf(".")) || d;
355
+ }
356
+ function spaces(d) {
357
+ return Array.from({ length: d }).map(() => " ").join("");
358
+ }
359
+ function multiSortBy(arr, accessors = [(d) => d]) {
360
+ return arr.map((d, i) => [d, i]).sort(([a, ai], [b, bi]) => {
361
+ for (const accessor of accessors) {
362
+ const ao = accessor(a);
363
+ const bo = accessor(b);
364
+ if (typeof ao === "undefined") {
365
+ if (typeof bo === "undefined") {
366
+ continue;
367
+ }
368
+ return 1;
369
+ }
370
+ if (ao === bo) {
371
+ continue;
372
+ }
373
+ return ao > bo ? 1 : -1;
374
+ }
375
+ return ai - bi;
376
+ }).map(([d]) => d);
377
+ }
378
+ function capitalize(s) {
379
+ if (typeof s !== "string")
380
+ return "";
381
+ return s.charAt(0).toUpperCase() + s.slice(1);
382
+ }
383
+ function removeUnderscores(s) {
384
+ return s == null ? void 0 : s.replace(/(^_|_$)/, "").replace(/(\/_|_\/)/, "/");
385
+ }
386
+ function removeTrailingUnderscores(s) {
387
+ return s == null ? void 0 : s.replace(/(_$)/, "").replace(/(_\/)/, "/");
388
+ }
389
+ function replaceBackslash(s) {
390
+ return s.replace(/\\/gi, "/");
391
+ }
392
+ function hasParentRoute(routes, routePathToCheck) {
393
+ if (!routePathToCheck || routePathToCheck === "/") {
394
+ return null;
395
+ }
396
+ const sortedNodes = multiSortBy(routes, [
397
+ (d) => d.routePath.length * -1,
398
+ (d) => d.variableName
399
+ ]).filter((d) => d.routePath !== `/${rootPathId}`);
400
+ for (const route of sortedNodes) {
401
+ if (route.routePath === "/")
402
+ continue;
403
+ if (routePathToCheck.startsWith(`${route.routePath}/`) && route.routePath !== routePathToCheck) {
404
+ return route;
405
+ }
406
+ }
407
+ const segments = routePathToCheck.split("/");
408
+ segments.pop();
409
+ const parentRoutePath = segments.join("/");
410
+ return hasParentRoute(routes, parentRoutePath);
411
+ }
412
+ exports.generator = generator;
413
+ exports.hasParentRoute = hasParentRoute;
414
+ exports.multiSortBy = multiSortBy;
415
+ exports.removeExt = removeExt;
416
+ exports.rootPathId = rootPathId;
417
+ //# sourceMappingURL=generator.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.cjs","sources":["../../src/generator.ts"],"sourcesContent":["import path from 'path'\nimport * as fs from 'fs/promises'\nimport * as prettier from 'prettier'\nimport { Config } from './config'\nimport { cleanPath, trimPathLeft } from './utils'\n\nlet latestTask = 0\nexport const rootPathId = '__root'\n\nexport type RouteNode = {\n filePath: string\n fullPath: string\n variableName: string\n routePath?: string\n cleanedPath?: string\n path?: string\n isNonPath?: boolean\n isNonLayout?: boolean\n isRoute?: boolean\n isLoader?: boolean\n isComponent?: boolean\n isErrorComponent?: boolean\n isPendingComponent?: boolean\n isVirtual?: boolean\n isRoot?: boolean\n children?: RouteNode[]\n parent?: RouteNode\n}\n\nasync function getRouteNodes(config: Config) {\n const { routeFilePrefix, routeFileIgnorePrefix } = config\n\n let routeNodes: RouteNode[] = []\n\n async function recurse(dir: string) {\n const fullDir = path.resolve(config.routesDirectory, dir)\n let dirList = await fs.readdir(fullDir, { withFileTypes: true })\n\n dirList = dirList.filter((d) => {\n if (\n d.name.startsWith('.') ||\n (routeFileIgnorePrefix && d.name.startsWith(routeFileIgnorePrefix))\n ) {\n return false\n }\n\n if (routeFilePrefix) {\n return d.name.startsWith(routeFilePrefix)\n }\n\n return true\n })\n\n await Promise.all(\n dirList.map(async (dirent) => {\n const fullPath = path.join(fullDir, dirent.name)\n const relativePath = path.join(dir, dirent.name)\n\n if (dirent.isDirectory()) {\n await recurse(relativePath)\n } else if (fullPath.match(/\\.(tsx|ts|jsx|js)$/)) {\n const filePath = replaceBackslash(path.join(dir, dirent.name))\n const filePathNoExt = removeExt(filePath)\n let routePath =\n cleanPath(`/${filePathNoExt.split('.').join('/')}`) || ''\n const variableName = routePathToVariable(routePath)\n\n // Remove the index from the route path and\n // if the route path is empty, use `/'\n\n let isRoute = routePath?.endsWith('/route')\n let isComponent = routePath?.endsWith('/component')\n let isErrorComponent = routePath?.endsWith('/errorComponent')\n let isPendingComponent = routePath?.endsWith('/pendingComponent')\n let isLoader = routePath?.endsWith('/loader')\n\n routePath = routePath?.replace(\n /\\/(component|errorComponent|pendingComponent|loader|route)$/,\n '',\n )\n\n if (routePath === 'index') {\n routePath = '/'\n }\n\n routePath = routePath.replace(/\\/index$/, '/') || '/'\n\n routeNodes.push({\n filePath,\n fullPath,\n routePath,\n variableName,\n isRoute,\n isComponent,\n isErrorComponent,\n isPendingComponent,\n isLoader,\n })\n }\n }),\n )\n\n return routeNodes\n }\n\n await recurse('./')\n\n return routeNodes\n}\n\nlet first = false\nlet skipMessage = false\n\ntype RouteSubNode = {\n component?: RouteNode\n errorComponent?: RouteNode\n pendingComponent?: RouteNode\n loader?: RouteNode\n}\n\nexport async function generator(config: Config) {\n console.log()\n\n if (!first) {\n console.log('🔄 Generating routes...')\n first = true\n } else if (skipMessage) {\n skipMessage = false\n } else {\n console.log('♻️ Regenerating routes...')\n }\n\n const taskId = latestTask + 1\n latestTask = taskId\n\n const checkLatest = () => {\n if (latestTask !== taskId) {\n skipMessage = true\n return false\n }\n\n return true\n }\n\n const start = Date.now()\n const routePathIdPrefix = config.routeFilePrefix ?? ''\n\n const preRouteNodes = multiSortBy(await getRouteNodes(config), [\n (d) => (d.routePath === '/' ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) => (d.filePath?.match(/[./]index[.]/) ? 1 : -1),\n (d) =>\n d.filePath?.match(\n /[./](component|errorComponent|pendingComponent|loader)[.]/,\n )\n ? 1\n : -1,\n (d) => (d.filePath?.match(/[./]route[.]/) ? -1 : 1),\n (d) => (d.routePath?.endsWith('/') ? -1 : 1),\n (d) => d.routePath,\n ]).filter(\n (d) => ![`/${routePathIdPrefix + rootPathId}`].includes(d.routePath || ''),\n )\n\n const routeTree: RouteNode[] = []\n const routePiecesByPath: Record<string, RouteSubNode> = {}\n\n // Loop over the flat list of routeNodes and\n // build up a tree based on the routeNodes' routePath\n let routeNodes: RouteNode[] = []\n\n const handleNode = (node: RouteNode) => {\n const parentRoute = hasParentRoute(routeNodes, node.routePath)\n if (parentRoute) node.parent = parentRoute\n\n node.path = node.parent\n ? node.routePath?.replace(node.parent.routePath!, '') || '/'\n : node.routePath\n\n const trimmedPath = trimPathLeft(node.path ?? '')\n\n const split = trimmedPath?.split('/') ?? []\n let first = split[0] ?? trimmedPath ?? ''\n\n node.isNonPath = first.startsWith('_')\n node.isNonLayout = first.endsWith('_')\n\n node.cleanedPath = removeUnderscores(node.path) ?? ''\n\n if (\n !node.isVirtual &&\n (node.isLoader ||\n node.isComponent ||\n node.isErrorComponent ||\n node.isPendingComponent)\n ) {\n routePiecesByPath[node.routePath!] =\n routePiecesByPath[node.routePath!] || {}\n\n routePiecesByPath[node.routePath!]![\n node.isLoader\n ? 'loader'\n : node.isErrorComponent\n ? 'errorComponent'\n : node.isPendingComponent\n ? 'pendingComponent'\n : 'component'\n ] = node\n\n const anchorRoute = routeNodes.find((d) => d.routePath === node.routePath)\n\n if (!anchorRoute) {\n handleNode({\n ...node,\n isVirtual: true,\n isLoader: false,\n isComponent: false,\n isErrorComponent: false,\n isPendingComponent: false,\n })\n }\n return\n }\n\n if (node.parent) {\n node.parent.children = node.parent.children ?? []\n node.parent.children.push(node)\n } else {\n routeTree.push(node)\n }\n\n routeNodes.push(node)\n }\n\n preRouteNodes.forEach((node) => handleNode(node))\n\n async function buildRouteConfig(\n nodes: RouteNode[],\n depth = 1,\n ): Promise<string> {\n const children = nodes.map(async (node) => {\n const routeCode = await fs.readFile(node.fullPath, 'utf-8')\n\n // Ensure the boilerplate for the route exists\n if (node.isRoot) {\n return\n }\n\n // Ensure that new FileRoute(anything?) is replaced with FileRoute(${node.routePath})\n // routePath can contain $ characters, which have special meaning when used in replace\n // so we have to escape it by turning all $ into $$. But since we do it through a replace call\n // we have to double escape it into $$$$. For more information, see\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement\n const escapedRoutePath = removeTrailingUnderscores(\n node.routePath?.replaceAll('$', '$$') ?? '',\n )\n const quote = config.quoteStyle === 'single' ? `'` : `\"`\n const replaced = routeCode.replace(\n /(FileRoute\\(\\s*['\"])([^\\s]+)(['\"](?:,?)\\s*\\))/g,\n (match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,\n )\n\n if (replaced !== routeCode) {\n await fs.writeFile(node.fullPath, replaced)\n }\n\n const route = `${node.variableName}Route`\n\n if (node.children?.length) {\n const childConfigs = await buildRouteConfig(node.children, depth + 1)\n return `${route}.addChildren([${spaces(depth * 4)}${childConfigs}])`\n }\n\n return route\n })\n\n return (await Promise.all(children)).filter(Boolean).join(`,`)\n }\n\n const routeConfigChildrenText = await buildRouteConfig(routeTree)\n\n const sortedRouteNodes = multiSortBy(routeNodes, [\n (d) =>\n d.routePath?.includes(`/${routePathIdPrefix + rootPathId}`) ? -1 : 1,\n (d) => d.routePath?.split('/').length,\n (d) => (d.routePath?.endsWith(\"index'\") ? -1 : 1),\n (d) => d,\n ])\n\n const imports = Object.entries({\n FileRoute: sortedRouteNodes.some((d) => d.isVirtual),\n lazyFn: sortedRouteNodes.some(\n (node) => routePiecesByPath[node.routePath!]?.loader,\n ),\n lazyRouteComponent: sortedRouteNodes.some(\n (node) =>\n routePiecesByPath[node.routePath!]?.component ||\n routePiecesByPath[node.routePath!]?.errorComponent ||\n routePiecesByPath[node.routePath!]?.pendingComponent,\n ),\n })\n .filter((d) => d[1])\n .map((d) => d[0])\n\n const virtualRouteNodes = sortedRouteNodes.filter((d) => d.isVirtual)\n\n const routeImports = [\n '// This file is auto-generated by TanStack Router',\n imports.length\n ? `import { ${imports.join(', ')} } from '@tanstack/react-router'\\n`\n : '',\n '// Import Routes',\n [\n `import { Route as rootRoute } from './${replaceBackslash(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, routePathIdPrefix + rootPathId),\n ),\n )}'`,\n ...sortedRouteNodes\n .filter((d) => !d.isVirtual)\n .map((node) => {\n return `import { Route as ${\n node.variableName\n }Import } from './${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, node.filePath),\n ),\n ),\n )}'`\n }),\n ].join('\\n'),\n virtualRouteNodes.length ? '// Create Virtual Routes' : '',\n virtualRouteNodes\n .map((node) => {\n return `const ${\n node.variableName\n }Import = new FileRoute('${removeTrailingUnderscores(\n node.routePath,\n )}').createRoute()`\n })\n .join('\\n'),\n '// Create/Update Routes',\n sortedRouteNodes\n .map((node) => {\n const loaderNode = routePiecesByPath[node.routePath!]?.loader\n const componentNode = routePiecesByPath[node.routePath!]?.component\n const errorComponentNode =\n routePiecesByPath[node.routePath!]?.errorComponent\n const pendingComponentNode =\n routePiecesByPath[node.routePath!]?.pendingComponent\n\n return [\n `const ${node.variableName}Route = ${node.variableName}Import.update({\n ${[\n node.isNonPath\n ? `id: '${node.path}'`\n : `path: '${node.cleanedPath}'`,\n `getParentRoute: () => ${node.parent?.variableName ?? 'root'}Route`,\n ]\n .filter(Boolean)\n .join(',')}\n }${config.disableTypes ? '' : 'as any'})`,\n loaderNode\n ? `.updateLoader({ loader: lazyFn(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, loaderNode.filePath),\n ),\n ),\n )}'), 'loader') })`\n : '',\n componentNode || errorComponentNode || pendingComponentNode\n ? `.update({\n ${(\n [\n ['component', componentNode],\n ['errorComponent', errorComponentNode],\n ['pendingComponent', pendingComponentNode],\n ] as const\n )\n .filter((d) => d[1])\n .map((d) => {\n return `${\n d[0]\n }: lazyRouteComponent(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, d[1]!.filePath),\n ),\n ),\n )}'), '${d[0]}')`\n })\n .join('\\n,')}\n })`\n : '',\n ].join('')\n })\n .join('\\n\\n'),\n ...(config.disableTypes\n ? []\n : [\n '// Populate the FileRoutesByPath interface',\n `declare module '@tanstack/react-router' {\n interface FileRoutesByPath {\n ${routeNodes\n .map((routeNode) => {\n return `'${removeTrailingUnderscores(routeNode.routePath)}': {\n preLoaderRoute: typeof ${routeNode.variableName}Import\n parentRoute: typeof ${\n routeNode.parent?.variableName\n ? `${routeNode.parent?.variableName}Import`\n : 'rootRoute'\n }\n }`\n })\n .join('\\n')}\n }\n}`,\n ]),\n '// Create and export the route tree',\n `export const routeTree = rootRoute.addChildren([${routeConfigChildrenText}])`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n const routeConfigFileContent = await prettier.format(routeImports, {\n semi: false,\n singleQuote: config.quoteStyle === 'single',\n parser: 'typescript',\n })\n\n const routeTreeContent = await fs\n .readFile(path.resolve(config.generatedRouteTree), 'utf-8')\n .catch((err: any) => {\n if (err.code === 'ENOENT') {\n return undefined\n }\n throw err\n })\n\n if (!checkLatest()) return\n\n if (routeTreeContent !== routeConfigFileContent) {\n await fs.mkdir(path.dirname(path.resolve(config.generatedRouteTree)), {\n recursive: true,\n })\n if (!checkLatest()) return\n await fs.writeFile(\n path.resolve(config.generatedRouteTree),\n routeConfigFileContent,\n )\n }\n\n console.log(\n `🌲 Processed ${routeNodes.length} routes in ${Date.now() - start}ms`,\n )\n}\n\nfunction routePathToVariable(d: string): string {\n return (\n removeUnderscores(d)\n ?.replace(/\\/\\$\\//g, '/splat/')\n ?.replace(/\\$$/g, 'splat')\n ?.replace(/\\$/g, '')\n ?.split(/[/-]/g)\n .map((d, i) => (i > 0 ? capitalize(d) : d))\n .join('')\n .replace(/([^a-zA-Z0-9]|[\\.])/gm, '') ?? ''\n )\n}\n\nexport function removeExt(d: string) {\n return d.substring(0, d.lastIndexOf('.')) || d\n}\n\nfunction spaces(d: number): string {\n return Array.from({ length: d })\n .map(() => ' ')\n .join('')\n}\n\nexport function multiSortBy<T>(\n arr: T[],\n accessors: ((item: T) => any)[] = [(d) => d],\n): T[] {\n return arr\n .map((d, i) => [d, i] as const)\n .sort(([a, ai], [b, bi]) => {\n for (const accessor of accessors) {\n const ao = accessor(a)\n const bo = accessor(b)\n\n if (typeof ao === 'undefined') {\n if (typeof bo === 'undefined') {\n continue\n }\n return 1\n }\n\n if (ao === bo) {\n continue\n }\n\n return ao > bo ? 1 : -1\n }\n\n return ai - bi\n })\n .map(([d]) => d)\n}\n\nfunction capitalize(s: string) {\n if (typeof s !== 'string') return ''\n return s.charAt(0).toUpperCase() + s.slice(1)\n}\n\nfunction removeUnderscores(s?: string) {\n return s?.replace(/(^_|_$)/, '').replace(/(\\/_|_\\/)/, '/')\n}\n\nfunction removeTrailingUnderscores(s?: string) {\n return s?.replace(/(_$)/, '').replace(/(_\\/)/, '/')\n}\n\nfunction replaceBackslash(s: string) {\n return s.replace(/\\\\/gi, '/')\n}\n\nexport function hasParentRoute(\n routes: RouteNode[],\n routePathToCheck: string | undefined,\n): RouteNode | null {\n if (!routePathToCheck || routePathToCheck === '/') {\n return null\n }\n\n const sortedNodes = multiSortBy(routes, [\n (d) => d.routePath!.length * -1,\n (d) => d.variableName,\n ]).filter((d) => d.routePath !== `/${rootPathId}`)\n\n for (const route of sortedNodes) {\n if (route.routePath === '/') continue\n\n if (\n routePathToCheck.startsWith(`${route.routePath}/`) &&\n route.routePath !== routePathToCheck\n ) {\n return route\n }\n }\n const segments = routePathToCheck.split('/')\n segments.pop() // Remove the last segment\n const parentRoutePath = segments.join('/')\n\n return hasParentRoute(routes, parentRoutePath)\n}\n"],"names":["fs","cleanPath","trimPathLeft","first","prettier","d"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAI,aAAa;AACV,MAAM,aAAa;AAsB1B,eAAe,cAAc,QAAgB;AACrC,QAAA,EAAE,iBAAiB,sBAA0B,IAAA;AAEnD,MAAI,aAA0B,CAAA;AAE9B,iBAAe,QAAQ,KAAa;AAClC,UAAM,UAAU,KAAK,QAAQ,OAAO,iBAAiB,GAAG;AACpD,QAAA,UAAU,MAAMA,cAAG,QAAQ,SAAS,EAAE,eAAe,MAAM;AAErD,cAAA,QAAQ,OAAO,CAAC,MAAM;AAE5B,UAAA,EAAE,KAAK,WAAW,GAAG,KACpB,yBAAyB,EAAE,KAAK,WAAW,qBAAqB,GACjE;AACO,eAAA;AAAA,MACT;AAEA,UAAI,iBAAiB;AACZ,eAAA,EAAE,KAAK,WAAW,eAAe;AAAA,MAC1C;AAEO,aAAA;AAAA,IAAA,CACR;AAED,UAAM,QAAQ;AAAA,MACZ,QAAQ,IAAI,OAAO,WAAW;AAC5B,cAAM,WAAW,KAAK,KAAK,SAAS,OAAO,IAAI;AAC/C,cAAM,eAAe,KAAK,KAAK,KAAK,OAAO,IAAI;AAE3C,YAAA,OAAO,eAAe;AACxB,gBAAM,QAAQ,YAAY;AAAA,QACjB,WAAA,SAAS,MAAM,oBAAoB,GAAG;AAC/C,gBAAM,WAAW,iBAAiB,KAAK,KAAK,KAAK,OAAO,IAAI,CAAC;AACvD,gBAAA,gBAAgB,UAAU,QAAQ;AACpC,cAAA,YACFC,MAAU,UAAA,IAAI,cAAc,MAAM,GAAG,EAAE,KAAK,GAAG,CAAC,EAAE,KAAK;AACnD,gBAAA,eAAe,oBAAoB,SA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@@ -0,0 +1,25 @@
1
+ import { Config } from './config';
2
+ export declare const rootPathId = "__root";
3
+ export type RouteNode = {
4
+ filePath: string;
5
+ fullPath: string;
6
+ variableName: string;
7
+ routePath?: string;
8
+ cleanedPath?: string;
9
+ path?: string;
10
+ isNonPath?: boolean;
11
+ isNonLayout?: boolean;
12
+ isRoute?: boolean;
13
+ isLoader?: boolean;
14
+ isComponent?: boolean;
15
+ isErrorComponent?: boolean;
16
+ isPendingComponent?: boolean;
17
+ isVirtual?: boolean;
18
+ isRoot?: boolean;
19
+ children?: RouteNode[];
20
+ parent?: RouteNode;
21
+ };
22
+ export declare function generator(config: Config): Promise<void>;
23
+ export declare function removeExt(d: string): string;
24
+ export declare function multiSortBy<T>(arr: T[], accessors?: ((item: T) => any)[]): T[];
25
+ export declare function hasParentRoute(routes: RouteNode[], routePathToCheck: string | undefined): RouteNode | null;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const config = require("./config.cjs");
4
+ const generator = require("./generator.cjs");
5
+ exports.configSchema = config.configSchema;
6
+ exports.getConfig = config.getConfig;
7
+ exports.generator = generator.generator;
8
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
@@ -0,0 +1,2 @@
1
+ export { type Config, configSchema, getConfig } from './config';
2
+ export { generator } from './generator';
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ function cleanPath(path) {
4
+ return path.replace(/\/{2,}/g, "/");
5
+ }
6
+ function trimPathLeft(path) {
7
+ return path === "/" ? path : path.replace(/^\/{1,}/, "");
8
+ }
9
+ exports.cleanPath = cleanPath;
10
+ exports.trimPathLeft = trimPathLeft;
11
+ //# sourceMappingURL=utils.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["export function cleanPath(path: string) {\n // remove double slashes\n return path.replace(/\\/{2,}/g, '/')\n}\n\nexport function trimPathLeft(path: string) {\n return path === '/' ? path : path.replace(/^\\/{1,}/, '')\n}\n"],"names":[],"mappings":";;AAAO,SAAS,UAAU,MAAc;AAE/B,SAAA,KAAK,QAAQ,WAAW,GAAG;AACpC;AAEO,SAAS,aAAa,MAAc;AACzC,SAAO,SAAS,MAAM,OAAO,KAAK,QAAQ,WAAW,EAAE;AACzD;;;"}
@@ -0,0 +1,2 @@
1
+ export declare function cleanPath(path: string): string;
2
+ export declare function trimPathLeft(path: string): string;
@@ -0,0 +1,25 @@
1
+ import { z } from 'zod';
2
+ export declare const configSchema: z.ZodObject<{
3
+ routeFilePrefix: z.ZodOptional<z.ZodString>;
4
+ routeFileIgnorePrefix: z.ZodDefault<z.ZodOptional<z.ZodString>>;
5
+ routesDirectory: z.ZodDefault<z.ZodOptional<z.ZodString>>;
6
+ generatedRouteTree: z.ZodDefault<z.ZodOptional<z.ZodString>>;
7
+ quoteStyle: z.ZodDefault<z.ZodOptional<z.ZodEnum<["single", "double"]>>>;
8
+ disableTypes: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
9
+ }, "strip", z.ZodTypeAny, {
10
+ routeFileIgnorePrefix: string;
11
+ routesDirectory: string;
12
+ generatedRouteTree: string;
13
+ quoteStyle: "single" | "double";
14
+ disableTypes: boolean;
15
+ routeFilePrefix?: string | undefined;
16
+ }, {
17
+ routeFilePrefix?: string | undefined;
18
+ routeFileIgnorePrefix?: string | undefined;
19
+ routesDirectory?: string | undefined;
20
+ generatedRouteTree?: string | undefined;
21
+ quoteStyle?: "single" | "double" | undefined;
22
+ disableTypes?: boolean | undefined;
23
+ }>;
24
+ export type Config = z.infer<typeof configSchema>;
25
+ export declare function getConfig(): Promise<Config>;