@benjavicente/router-generator 1.166.24

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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/_virtual/_rolldown/runtime.cjs +23 -0
  3. package/dist/cjs/config.cjs +134 -0
  4. package/dist/cjs/config.cjs.map +1 -0
  5. package/dist/cjs/config.d.cts +254 -0
  6. package/dist/cjs/filesystem/physical/getRouteNodes.cjs +234 -0
  7. package/dist/cjs/filesystem/physical/getRouteNodes.cjs.map +1 -0
  8. package/dist/cjs/filesystem/physical/getRouteNodes.d.cts +25 -0
  9. package/dist/cjs/filesystem/physical/rootPathId.cjs +6 -0
  10. package/dist/cjs/filesystem/physical/rootPathId.cjs.map +1 -0
  11. package/dist/cjs/filesystem/physical/rootPathId.d.cts +1 -0
  12. package/dist/cjs/filesystem/virtual/config.cjs +39 -0
  13. package/dist/cjs/filesystem/virtual/config.cjs.map +1 -0
  14. package/dist/cjs/filesystem/virtual/config.d.cts +3 -0
  15. package/dist/cjs/filesystem/virtual/getRouteNodes.cjs +175 -0
  16. package/dist/cjs/filesystem/virtual/getRouteNodes.cjs.map +1 -0
  17. package/dist/cjs/filesystem/virtual/getRouteNodes.d.cts +9 -0
  18. package/dist/cjs/filesystem/virtual/loadConfigFile.cjs +12 -0
  19. package/dist/cjs/filesystem/virtual/loadConfigFile.cjs.map +1 -0
  20. package/dist/cjs/filesystem/virtual/loadConfigFile.d.cts +1 -0
  21. package/dist/cjs/generator.cjs +805 -0
  22. package/dist/cjs/generator.cjs.map +1 -0
  23. package/dist/cjs/generator.d.cts +116 -0
  24. package/dist/cjs/index.cjs +33 -0
  25. package/dist/cjs/index.d.cts +12 -0
  26. package/dist/cjs/logger.cjs +31 -0
  27. package/dist/cjs/logger.cjs.map +1 -0
  28. package/dist/cjs/logger.d.cts +10 -0
  29. package/dist/cjs/plugin/types.d.cts +18 -0
  30. package/dist/cjs/template.cjs +203 -0
  31. package/dist/cjs/template.cjs.map +1 -0
  32. package/dist/cjs/template.d.cts +34 -0
  33. package/dist/cjs/transform/transform.cjs +302 -0
  34. package/dist/cjs/transform/transform.cjs.map +1 -0
  35. package/dist/cjs/transform/transform.d.cts +4 -0
  36. package/dist/cjs/transform/types.d.cts +31 -0
  37. package/dist/cjs/transform/utils.cjs +34 -0
  38. package/dist/cjs/transform/utils.cjs.map +1 -0
  39. package/dist/cjs/transform/utils.d.cts +2 -0
  40. package/dist/cjs/types.d.cts +57 -0
  41. package/dist/cjs/utils.cjs +653 -0
  42. package/dist/cjs/utils.cjs.map +1 -0
  43. package/dist/cjs/utils.d.cts +212 -0
  44. package/dist/cjs/validate-route-params.cjs +73 -0
  45. package/dist/cjs/validate-route-params.cjs.map +1 -0
  46. package/dist/cjs/validate-route-params.d.cts +9 -0
  47. package/dist/esm/config.d.ts +254 -0
  48. package/dist/esm/config.js +129 -0
  49. package/dist/esm/config.js.map +1 -0
  50. package/dist/esm/filesystem/physical/getRouteNodes.d.ts +25 -0
  51. package/dist/esm/filesystem/physical/getRouteNodes.js +230 -0
  52. package/dist/esm/filesystem/physical/getRouteNodes.js.map +1 -0
  53. package/dist/esm/filesystem/physical/rootPathId.d.ts +1 -0
  54. package/dist/esm/filesystem/physical/rootPathId.js +6 -0
  55. package/dist/esm/filesystem/physical/rootPathId.js.map +1 -0
  56. package/dist/esm/filesystem/virtual/config.d.ts +3 -0
  57. package/dist/esm/filesystem/virtual/config.js +38 -0
  58. package/dist/esm/filesystem/virtual/config.js.map +1 -0
  59. package/dist/esm/filesystem/virtual/getRouteNodes.d.ts +9 -0
  60. package/dist/esm/filesystem/virtual/getRouteNodes.js +173 -0
  61. package/dist/esm/filesystem/virtual/getRouteNodes.js.map +1 -0
  62. package/dist/esm/filesystem/virtual/loadConfigFile.d.ts +1 -0
  63. package/dist/esm/filesystem/virtual/loadConfigFile.js +11 -0
  64. package/dist/esm/filesystem/virtual/loadConfigFile.js.map +1 -0
  65. package/dist/esm/generator.d.ts +116 -0
  66. package/dist/esm/generator.js +801 -0
  67. package/dist/esm/generator.js.map +1 -0
  68. package/dist/esm/index.d.ts +12 -0
  69. package/dist/esm/index.js +8 -0
  70. package/dist/esm/logger.d.ts +10 -0
  71. package/dist/esm/logger.js +31 -0
  72. package/dist/esm/logger.js.map +1 -0
  73. package/dist/esm/plugin/types.d.ts +18 -0
  74. package/dist/esm/template.d.ts +34 -0
  75. package/dist/esm/template.js +202 -0
  76. package/dist/esm/template.js.map +1 -0
  77. package/dist/esm/transform/transform.d.ts +4 -0
  78. package/dist/esm/transform/transform.js +301 -0
  79. package/dist/esm/transform/transform.js.map +1 -0
  80. package/dist/esm/transform/types.d.ts +31 -0
  81. package/dist/esm/transform/utils.d.ts +2 -0
  82. package/dist/esm/transform/utils.js +34 -0
  83. package/dist/esm/transform/utils.js.map +1 -0
  84. package/dist/esm/types.d.ts +57 -0
  85. package/dist/esm/utils.d.ts +212 -0
  86. package/dist/esm/utils.js +609 -0
  87. package/dist/esm/utils.js.map +1 -0
  88. package/dist/esm/validate-route-params.d.ts +9 -0
  89. package/dist/esm/validate-route-params.js +73 -0
  90. package/dist/esm/validate-route-params.js.map +1 -0
  91. package/package.json +82 -0
  92. package/src/config.ts +247 -0
  93. package/src/filesystem/physical/getRouteNodes.ts +541 -0
  94. package/src/filesystem/physical/rootPathId.ts +1 -0
  95. package/src/filesystem/virtual/config.ts +45 -0
  96. package/src/filesystem/virtual/getRouteNodes.ts +307 -0
  97. package/src/filesystem/virtual/loadConfigFile.ts +8 -0
  98. package/src/generator.ts +1686 -0
  99. package/src/index.ts +54 -0
  100. package/src/logger.ts +43 -0
  101. package/src/plugin/types.ts +18 -0
  102. package/src/template.ts +313 -0
  103. package/src/transform/transform.ts +534 -0
  104. package/src/transform/types.ts +39 -0
  105. package/src/transform/utils.ts +42 -0
  106. package/src/types.ts +74 -0
  107. package/src/utils.ts +1067 -0
  108. package/src/validate-route-params.ts +118 -0
@@ -0,0 +1,234 @@
1
+ const require_runtime = require("../../_virtual/_rolldown/runtime.cjs");
2
+ const require_logger = require("../../logger.cjs");
3
+ require("./rootPathId.cjs");
4
+ const require_utils = require("../../utils.cjs");
5
+ const require_loadConfigFile = require("../virtual/loadConfigFile.cjs");
6
+ const require_getRouteNodes = require("../virtual/getRouteNodes.cjs");
7
+ let node_path = require("node:path");
8
+ node_path = require_runtime.__toESM(node_path);
9
+ let node_fs_promises = require("node:fs/promises");
10
+ node_fs_promises = require_runtime.__toESM(node_fs_promises);
11
+ //#region src/filesystem/physical/getRouteNodes.ts
12
+ var disallowedRouteGroupConfiguration = /\(([^)]+)\).(ts|js|tsx|jsx|vue)/;
13
+ var virtualConfigFileRegExp = /__virtual\.[mc]?[jt]s$/;
14
+ function isVirtualConfigFile(fileName) {
15
+ return virtualConfigFileRegExp.test(fileName);
16
+ }
17
+ async function getRouteNodes(config, root, tokenRegexes) {
18
+ const { routeFilePrefix, routeFileIgnorePrefix, routeFileIgnorePattern } = config;
19
+ const logger = require_logger.logging({ disabled: config.disableLogging });
20
+ const routeFileIgnoreRegExp = new RegExp(routeFileIgnorePattern ?? "", "g");
21
+ const routeNodes = [];
22
+ const allPhysicalDirectories = [];
23
+ async function recurse(dir) {
24
+ const fullDir = node_path.default.resolve(config.routesDirectory, dir);
25
+ let dirList = await node_fs_promises.readdir(fullDir, { withFileTypes: true });
26
+ dirList = dirList.filter((d) => {
27
+ if (d.name.startsWith(".") || routeFileIgnorePrefix && d.name.startsWith(routeFileIgnorePrefix)) return false;
28
+ if (routeFilePrefix) {
29
+ if (routeFileIgnorePattern) return d.name.startsWith(routeFilePrefix) && !d.name.match(routeFileIgnoreRegExp);
30
+ return d.name.startsWith(routeFilePrefix);
31
+ }
32
+ if (routeFileIgnorePattern) return !d.name.match(routeFileIgnoreRegExp);
33
+ return true;
34
+ });
35
+ const virtualConfigFile = dirList.find((dirent) => {
36
+ return dirent.isFile() && isVirtualConfigFile(dirent.name);
37
+ });
38
+ if (virtualConfigFile !== void 0) {
39
+ const virtualRouteConfigExport = await require_loadConfigFile.loadConfigFile(node_path.default.resolve(fullDir, virtualConfigFile.name));
40
+ let virtualRouteSubtreeConfig;
41
+ if (typeof virtualRouteConfigExport.default === "function") virtualRouteSubtreeConfig = await virtualRouteConfigExport.default();
42
+ else virtualRouteSubtreeConfig = virtualRouteConfigExport.default;
43
+ const dummyRoot = {
44
+ type: "root",
45
+ file: "",
46
+ children: virtualRouteSubtreeConfig
47
+ };
48
+ const { routeNodes: virtualRouteNodes, physicalDirectories } = await require_getRouteNodes.getRouteNodes({
49
+ ...config,
50
+ routesDirectory: fullDir,
51
+ virtualRouteConfig: dummyRoot
52
+ }, root, tokenRegexes);
53
+ allPhysicalDirectories.push(...physicalDirectories);
54
+ virtualRouteNodes.forEach((node) => {
55
+ const filePath = require_utils.replaceBackslash(node_path.default.join(dir, node.filePath));
56
+ const routePath = `/${dir}${node.routePath}`;
57
+ node.variableName = require_utils.routePathToVariable(`${dir}/${require_utils.removeExt(node.filePath)}`);
58
+ node.routePath = routePath;
59
+ if (node.originalRoutePath) node.originalRoutePath = `/${dir}${node.originalRoutePath}`;
60
+ node.filePath = filePath;
61
+ delete node._virtualParentRoutePath;
62
+ });
63
+ routeNodes.push(...virtualRouteNodes);
64
+ return;
65
+ }
66
+ await Promise.all(dirList.map(async (dirent) => {
67
+ const fullPath = require_utils.replaceBackslash(node_path.default.join(fullDir, dirent.name));
68
+ const relativePath = node_path.default.posix.join(dir, dirent.name);
69
+ if (dirent.isDirectory()) await recurse(relativePath);
70
+ else if (fullPath.match(/\.(tsx|ts|jsx|js|vue)$/)) {
71
+ const filePath = require_utils.replaceBackslash(node_path.default.join(dir, dirent.name));
72
+ const { routePath: initialRoutePath, originalRoutePath: initialOriginalRoutePath } = require_utils.determineInitialRoutePath(require_utils.removeExt(filePath));
73
+ let routePath = initialRoutePath;
74
+ let originalRoutePath = initialOriginalRoutePath;
75
+ if (routeFilePrefix) {
76
+ routePath = routePath.replaceAll(routeFilePrefix, "");
77
+ originalRoutePath = originalRoutePath.replaceAll(routeFilePrefix, "");
78
+ }
79
+ if (disallowedRouteGroupConfiguration.test(dirent.name)) {
80
+ const errorMessage = `A route configuration for a route group was found at \`${filePath}\`. This is not supported. Did you mean to use a layout/pathless route instead?`;
81
+ logger.error(`ERROR: ${errorMessage}`);
82
+ throw new Error(errorMessage);
83
+ }
84
+ const meta = getRouteMeta(routePath, originalRoutePath, tokenRegexes);
85
+ const variableName = meta.variableName;
86
+ let routeType = meta.fsRouteType;
87
+ if (routeType === "lazy") {
88
+ routePath = routePath.replace(/\/lazy$/, "");
89
+ originalRoutePath = originalRoutePath.replace(/\/lazy$/, "");
90
+ }
91
+ if (isValidPathlessLayoutRoute(routePath, originalRoutePath, routeType, tokenRegexes)) routeType = "pathless_layout";
92
+ if (!filePath.endsWith(".vue")) [
93
+ ["component", "component"],
94
+ ["errorComponent", "errorComponent"],
95
+ ["notFoundComponent", "notFoundComponent"],
96
+ ["pendingComponent", "pendingComponent"],
97
+ ["loader", "loader"]
98
+ ].forEach(([matcher, type]) => {
99
+ if (routeType === matcher) logger.warn(`WARNING: The \`.${type}.tsx\` suffix used for the ${filePath} file is deprecated. Use the new \`.lazy.tsx\` suffix instead.`);
100
+ });
101
+ const originalSegments = originalRoutePath.split("/").filter(Boolean);
102
+ const lastOriginalSegmentForSuffix = originalSegments[originalSegments.length - 1] || "";
103
+ const { routeTokenSegmentRegex, indexTokenSegmentRegex } = tokenRegexes;
104
+ const specialSuffixes = [
105
+ "component",
106
+ "errorComponent",
107
+ "notFoundComponent",
108
+ "pendingComponent",
109
+ "loader",
110
+ "lazy"
111
+ ];
112
+ const routePathSegments = routePath.split("/").filter(Boolean);
113
+ const lastRouteSegment = routePathSegments[routePathSegments.length - 1] || "";
114
+ const suffixToStrip = specialSuffixes.find((suffix) => {
115
+ const endsWithSuffix = routePath.endsWith(`/${suffix}`);
116
+ const isEscaped = lastOriginalSegmentForSuffix.startsWith("[") && lastOriginalSegmentForSuffix.endsWith("]") && require_utils.unwrapBracketWrappedSegment(lastOriginalSegmentForSuffix) === suffix;
117
+ return endsWithSuffix && !isEscaped;
118
+ });
119
+ const routeTokenCandidate = require_utils.unwrapBracketWrappedSegment(lastOriginalSegmentForSuffix);
120
+ const isRouteTokenEscaped = lastOriginalSegmentForSuffix !== routeTokenCandidate && routeTokenSegmentRegex.test(routeTokenCandidate);
121
+ const shouldStripRouteToken = routeTokenSegmentRegex.test(lastRouteSegment) && !isRouteTokenEscaped;
122
+ if (suffixToStrip || shouldStripRouteToken) {
123
+ const stripSegment = suffixToStrip ?? lastRouteSegment;
124
+ routePath = routePath.replace(new RegExp(`/${require_utils.escapeRegExp(stripSegment)}$`), "");
125
+ originalRoutePath = originalRoutePath.replace(new RegExp(`/${require_utils.escapeRegExp(stripSegment)}$`), "");
126
+ }
127
+ const lastOriginalSegment = originalRoutePath.split("/").filter(Boolean).pop() || "";
128
+ const indexTokenCandidate = require_utils.unwrapBracketWrappedSegment(lastOriginalSegment);
129
+ if (!(lastOriginalSegment !== indexTokenCandidate && indexTokenSegmentRegex.test(indexTokenCandidate))) {
130
+ const updatedRouteSegments = routePath.split("/").filter(Boolean);
131
+ const updatedLastRouteSegment = updatedRouteSegments[updatedRouteSegments.length - 1] || "";
132
+ if (indexTokenSegmentRegex.test(updatedLastRouteSegment)) {
133
+ if (routePathSegments.length === 1) routePath = "/";
134
+ if (lastOriginalSegment === updatedLastRouteSegment) originalRoutePath = "/";
135
+ const isLayoutRoute = routeType === "layout";
136
+ routePath = routePath.replace(new RegExp(`/${require_utils.escapeRegExp(updatedLastRouteSegment)}$`), "/") || (isLayoutRoute ? "" : "/");
137
+ originalRoutePath = originalRoutePath.replace(new RegExp(`/${require_utils.escapeRegExp(indexTokenCandidate)}$`), "/") || (isLayoutRoute ? "" : "/");
138
+ }
139
+ }
140
+ routeNodes.push({
141
+ filePath,
142
+ fullPath,
143
+ routePath,
144
+ variableName,
145
+ _fsRouteType: routeType,
146
+ originalRoutePath
147
+ });
148
+ }
149
+ }));
150
+ return routeNodes;
151
+ }
152
+ await recurse("./");
153
+ const rootRouteNode = routeNodes.find((d) => d.routePath === `/__root` && ![
154
+ "component",
155
+ "errorComponent",
156
+ "notFoundComponent",
157
+ "pendingComponent",
158
+ "loader",
159
+ "lazy"
160
+ ].includes(d._fsRouteType)) ?? routeNodes.find((d) => d.routePath === `/__root`);
161
+ if (rootRouteNode) {
162
+ rootRouteNode._fsRouteType = "__root";
163
+ rootRouteNode.variableName = "root";
164
+ }
165
+ return {
166
+ rootRouteNode,
167
+ routeNodes,
168
+ physicalDirectories: allPhysicalDirectories
169
+ };
170
+ }
171
+ /**
172
+ * Determines the metadata for a given route path based on the provided configuration.
173
+ *
174
+ * @param routePath - The determined initial routePath (with brackets removed).
175
+ * @param originalRoutePath - The original route path (may contain brackets for escaped content).
176
+ * @param tokenRegexes - Pre-compiled token regexes for matching.
177
+ * @returns An object containing the type of the route and the variable name derived from the route path.
178
+ */
179
+ function getRouteMeta(routePath, originalRoutePath, tokenRegexes) {
180
+ let fsRouteType = "static";
181
+ const originalSegments = originalRoutePath.split("/").filter(Boolean);
182
+ const lastOriginalSegment = originalSegments[originalSegments.length - 1] || "";
183
+ const { routeTokenSegmentRegex } = tokenRegexes;
184
+ const isSuffixEscaped = (suffix) => {
185
+ return lastOriginalSegment.startsWith("[") && lastOriginalSegment.endsWith("]") && require_utils.unwrapBracketWrappedSegment(lastOriginalSegment) === suffix;
186
+ };
187
+ const routeSegments = routePath.split("/").filter(Boolean);
188
+ const lastRouteSegment = routeSegments[routeSegments.length - 1] || "";
189
+ const routeTokenCandidate = require_utils.unwrapBracketWrappedSegment(lastOriginalSegment);
190
+ const isRouteTokenEscaped = lastOriginalSegment !== routeTokenCandidate && routeTokenSegmentRegex.test(routeTokenCandidate);
191
+ if (routeTokenSegmentRegex.test(lastRouteSegment) && !isRouteTokenEscaped) fsRouteType = "layout";
192
+ else if (routePath.endsWith("/lazy") && !isSuffixEscaped("lazy")) fsRouteType = "lazy";
193
+ else if (routePath.endsWith("/loader") && !isSuffixEscaped("loader")) fsRouteType = "loader";
194
+ else if (routePath.endsWith("/component") && !isSuffixEscaped("component")) fsRouteType = "component";
195
+ else if (routePath.endsWith("/pendingComponent") && !isSuffixEscaped("pendingComponent")) fsRouteType = "pendingComponent";
196
+ else if (routePath.endsWith("/errorComponent") && !isSuffixEscaped("errorComponent")) fsRouteType = "errorComponent";
197
+ else if (routePath.endsWith("/notFoundComponent") && !isSuffixEscaped("notFoundComponent")) fsRouteType = "notFoundComponent";
198
+ const variableName = require_utils.routePathToVariable(originalSegments.some((seg) => seg.startsWith("[") && seg.endsWith("]") && !seg.slice(1, -1).includes("[") && !seg.slice(1, -1).includes("]")) ? originalRoutePath : routePath);
199
+ return {
200
+ fsRouteType,
201
+ variableName
202
+ };
203
+ }
204
+ /**
205
+ * Used to validate if a route is a pathless layout route
206
+ * @param normalizedRoutePath Normalized route path, i.e `/foo/_layout/route.tsx` and `/foo._layout.route.tsx` to `/foo/_layout/route`
207
+ * @param originalRoutePath Original route path with brackets for escaped content
208
+ * @param routeType The route type determined from file extension
209
+ * @param tokenRegexes Pre-compiled token regexes for matching
210
+ * @returns Boolean indicating if the route is a pathless layout route
211
+ */
212
+ function isValidPathlessLayoutRoute(normalizedRoutePath, originalRoutePath, routeType, tokenRegexes) {
213
+ if (routeType === "lazy") return false;
214
+ const segments = normalizedRoutePath.split("/").filter(Boolean);
215
+ const originalSegments = originalRoutePath.split("/").filter(Boolean);
216
+ if (segments.length === 0) return false;
217
+ const lastRouteSegment = segments[segments.length - 1];
218
+ const lastOriginalSegment = originalSegments[originalSegments.length - 1] || "";
219
+ const secondToLastRouteSegment = segments[segments.length - 2];
220
+ const secondToLastOriginalSegment = originalSegments[originalSegments.length - 2];
221
+ if (lastRouteSegment === "__root") return false;
222
+ const { routeTokenSegmentRegex, indexTokenSegmentRegex } = tokenRegexes;
223
+ if (routeTokenSegmentRegex.test(lastRouteSegment) && typeof secondToLastRouteSegment === "string" && typeof secondToLastOriginalSegment === "string") {
224
+ if (require_utils.hasEscapedLeadingUnderscore(secondToLastOriginalSegment)) return false;
225
+ return secondToLastRouteSegment.startsWith("_");
226
+ }
227
+ if (require_utils.hasEscapedLeadingUnderscore(lastOriginalSegment)) return false;
228
+ return !indexTokenSegmentRegex.test(lastRouteSegment) && !routeTokenSegmentRegex.test(lastRouteSegment) && lastRouteSegment.startsWith("_");
229
+ }
230
+ //#endregion
231
+ exports.getRouteNodes = getRouteNodes;
232
+ exports.isVirtualConfigFile = isVirtualConfigFile;
233
+
234
+ //# sourceMappingURL=getRouteNodes.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getRouteNodes.cjs","names":[],"sources":["../../../../src/filesystem/physical/getRouteNodes.ts"],"sourcesContent":["import path from 'node:path'\nimport * as fsp from 'node:fs/promises'\nimport {\n determineInitialRoutePath,\n escapeRegExp,\n hasEscapedLeadingUnderscore,\n removeExt,\n replaceBackslash,\n routePathToVariable,\n unwrapBracketWrappedSegment,\n} from '../../utils'\nimport { getRouteNodes as getRouteNodesVirtual } from '../virtual/getRouteNodes'\nimport { loadConfigFile } from '../virtual/loadConfigFile'\nimport { logging } from '../../logger'\nimport { rootPathId } from './rootPathId'\nimport type {\n VirtualRootRoute,\n VirtualRouteSubtreeConfig,\n} from '@benjavicente/virtual-file-routes'\nimport type { FsRouteType, GetRouteNodesResult, RouteNode } from '../../types'\nimport type { Config } from '../../config'\n\n/**\n * Pre-compiled segment regexes for matching token patterns against route segments.\n * These are created once (in Generator constructor) and passed through to avoid\n * repeated regex compilation during route crawling.\n */\nexport interface TokenRegexBundle {\n indexTokenSegmentRegex: RegExp\n routeTokenSegmentRegex: RegExp\n}\n\nconst disallowedRouteGroupConfiguration = /\\(([^)]+)\\).(ts|js|tsx|jsx|vue)/\n\nconst virtualConfigFileRegExp = /__virtual\\.[mc]?[jt]s$/\nexport function isVirtualConfigFile(fileName: string): boolean {\n return virtualConfigFileRegExp.test(fileName)\n}\n\nexport async function getRouteNodes(\n config: Pick<\n Config,\n | 'routesDirectory'\n | 'routeFilePrefix'\n | 'routeFileIgnorePrefix'\n | 'routeFileIgnorePattern'\n | 'disableLogging'\n | 'routeToken'\n | 'indexToken'\n >,\n root: string,\n tokenRegexes: TokenRegexBundle,\n): Promise<GetRouteNodesResult> {\n const { routeFilePrefix, routeFileIgnorePrefix, routeFileIgnorePattern } =\n config\n\n const logger = logging({ disabled: config.disableLogging })\n const routeFileIgnoreRegExp = new RegExp(routeFileIgnorePattern ?? '', 'g')\n\n const routeNodes: Array<RouteNode> = []\n const allPhysicalDirectories: Array<string> = []\n\n async function recurse(dir: string) {\n const fullDir = path.resolve(config.routesDirectory, dir)\n let dirList = await fsp.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 if (routeFileIgnorePattern) {\n return (\n d.name.startsWith(routeFilePrefix) &&\n !d.name.match(routeFileIgnoreRegExp)\n )\n }\n\n return d.name.startsWith(routeFilePrefix)\n }\n\n if (routeFileIgnorePattern) {\n return !d.name.match(routeFileIgnoreRegExp)\n }\n\n return true\n })\n\n const virtualConfigFile = dirList.find((dirent) => {\n return dirent.isFile() && isVirtualConfigFile(dirent.name)\n })\n\n if (virtualConfigFile !== undefined) {\n const virtualRouteConfigExport = await loadConfigFile(\n path.resolve(fullDir, virtualConfigFile.name),\n )\n let virtualRouteSubtreeConfig: VirtualRouteSubtreeConfig\n if (typeof virtualRouteConfigExport.default === 'function') {\n virtualRouteSubtreeConfig = await virtualRouteConfigExport.default()\n } else {\n virtualRouteSubtreeConfig = virtualRouteConfigExport.default\n }\n const dummyRoot: VirtualRootRoute = {\n type: 'root',\n file: '',\n children: virtualRouteSubtreeConfig,\n }\n const { routeNodes: virtualRouteNodes, physicalDirectories } =\n await getRouteNodesVirtual(\n {\n ...config,\n routesDirectory: fullDir,\n virtualRouteConfig: dummyRoot,\n },\n root,\n tokenRegexes,\n )\n allPhysicalDirectories.push(...physicalDirectories)\n virtualRouteNodes.forEach((node) => {\n const filePath = replaceBackslash(path.join(dir, node.filePath))\n const routePath = `/${dir}${node.routePath}`\n\n node.variableName = routePathToVariable(\n `${dir}/${removeExt(node.filePath)}`,\n )\n node.routePath = routePath\n // Keep originalRoutePath aligned with routePath for escape detection\n if (node.originalRoutePath) {\n node.originalRoutePath = `/${dir}${node.originalRoutePath}`\n }\n node.filePath = filePath\n // Virtual subtree nodes (from __virtual.ts) are embedded in a\n // physical directory tree. They should use path-based parent\n // inference, not the explicit virtual parent tracking. Clear any\n // _virtualParentRoutePath that was set at construction time.\n delete node._virtualParentRoutePath\n })\n\n routeNodes.push(...virtualRouteNodes)\n\n return\n }\n\n await Promise.all(\n dirList.map(async (dirent) => {\n const fullPath = replaceBackslash(path.join(fullDir, dirent.name))\n const relativePath = path.posix.join(dir, dirent.name)\n\n if (dirent.isDirectory()) {\n await recurse(relativePath)\n } else if (fullPath.match(/\\.(tsx|ts|jsx|js|vue)$/)) {\n const filePath = replaceBackslash(path.join(dir, dirent.name))\n const filePathNoExt = removeExt(filePath)\n const {\n routePath: initialRoutePath,\n originalRoutePath: initialOriginalRoutePath,\n } = determineInitialRoutePath(filePathNoExt)\n\n let routePath = initialRoutePath\n let originalRoutePath = initialOriginalRoutePath\n\n if (routeFilePrefix) {\n routePath = routePath.replaceAll(routeFilePrefix, '')\n originalRoutePath = originalRoutePath.replaceAll(\n routeFilePrefix,\n '',\n )\n }\n\n if (disallowedRouteGroupConfiguration.test(dirent.name)) {\n const errorMessage = `A route configuration for a route group was found at \\`${filePath}\\`. This is not supported. Did you mean to use a layout/pathless route instead?`\n logger.error(`ERROR: ${errorMessage}`)\n throw new Error(errorMessage)\n }\n\n const meta = getRouteMeta(routePath, originalRoutePath, tokenRegexes)\n const variableName = meta.variableName\n let routeType: FsRouteType = meta.fsRouteType\n\n if (routeType === 'lazy') {\n routePath = routePath.replace(/\\/lazy$/, '')\n originalRoutePath = originalRoutePath.replace(/\\/lazy$/, '')\n }\n\n // this check needs to happen after the lazy route has been cleaned up\n // since the routePath is used to determine if a route is pathless\n if (\n isValidPathlessLayoutRoute(\n routePath,\n originalRoutePath,\n routeType,\n tokenRegexes,\n )\n ) {\n routeType = 'pathless_layout'\n }\n\n // Only show deprecation warning for .tsx/.ts files, not .vue files\n // Vue files using .component.vue is the Vue-native way\n const isVueFile = filePath.endsWith('.vue')\n if (!isVueFile) {\n ;(\n [\n ['component', 'component'],\n ['errorComponent', 'errorComponent'],\n ['notFoundComponent', 'notFoundComponent'],\n ['pendingComponent', 'pendingComponent'],\n ['loader', 'loader'],\n ] satisfies Array<[FsRouteType, string]>\n ).forEach(([matcher, type]) => {\n if (routeType === matcher) {\n logger.warn(\n `WARNING: The \\`.${type}.tsx\\` suffix used for the ${filePath} file is deprecated. Use the new \\`.lazy.tsx\\` suffix instead.`,\n )\n }\n })\n }\n\n // Get the last segment of originalRoutePath to check for escaping\n const originalSegments = originalRoutePath.split('/').filter(Boolean)\n const lastOriginalSegmentForSuffix =\n originalSegments[originalSegments.length - 1] || ''\n\n const { routeTokenSegmentRegex, indexTokenSegmentRegex } =\n tokenRegexes\n\n // List of special suffixes that can be escaped\n const specialSuffixes = [\n 'component',\n 'errorComponent',\n 'notFoundComponent',\n 'pendingComponent',\n 'loader',\n 'lazy',\n ]\n\n const routePathSegments = routePath.split('/').filter(Boolean)\n const lastRouteSegment =\n routePathSegments[routePathSegments.length - 1] || ''\n\n const suffixToStrip = specialSuffixes.find((suffix) => {\n const endsWithSuffix = routePath.endsWith(`/${suffix}`)\n // A suffix is escaped if wrapped in brackets in the original: [lazy] means literal \"lazy\"\n const isEscaped =\n lastOriginalSegmentForSuffix.startsWith('[') &&\n lastOriginalSegmentForSuffix.endsWith(']') &&\n unwrapBracketWrappedSegment(lastOriginalSegmentForSuffix) ===\n suffix\n return endsWithSuffix && !isEscaped\n })\n\n const routeTokenCandidate = unwrapBracketWrappedSegment(\n lastOriginalSegmentForSuffix,\n )\n const isRouteTokenEscaped =\n lastOriginalSegmentForSuffix !== routeTokenCandidate &&\n routeTokenSegmentRegex.test(routeTokenCandidate)\n\n const shouldStripRouteToken =\n routeTokenSegmentRegex.test(lastRouteSegment) &&\n !isRouteTokenEscaped\n\n if (suffixToStrip || shouldStripRouteToken) {\n const stripSegment = suffixToStrip ?? lastRouteSegment\n routePath = routePath.replace(\n new RegExp(`/${escapeRegExp(stripSegment)}$`),\n '',\n )\n originalRoutePath = originalRoutePath.replace(\n new RegExp(`/${escapeRegExp(stripSegment)}$`),\n '',\n )\n }\n\n // Check if the index token should be treated specially or as a literal path\n // Escaping stays literal-only: if the last original segment is bracket-wrapped,\n // treat it as literal even if it matches the token regex.\n const lastOriginalSegment =\n originalRoutePath.split('/').filter(Boolean).pop() || ''\n\n const indexTokenCandidate =\n unwrapBracketWrappedSegment(lastOriginalSegment)\n const isIndexEscaped =\n lastOriginalSegment !== indexTokenCandidate &&\n indexTokenSegmentRegex.test(indexTokenCandidate)\n\n if (!isIndexEscaped) {\n const updatedRouteSegments = routePath.split('/').filter(Boolean)\n const updatedLastRouteSegment =\n updatedRouteSegments[updatedRouteSegments.length - 1] || ''\n\n if (indexTokenSegmentRegex.test(updatedLastRouteSegment)) {\n if (routePathSegments.length === 1) {\n routePath = '/'\n }\n\n if (lastOriginalSegment === updatedLastRouteSegment) {\n originalRoutePath = '/'\n }\n\n // For layout routes, don't use '/' fallback - an empty path means\n // \"layout for the parent path\" which is important for physical() mounts\n // where route.tsx at root should have empty path, not '/'\n const isLayoutRoute = routeType === 'layout'\n\n routePath =\n routePath.replace(\n new RegExp(`/${escapeRegExp(updatedLastRouteSegment)}$`),\n '/',\n ) || (isLayoutRoute ? '' : '/')\n\n originalRoutePath =\n originalRoutePath.replace(\n new RegExp(`/${escapeRegExp(indexTokenCandidate)}$`),\n '/',\n ) || (isLayoutRoute ? '' : '/')\n }\n }\n\n routeNodes.push({\n filePath,\n fullPath,\n routePath,\n variableName,\n _fsRouteType: routeType,\n originalRoutePath,\n })\n }\n }),\n )\n\n return routeNodes\n }\n\n await recurse('./')\n\n // Find the root route node - prefer the actual route file over component/loader files\n const rootRouteNode =\n routeNodes.find(\n (d) =>\n d.routePath === `/${rootPathId}` &&\n ![\n 'component',\n 'errorComponent',\n 'notFoundComponent',\n 'pendingComponent',\n 'loader',\n 'lazy',\n ].includes(d._fsRouteType),\n ) ?? routeNodes.find((d) => d.routePath === `/${rootPathId}`)\n if (rootRouteNode) {\n rootRouteNode._fsRouteType = '__root'\n rootRouteNode.variableName = 'root'\n }\n\n return {\n rootRouteNode,\n routeNodes,\n physicalDirectories: allPhysicalDirectories,\n }\n}\n\n/**\n * Determines the metadata for a given route path based on the provided configuration.\n *\n * @param routePath - The determined initial routePath (with brackets removed).\n * @param originalRoutePath - The original route path (may contain brackets for escaped content).\n * @param tokenRegexes - Pre-compiled token regexes for matching.\n * @returns An object containing the type of the route and the variable name derived from the route path.\n */\nexport function getRouteMeta(\n routePath: string,\n originalRoutePath: string,\n tokenRegexes: TokenRegexBundle,\n): {\n // `__root` is can be more easily determined by filtering down to routePath === /${rootPathId}\n // `pathless` is needs to determined after `lazy` has been cleaned up from the routePath\n fsRouteType: Extract<\n FsRouteType,\n | 'static'\n | 'layout'\n | 'api'\n | 'lazy'\n | 'loader'\n | 'component'\n | 'pendingComponent'\n | 'errorComponent'\n | 'notFoundComponent'\n >\n variableName: string\n} {\n let fsRouteType: FsRouteType = 'static'\n\n // Get the last segment from the original path to check for escaping\n const originalSegments = originalRoutePath.split('/').filter(Boolean)\n const lastOriginalSegment =\n originalSegments[originalSegments.length - 1] || ''\n\n const { routeTokenSegmentRegex } = tokenRegexes\n\n // Helper to check if a specific suffix is escaped (literal-only)\n // A suffix is escaped if the original segment is wrapped in brackets: [lazy] means literal \"lazy\"\n const isSuffixEscaped = (suffix: string): boolean => {\n return (\n lastOriginalSegment.startsWith('[') &&\n lastOriginalSegment.endsWith(']') &&\n unwrapBracketWrappedSegment(lastOriginalSegment) === suffix\n )\n }\n\n const routeSegments = routePath.split('/').filter(Boolean)\n const lastRouteSegment = routeSegments[routeSegments.length - 1] || ''\n\n const routeTokenCandidate = unwrapBracketWrappedSegment(lastOriginalSegment)\n const isRouteTokenEscaped =\n lastOriginalSegment !== routeTokenCandidate &&\n routeTokenSegmentRegex.test(routeTokenCandidate)\n\n if (routeTokenSegmentRegex.test(lastRouteSegment) && !isRouteTokenEscaped) {\n // layout routes, i.e `/foo/route.tsx` or `/foo/_layout/route.tsx`\n fsRouteType = 'layout'\n } else if (routePath.endsWith('/lazy') && !isSuffixEscaped('lazy')) {\n // lazy routes, i.e. `/foo.lazy.tsx`\n fsRouteType = 'lazy'\n } else if (routePath.endsWith('/loader') && !isSuffixEscaped('loader')) {\n // loader routes, i.e. `/foo.loader.tsx`\n fsRouteType = 'loader'\n } else if (\n routePath.endsWith('/component') &&\n !isSuffixEscaped('component')\n ) {\n // component routes, i.e. `/foo.component.tsx`\n fsRouteType = 'component'\n } else if (\n routePath.endsWith('/pendingComponent') &&\n !isSuffixEscaped('pendingComponent')\n ) {\n // pending component routes, i.e. `/foo.pendingComponent.tsx`\n fsRouteType = 'pendingComponent'\n } else if (\n routePath.endsWith('/errorComponent') &&\n !isSuffixEscaped('errorComponent')\n ) {\n // error component routes, i.e. `/foo.errorComponent.tsx`\n fsRouteType = 'errorComponent'\n } else if (\n routePath.endsWith('/notFoundComponent') &&\n !isSuffixEscaped('notFoundComponent')\n ) {\n // not found component routes, i.e. `/foo.notFoundComponent.tsx`\n fsRouteType = 'notFoundComponent'\n }\n\n // Use originalRoutePath for variable name when any segment is fully\n // bracket-wrapped (e.g. [index], [route], [_]auth) to avoid collisions\n // with their non-escaped counterparts that get special token treatment\n const hasFullyEscapedSegment = originalSegments.some(\n (seg) =>\n seg.startsWith('[') &&\n seg.endsWith(']') &&\n !seg.slice(1, -1).includes('[') &&\n !seg.slice(1, -1).includes(']'),\n )\n const variableName = routePathToVariable(\n hasFullyEscapedSegment ? originalRoutePath : routePath,\n )\n\n return { fsRouteType, variableName }\n}\n\n/**\n * Used to validate if a route is a pathless layout route\n * @param normalizedRoutePath Normalized route path, i.e `/foo/_layout/route.tsx` and `/foo._layout.route.tsx` to `/foo/_layout/route`\n * @param originalRoutePath Original route path with brackets for escaped content\n * @param routeType The route type determined from file extension\n * @param tokenRegexes Pre-compiled token regexes for matching\n * @returns Boolean indicating if the route is a pathless layout route\n */\nfunction isValidPathlessLayoutRoute(\n normalizedRoutePath: string,\n originalRoutePath: string,\n routeType: FsRouteType,\n tokenRegexes: TokenRegexBundle,\n): boolean {\n if (routeType === 'lazy') {\n return false\n }\n\n const segments = normalizedRoutePath.split('/').filter(Boolean)\n const originalSegments = originalRoutePath.split('/').filter(Boolean)\n\n if (segments.length === 0) {\n return false\n }\n\n const lastRouteSegment = segments[segments.length - 1]!\n const lastOriginalSegment =\n originalSegments[originalSegments.length - 1] || ''\n const secondToLastRouteSegment = segments[segments.length - 2]\n const secondToLastOriginalSegment =\n originalSegments[originalSegments.length - 2]\n\n // If segment === __root, then exit as false\n if (lastRouteSegment === rootPathId) {\n return false\n }\n\n const { routeTokenSegmentRegex, indexTokenSegmentRegex } = tokenRegexes\n\n // If segment matches routeToken and secondToLastSegment is a string that starts with _, then exit as true\n // Since the route is actually a configuration route for a layout/pathless route\n // i.e. /foo/_layout/route.tsx === /foo/_layout.tsx\n // But if the underscore is escaped, it's not a pathless layout\n if (\n routeTokenSegmentRegex.test(lastRouteSegment) &&\n typeof secondToLastRouteSegment === 'string' &&\n typeof secondToLastOriginalSegment === 'string'\n ) {\n // Check if the underscore is escaped\n if (hasEscapedLeadingUnderscore(secondToLastOriginalSegment)) {\n return false\n }\n return secondToLastRouteSegment.startsWith('_')\n }\n\n // Segment starts with _ but check if it's escaped\n // If the original segment has [_] at the start, the underscore is escaped and it's not a pathless layout\n if (hasEscapedLeadingUnderscore(lastOriginalSegment)) {\n return false\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W,IAAI,IACnB,IAAI,SAAS,IAAI,IACjB,CAAC,IAAI,MAAM,GAAG,GAAG,CAAC,SAAS,IAAI,IAC/B,CAAC,IAAI,MAAM,GAAG,GAAG,CAAC,SAAS,IAAI,CAClC,GAE0B,oBAAoB,UAC9C;AAED,QAAO;EAAE;EAAa;EAAc;;;;;;;;;;AAWtC,SAAS,2BACP,qBACA,mBACA,WACA,cACS;AACT,KAAI,cAAc,OAChB,QAAO;CAGT,MAAM,WAAW,oBAAoB,MAAM,IAAI,CAAC,OAAO,QAAQ;CAC/D,MAAM,mBAAmB,kBAAkB,MAAM,IAAI,CAAC,OAAO,QAAQ;AAErE,KAAI,SAAS,WAAW,EACtB,QAAO;CAGT,MAAM,mBAAmB,SAAS,SAAS,SAAS;CACpD,MAAM,sBACJ,iBAAiB,iBAAiB,SAAS,MAAM;CACnD,MAAM,2BAA2B,SAAS,SAAS,SAAS;CAC5D,MAAM,8BACJ,iBAAiB,iBAAiB,SAAS;AAG7C,KAAI,qBAAA,SACF,QAAO;CAGT,MAAM,EAAE,wBAAwB,2BAA2B;AAM3D,KACE,uBAAuB,KAAK,iBAAiB,IAC7C,OAAO,6BAA6B,YACpC,OAAO,gCAAgC,UACvC;AAEA,MAAI,cAAA,4BAA4B,4BAA4B,CAC1D,QAAO;AAET,SAAO,yBAAyB,WAAW,IAAI;;AAKjD,KAAI,cAAA,4BAA4B,oBAAoB,CAClD,QAAO;AAGT,QACE,CAAC,uBAAuB,KAAK,iBAAiB,IAC9C,CAAC,uBAAuB,KAAK,iBAAiB,IAC9C,iBAAiB,WAAW,IAAI"}
@@ -0,0 +1,25 @@
1
+ import { FsRouteType, GetRouteNodesResult } from '../../types.cjs';
2
+ import { Config } from '../../config.cjs';
3
+ /**
4
+ * Pre-compiled segment regexes for matching token patterns against route segments.
5
+ * These are created once (in Generator constructor) and passed through to avoid
6
+ * repeated regex compilation during route crawling.
7
+ */
8
+ export interface TokenRegexBundle {
9
+ indexTokenSegmentRegex: RegExp;
10
+ routeTokenSegmentRegex: RegExp;
11
+ }
12
+ export declare function isVirtualConfigFile(fileName: string): boolean;
13
+ export declare function getRouteNodes(config: Pick<Config, 'routesDirectory' | 'routeFilePrefix' | 'routeFileIgnorePrefix' | 'routeFileIgnorePattern' | 'disableLogging' | 'routeToken' | 'indexToken'>, root: string, tokenRegexes: TokenRegexBundle): Promise<GetRouteNodesResult>;
14
+ /**
15
+ * Determines the metadata for a given route path based on the provided configuration.
16
+ *
17
+ * @param routePath - The determined initial routePath (with brackets removed).
18
+ * @param originalRoutePath - The original route path (may contain brackets for escaped content).
19
+ * @param tokenRegexes - Pre-compiled token regexes for matching.
20
+ * @returns An object containing the type of the route and the variable name derived from the route path.
21
+ */
22
+ export declare function getRouteMeta(routePath: string, originalRoutePath: string, tokenRegexes: TokenRegexBundle): {
23
+ fsRouteType: Extract<FsRouteType, 'static' | 'layout' | 'api' | 'lazy' | 'loader' | 'component' | 'pendingComponent' | 'errorComponent' | 'notFoundComponent'>;
24
+ variableName: string;
25
+ };
@@ -0,0 +1,6 @@
1
+ //#region src/filesystem/physical/rootPathId.ts
2
+ var rootPathId = "__root";
3
+ //#endregion
4
+ exports.rootPathId = rootPathId;
5
+
6
+ //# sourceMappingURL=rootPathId.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rootPathId.cjs","names":[],"sources":["../../../../src/filesystem/physical/rootPathId.ts"],"sourcesContent":["export const rootPathId = '__root'\n"],"mappings":";AAAA,IAAa,aAAa"}
@@ -0,0 +1 @@
1
+ export declare const rootPathId = "__root";
@@ -0,0 +1,39 @@
1
+ require("../../_virtual/_rolldown/runtime.cjs");
2
+ let zod = require("zod");
3
+ //#region src/filesystem/virtual/config.ts
4
+ var indexRouteSchema = zod.z.object({
5
+ type: zod.z.literal("index"),
6
+ file: zod.z.string()
7
+ });
8
+ var layoutRouteSchema = zod.z.object({
9
+ type: zod.z.literal("layout"),
10
+ id: zod.z.string().optional(),
11
+ file: zod.z.string(),
12
+ children: zod.z.array(zod.z.lazy(() => virtualRouteNodeSchema)).optional()
13
+ });
14
+ var routeSchema = zod.z.object({
15
+ type: zod.z.literal("route"),
16
+ file: zod.z.string().optional(),
17
+ path: zod.z.string(),
18
+ children: zod.z.array(zod.z.lazy(() => virtualRouteNodeSchema)).optional()
19
+ });
20
+ var physicalSubTreeSchema = zod.z.object({
21
+ type: zod.z.literal("physical"),
22
+ directory: zod.z.string(),
23
+ pathPrefix: zod.z.string()
24
+ });
25
+ var virtualRouteNodeSchema = zod.z.union([
26
+ indexRouteSchema,
27
+ layoutRouteSchema,
28
+ routeSchema,
29
+ physicalSubTreeSchema
30
+ ]);
31
+ var virtualRootRouteSchema = zod.z.object({
32
+ type: zod.z.literal("root"),
33
+ file: zod.z.string(),
34
+ children: zod.z.array(virtualRouteNodeSchema).optional()
35
+ });
36
+ //#endregion
37
+ exports.virtualRootRouteSchema = virtualRootRouteSchema;
38
+
39
+ //# sourceMappingURL=config.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.cjs","names":[],"sources":["../../../../src/filesystem/virtual/config.ts"],"sourcesContent":["import { z } from 'zod'\nimport type {\n LayoutRoute,\n PhysicalSubtree,\n Route,\n VirtualRootRoute,\n} from '@benjavicente/virtual-file-routes'\n\nconst indexRouteSchema = z.object({\n type: z.literal('index'),\n file: z.string(),\n})\n\nconst layoutRouteSchema: z.ZodType<LayoutRoute> = z.object({\n type: z.literal('layout'),\n id: z.string().optional(),\n file: z.string(),\n children: z.array(z.lazy(() => virtualRouteNodeSchema)).optional(),\n})\n\nconst routeSchema: z.ZodType<Route> = z.object({\n type: z.literal('route'),\n file: z.string().optional(),\n path: z.string(),\n children: z.array(z.lazy(() => virtualRouteNodeSchema)).optional(),\n})\n\nconst physicalSubTreeSchema: z.ZodType<PhysicalSubtree> = z.object({\n type: z.literal('physical'),\n directory: z.string(),\n pathPrefix: z.string(),\n})\n\nconst virtualRouteNodeSchema = z.union([\n indexRouteSchema,\n layoutRouteSchema,\n routeSchema,\n physicalSubTreeSchema,\n])\n\nexport const virtualRootRouteSchema: z.ZodType<VirtualRootRoute> = z.object({\n type: z.literal('root'),\n file: z.string(),\n children: z.array(virtualRouteNodeSchema).optional(),\n})\n"],"mappings":";;;AAQA,IAAM,mBAAmB,IAAA,EAAE,OAAO;CAChC,MAAM,IAAA,EAAE,QAAQ,QAAQ;CACxB,MAAM,IAAA,EAAE,QAAQ;CACjB,CAAC;AAEF,IAAM,oBAA4C,IAAA,EAAE,OAAO;CACzD,MAAM,IAAA,EAAE,QAAQ,SAAS;CACzB,IAAI,IAAA,EAAE,QAAQ,CAAC,UAAU;CACzB,MAAM,IAAA,EAAE,QAAQ;CAChB,UAAU,IAAA,EAAE,MAAM,IAAA,EAAE,WAAW,uBAAuB,CAAC,CAAC,UAAU;CACnE,CAAC;AAEF,IAAM,cAAgC,IAAA,EAAE,OAAO;CAC7C,MAAM,IAAA,EAAE,QAAQ,QAAQ;CACxB,MAAM,IAAA,EAAE,QAAQ,CAAC,UAAU;CAC3B,MAAM,IAAA,EAAE,QAAQ;CAChB,UAAU,IAAA,EAAE,MAAM,IAAA,EAAE,WAAW,uBAAuB,CAAC,CAAC,UAAU;CACnE,CAAC;AAEF,IAAM,wBAAoD,IAAA,EAAE,OAAO;CACjE,MAAM,IAAA,EAAE,QAAQ,WAAW;CAC3B,WAAW,IAAA,EAAE,QAAQ;CACrB,YAAY,IAAA,EAAE,QAAQ;CACvB,CAAC;AAEF,IAAM,yBAAyB,IAAA,EAAE,MAAM;CACrC;CACA;CACA;CACA;CACD,CAAC;AAEF,IAAa,yBAAsD,IAAA,EAAE,OAAO;CAC1E,MAAM,IAAA,EAAE,QAAQ,OAAO;CACvB,MAAM,IAAA,EAAE,QAAQ;CAChB,UAAU,IAAA,EAAE,MAAM,uBAAuB,CAAC,UAAU;CACrD,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { z } from 'zod';
2
+ import { VirtualRootRoute } from '@benjavicente/virtual-file-routes';
3
+ export declare const virtualRootRouteSchema: z.ZodType<VirtualRootRoute>;
@@ -0,0 +1,175 @@
1
+ const require_runtime = require("../../_virtual/_rolldown/runtime.cjs");
2
+ const require_config = require("./config.cjs");
3
+ const require_rootPathId = require("../physical/rootPathId.cjs");
4
+ const require_utils = require("../../utils.cjs");
5
+ const require_loadConfigFile = require("./loadConfigFile.cjs");
6
+ const require_getRouteNodes = require("../physical/getRouteNodes.cjs");
7
+ let node_path = require("node:path");
8
+ node_path = require_runtime.__toESM(node_path);
9
+ //#region src/filesystem/virtual/getRouteNodes.ts
10
+ function ensureLeadingUnderScore(id) {
11
+ if (id.startsWith("_")) return id;
12
+ return `_${id}`;
13
+ }
14
+ function flattenTree(node) {
15
+ const result = [node];
16
+ if (node.children) for (const child of node.children) result.push(...flattenTree(child));
17
+ delete node.children;
18
+ return result;
19
+ }
20
+ async function getRouteNodes(tsrConfig, root, tokenRegexes) {
21
+ const fullDir = (0, node_path.resolve)(tsrConfig.routesDirectory);
22
+ if (tsrConfig.virtualRouteConfig === void 0) throw new Error(`virtualRouteConfig is undefined`);
23
+ let virtualRouteConfig;
24
+ if (typeof tsrConfig.virtualRouteConfig === "string") virtualRouteConfig = await getVirtualRouteConfigFromFileExport(tsrConfig, root);
25
+ else virtualRouteConfig = tsrConfig.virtualRouteConfig;
26
+ const { children, physicalDirectories } = await getRouteNodesRecursive(tsrConfig, root, fullDir, virtualRouteConfig.children, tokenRegexes);
27
+ const allNodes = flattenTree({
28
+ children,
29
+ filePath: virtualRouteConfig.file,
30
+ fullPath: require_utils.replaceBackslash((0, node_path.join)(fullDir, virtualRouteConfig.file)),
31
+ variableName: "root",
32
+ routePath: `/${require_rootPathId.rootPathId}`,
33
+ _fsRouteType: "__root"
34
+ });
35
+ return {
36
+ rootRouteNode: allNodes[0],
37
+ routeNodes: allNodes.slice(1),
38
+ physicalDirectories
39
+ };
40
+ }
41
+ /**
42
+ * Get the virtual route config from a file export
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * // routes.ts
47
+ * import { rootRoute } from '@benjavicente/virtual-file-routes'
48
+ *
49
+ * export const routes = rootRoute({ ... })
50
+ * // or
51
+ * export default rootRoute({ ... })
52
+ * ```
53
+ *
54
+ */
55
+ async function getVirtualRouteConfigFromFileExport(tsrConfig, root) {
56
+ if (tsrConfig.virtualRouteConfig === void 0 || typeof tsrConfig.virtualRouteConfig !== "string" || tsrConfig.virtualRouteConfig === "") throw new Error(`virtualRouteConfig is undefined or empty`);
57
+ const exports = await require_loadConfigFile.loadConfigFile((0, node_path.join)(root, tsrConfig.virtualRouteConfig));
58
+ if (!("routes" in exports) && !("default" in exports)) throw new Error(`routes not found in ${tsrConfig.virtualRouteConfig}. The routes export must be named like 'export const routes = ...' or done using 'export default ...'`);
59
+ const virtualRouteConfig = "routes" in exports ? exports.routes : exports.default;
60
+ return require_config.virtualRootRouteSchema.parse(virtualRouteConfig);
61
+ }
62
+ async function getRouteNodesRecursive(tsrConfig, root, fullDir, nodes, tokenRegexes, parent) {
63
+ if (nodes === void 0) return {
64
+ children: [],
65
+ physicalDirectories: []
66
+ };
67
+ const allPhysicalDirectories = [];
68
+ return {
69
+ children: (await Promise.all(nodes.map(async (node) => {
70
+ if (node.type === "physical") {
71
+ const { routeNodes, physicalDirectories } = await require_getRouteNodes.getRouteNodes({
72
+ ...tsrConfig,
73
+ routesDirectory: (0, node_path.resolve)(fullDir, node.directory)
74
+ }, root, tokenRegexes);
75
+ allPhysicalDirectories.push((0, node_path.resolve)(fullDir, node.directory), ...physicalDirectories);
76
+ routeNodes.forEach((subtreeNode) => {
77
+ subtreeNode.variableName = require_utils.routePathToVariable(`${node.pathPrefix}/${require_utils.removeExt(subtreeNode.filePath)}`);
78
+ subtreeNode.routePath = `${parent?.routePath ?? ""}${node.pathPrefix}${subtreeNode.routePath}`;
79
+ if (subtreeNode.originalRoutePath) subtreeNode.originalRoutePath = `${parent?.routePath ?? ""}${node.pathPrefix}${subtreeNode.originalRoutePath}`;
80
+ subtreeNode.filePath = `${node.directory}/${subtreeNode.filePath}`;
81
+ });
82
+ return routeNodes;
83
+ }
84
+ function getFile(file) {
85
+ const filePath = file;
86
+ return {
87
+ filePath,
88
+ variableName: require_utils.routePathToVariable(require_utils.removeExt(filePath)),
89
+ fullPath: require_utils.replaceBackslash((0, node_path.join)(fullDir, filePath))
90
+ };
91
+ }
92
+ const parentRoutePath = require_utils.removeTrailingSlash(parent?.routePath ?? "/");
93
+ const virtualParentRoutePath = parent?.routePath ?? `/__root`;
94
+ switch (node.type) {
95
+ case "index": {
96
+ const { filePath, variableName, fullPath } = getFile(node.file);
97
+ return {
98
+ filePath,
99
+ fullPath,
100
+ variableName,
101
+ routePath: `${parentRoutePath}/`,
102
+ _fsRouteType: "static",
103
+ _virtualParentRoutePath: virtualParentRoutePath
104
+ };
105
+ }
106
+ case "route": {
107
+ const lastSegment = node.path;
108
+ let routeNode;
109
+ const { routePath: escapedSegment, originalRoutePath: originalSegment } = require_utils.determineInitialRoutePath(require_utils.removeLeadingSlash(lastSegment));
110
+ const routePath = `${parentRoutePath}${escapedSegment}`;
111
+ const originalRoutePath = `${parentRoutePath}${originalSegment}`;
112
+ if (node.file) {
113
+ const { filePath, variableName, fullPath } = getFile(node.file);
114
+ routeNode = {
115
+ filePath,
116
+ fullPath,
117
+ variableName,
118
+ routePath,
119
+ originalRoutePath,
120
+ _fsRouteType: "static",
121
+ _virtualParentRoutePath: virtualParentRoutePath
122
+ };
123
+ } else routeNode = {
124
+ filePath: "",
125
+ fullPath: "",
126
+ variableName: require_utils.routePathToVariable(routePath),
127
+ routePath,
128
+ originalRoutePath,
129
+ isVirtual: true,
130
+ _fsRouteType: "static",
131
+ _virtualParentRoutePath: virtualParentRoutePath
132
+ };
133
+ if (node.children !== void 0) {
134
+ const { children, physicalDirectories } = await getRouteNodesRecursive(tsrConfig, root, fullDir, node.children, tokenRegexes, routeNode);
135
+ routeNode.children = children;
136
+ allPhysicalDirectories.push(...physicalDirectories);
137
+ routeNode._fsRouteType = "layout";
138
+ }
139
+ return routeNode;
140
+ }
141
+ case "layout": {
142
+ const { filePath, variableName, fullPath } = getFile(node.file);
143
+ if (node.id !== void 0) node.id = ensureLeadingUnderScore(node.id);
144
+ else {
145
+ const baseName = node_path.default.basename(filePath);
146
+ const fileNameWithoutExt = node_path.default.parse(baseName).name;
147
+ node.id = ensureLeadingUnderScore(fileNameWithoutExt);
148
+ }
149
+ const lastSegment = node.id;
150
+ const { routePath: escapedSegment, originalRoutePath: originalSegment } = require_utils.determineInitialRoutePath(require_utils.removeLeadingSlash(lastSegment));
151
+ const routeNode = {
152
+ fullPath,
153
+ filePath,
154
+ variableName,
155
+ routePath: `${parentRoutePath}${escapedSegment}`,
156
+ originalRoutePath: `${parentRoutePath}${originalSegment}`,
157
+ _fsRouteType: "pathless_layout",
158
+ _virtualParentRoutePath: virtualParentRoutePath
159
+ };
160
+ if (node.children !== void 0) {
161
+ const { children, physicalDirectories } = await getRouteNodesRecursive(tsrConfig, root, fullDir, node.children, tokenRegexes, routeNode);
162
+ routeNode.children = children;
163
+ allPhysicalDirectories.push(...physicalDirectories);
164
+ }
165
+ return routeNode;
166
+ }
167
+ }
168
+ }))).flat(),
169
+ physicalDirectories: allPhysicalDirectories
170
+ };
171
+ }
172
+ //#endregion
173
+ exports.getRouteNodes = getRouteNodes;
174
+
175
+ //# sourceMappingURL=getRouteNodes.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getRouteNodes.cjs","names":[],"sources":["../../../../src/filesystem/virtual/getRouteNodes.ts"],"sourcesContent":["import path, { join, resolve } from 'node:path'\nimport {\n determineInitialRoutePath,\n removeExt,\n removeLeadingSlash,\n removeTrailingSlash,\n replaceBackslash,\n routePathToVariable,\n} from '../../utils'\nimport { getRouteNodes as getRouteNodesPhysical } from '../physical/getRouteNodes'\nimport { rootPathId } from '../physical/rootPathId'\nimport { virtualRootRouteSchema } from './config'\nimport { loadConfigFile } from './loadConfigFile'\nimport type {\n VirtualRootRoute,\n VirtualRouteNode,\n} from '@benjavicente/virtual-file-routes'\nimport type { GetRouteNodesResult, RouteNode } from '../../types'\nimport type { Config } from '../../config'\nimport type { TokenRegexBundle } from '../physical/getRouteNodes'\n\nfunction ensureLeadingUnderScore(id: string) {\n if (id.startsWith('_')) {\n return id\n }\n return `_${id}`\n}\n\nfunction flattenTree(node: RouteNode): Array<RouteNode> {\n const result = [node]\n\n if (node.children) {\n for (const child of node.children) {\n result.push(...flattenTree(child))\n }\n }\n delete node.children\n\n return result\n}\n\nexport async function getRouteNodes(\n tsrConfig: Pick<\n Config,\n | 'routesDirectory'\n | 'virtualRouteConfig'\n | 'routeFileIgnorePrefix'\n | 'disableLogging'\n | 'indexToken'\n | 'routeToken'\n >,\n root: string,\n tokenRegexes: TokenRegexBundle,\n): Promise<GetRouteNodesResult> {\n const fullDir = resolve(tsrConfig.routesDirectory)\n if (tsrConfig.virtualRouteConfig === undefined) {\n throw new Error(`virtualRouteConfig is undefined`)\n }\n let virtualRouteConfig: VirtualRootRoute\n if (typeof tsrConfig.virtualRouteConfig === 'string') {\n virtualRouteConfig = await getVirtualRouteConfigFromFileExport(\n tsrConfig,\n root,\n )\n } else {\n virtualRouteConfig = tsrConfig.virtualRouteConfig\n }\n const { children, physicalDirectories } = await getRouteNodesRecursive(\n tsrConfig,\n root,\n fullDir,\n virtualRouteConfig.children,\n tokenRegexes,\n )\n const allNodes = flattenTree({\n children,\n filePath: virtualRouteConfig.file,\n fullPath: replaceBackslash(join(fullDir, virtualRouteConfig.file)),\n variableName: 'root',\n routePath: `/${rootPathId}`,\n _fsRouteType: '__root',\n })\n\n const rootRouteNode = allNodes[0]\n const routeNodes = allNodes.slice(1)\n\n return { rootRouteNode, routeNodes, physicalDirectories }\n}\n\n/**\n * Get the virtual route config from a file export\n *\n * @example\n * ```ts\n * // routes.ts\n * import { rootRoute } from '@benjavicente/virtual-file-routes'\n *\n * export const routes = rootRoute({ ... })\n * // or\n * export default rootRoute({ ... })\n * ```\n *\n */\nasync function getVirtualRouteConfigFromFileExport(\n tsrConfig: Pick<Config, 'virtualRouteConfig'>,\n root: string,\n): Promise<VirtualRootRoute> {\n if (\n tsrConfig.virtualRouteConfig === undefined ||\n typeof tsrConfig.virtualRouteConfig !== 'string' ||\n tsrConfig.virtualRouteConfig === ''\n ) {\n throw new Error(`virtualRouteConfig is undefined or empty`)\n }\n const exports = await loadConfigFile(join(root, tsrConfig.virtualRouteConfig))\n\n if (!('routes' in exports) && !('default' in exports)) {\n throw new Error(\n `routes not found in ${tsrConfig.virtualRouteConfig}. The routes export must be named like 'export const routes = ...' or done using 'export default ...'`,\n )\n }\n\n const virtualRouteConfig =\n 'routes' in exports ? exports.routes : exports.default\n\n return virtualRootRouteSchema.parse(virtualRouteConfig)\n}\n\nexport async function getRouteNodesRecursive(\n tsrConfig: Pick<\n Config,\n | 'routesDirectory'\n | 'routeFileIgnorePrefix'\n | 'disableLogging'\n | 'indexToken'\n | 'routeToken'\n >,\n root: string,\n fullDir: string,\n nodes: Array<VirtualRouteNode> | undefined,\n tokenRegexes: TokenRegexBundle,\n parent?: RouteNode,\n): Promise<{ children: Array<RouteNode>; physicalDirectories: Array<string> }> {\n if (nodes === undefined) {\n return { children: [], physicalDirectories: [] }\n }\n const allPhysicalDirectories: Array<string> = []\n const children = await Promise.all(\n nodes.map(async (node) => {\n if (node.type === 'physical') {\n const { routeNodes, physicalDirectories } = await getRouteNodesPhysical(\n {\n ...tsrConfig,\n routesDirectory: resolve(fullDir, node.directory),\n },\n root,\n tokenRegexes,\n )\n allPhysicalDirectories.push(\n resolve(fullDir, node.directory),\n ...physicalDirectories,\n )\n routeNodes.forEach((subtreeNode) => {\n subtreeNode.variableName = routePathToVariable(\n `${node.pathPrefix}/${removeExt(subtreeNode.filePath)}`,\n )\n subtreeNode.routePath = `${parent?.routePath ?? ''}${node.pathPrefix}${subtreeNode.routePath}`\n // Keep originalRoutePath aligned with routePath for escape detection\n if (subtreeNode.originalRoutePath) {\n subtreeNode.originalRoutePath = `${parent?.routePath ?? ''}${node.pathPrefix}${subtreeNode.originalRoutePath}`\n }\n subtreeNode.filePath = `${node.directory}/${subtreeNode.filePath}`\n })\n return routeNodes\n }\n\n function getFile(file: string) {\n const filePath = file\n const variableName = routePathToVariable(removeExt(filePath))\n const fullPath = replaceBackslash(join(fullDir, filePath))\n return { filePath, variableName, fullPath }\n }\n const parentRoutePath = removeTrailingSlash(parent?.routePath ?? '/')\n const virtualParentRoutePath = parent?.routePath ?? `/${rootPathId}`\n\n switch (node.type) {\n case 'index': {\n const { filePath, variableName, fullPath } = getFile(node.file)\n const routePath = `${parentRoutePath}/`\n return {\n filePath,\n fullPath,\n variableName,\n routePath,\n _fsRouteType: 'static',\n _virtualParentRoutePath: virtualParentRoutePath,\n } satisfies RouteNode\n }\n\n case 'route': {\n const lastSegment = node.path\n let routeNode: RouteNode\n\n // Process the segment to handle escape sequences like [_]\n const {\n routePath: escapedSegment,\n originalRoutePath: originalSegment,\n } = determineInitialRoutePath(removeLeadingSlash(lastSegment))\n const routePath = `${parentRoutePath}${escapedSegment}`\n // Store the original path with brackets for escape detection\n const originalRoutePath = `${parentRoutePath}${originalSegment}`\n\n if (node.file) {\n const { filePath, variableName, fullPath } = getFile(node.file)\n routeNode = {\n filePath,\n fullPath,\n variableName,\n routePath,\n originalRoutePath,\n _fsRouteType: 'static',\n _virtualParentRoutePath: virtualParentRoutePath,\n }\n } else {\n routeNode = {\n filePath: '',\n fullPath: '',\n variableName: routePathToVariable(routePath),\n routePath,\n originalRoutePath,\n isVirtual: true,\n _fsRouteType: 'static',\n _virtualParentRoutePath: virtualParentRoutePath,\n }\n }\n\n if (node.children !== undefined) {\n const { children, physicalDirectories } =\n await getRouteNodesRecursive(\n tsrConfig,\n root,\n fullDir,\n node.children,\n tokenRegexes,\n routeNode,\n )\n routeNode.children = children\n allPhysicalDirectories.push(...physicalDirectories)\n\n // If the route has children, it should be a layout\n routeNode._fsRouteType = 'layout'\n }\n return routeNode\n }\n case 'layout': {\n const { filePath, variableName, fullPath } = getFile(node.file)\n\n if (node.id !== undefined) {\n node.id = ensureLeadingUnderScore(node.id)\n } else {\n const baseName = path.basename(filePath)\n const fileNameWithoutExt = path.parse(baseName).name\n node.id = ensureLeadingUnderScore(fileNameWithoutExt)\n }\n const lastSegment = node.id\n // Process the segment to handle escape sequences like [_]\n const {\n routePath: escapedSegment,\n originalRoutePath: originalSegment,\n } = determineInitialRoutePath(removeLeadingSlash(lastSegment))\n const routePath = `${parentRoutePath}${escapedSegment}`\n // Store the original path with brackets for escape detection\n const originalRoutePath = `${parentRoutePath}${originalSegment}`\n\n const routeNode: RouteNode = {\n fullPath,\n filePath,\n variableName,\n routePath,\n originalRoutePath,\n _fsRouteType: 'pathless_layout',\n _virtualParentRoutePath: virtualParentRoutePath,\n }\n\n if (node.children !== undefined) {\n const { children, physicalDirectories } =\n await getRouteNodesRecursive(\n tsrConfig,\n root,\n fullDir,\n node.children,\n tokenRegexes,\n routeNode,\n )\n routeNode.children = children\n allPhysicalDirectories.push(...physicalDirectories)\n }\n return routeNode\n }\n }\n }),\n )\n return {\n children: children.flat(),\n physicalDirectories: allPhysicalDirectories,\n }\n}\n"],"mappings":";;;;;;;;;AAqBA,SAAS,wBAAwB,IAAY;AAC3C,KAAI,GAAG,WAAW,IAAI,CACpB,QAAO;AAET,QAAO,IAAI;;AAGb,SAAS,YAAY,MAAmC;CACtD,MAAM,SAAS,CAAC,KAAK;AAErB,KAAI,KAAK,SACP,MAAK,MAAM,SAAS,KAAK,SACvB,QAAO,KAAK,GAAG,YAAY,MAAM,CAAC;AAGtC,QAAO,KAAK;AAEZ,QAAO;;AAGT,eAAsB,cACpB,WASA,MACA,cAC8B;CAC9B,MAAM,WAAA,GAAA,UAAA,SAAkB,UAAU,gBAAgB;AAClD,KAAI,UAAU,uBAAuB,KAAA,EACnC,OAAM,IAAI,MAAM,kCAAkC;CAEpD,IAAI;AACJ,KAAI,OAAO,UAAU,uBAAuB,SAC1C,sBAAqB,MAAM,oCACzB,WACA,KACD;KAED,sBAAqB,UA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C;MACA;MACA,WAAW;MACX,cAAc;MACd,yBAAyB;MAC1B;AAGH,SAAI,KAAK,aAAa,KAAA,GAAW;MAC/B,MAAM,EAAE,UAAU,wBAChB,MAAM,uBACJ,WACA,MACA,SACA,KAAK,UACL,cACA,UACD;AACH,gBAAU,WAAW;AACrB,6BAAuB,KAAK,GAAG,oBAAoB;AAGnD,gBAAU,eAAe;;AAE3B,YAAO;;IAET,KAAK,UAAU;KACb,MAAM,EAAE,UAAU,cAAc,aAAa,QAAQ,KAAK,KAAK;AAE/D,SAAI,KAAK,OAAO,KAAA,EACd,MAAK,KAAK,wBAAwB,KAAK,GAAG;UACrC;MACL,MAAM,WAAW,UAAA,QAAK,SAAS,SAAS;MACxC,MAAM,qBAAqB,UAAA,QAAK,MAAM,SAAS,CAAC;AAChD,WAAK,KAAK,wBAAwB,mBAAmB;;KAEvD,MAAM,cAAc,KAAK;KAEzB,MAAM,EACJ,WAAW,gBACX,mBAAmB,oBACjB,cAAA,0BAA0B,cAAA,mBAAmB,YAAY,CAAC;KAK9D,MAAM,YAAuB;MAC3B;MACA;MACA;MACA,WARgB,GAAG,kBAAkB;MASrC,mBAPwB,GAAG,kBAAkB;MAQ7C,cAAc;MACd,yBAAyB;MAC1B;AAED,SAAI,KAAK,aAAa,KAAA,GAAW;MAC/B,MAAM,EAAE,UAAU,wBAChB,MAAM,uBACJ,WACA,MACA,SACA,KAAK,UACL,cACA,UACD;AACH,gBAAU,WAAW;AACrB,6BAAuB,KAAK,GAAG,oBAAoB;;AAErD,YAAO;;;IAGX,CACH,EAEoB,MAAM;EACzB,qBAAqB;EACtB"}
@@ -0,0 +1,9 @@
1
+ import { VirtualRouteNode } from '@benjavicente/virtual-file-routes';
2
+ import { GetRouteNodesResult, RouteNode } from '../../types.cjs';
3
+ import { Config } from '../../config.cjs';
4
+ import { TokenRegexBundle } from '../physical/getRouteNodes.cjs';
5
+ export declare function getRouteNodes(tsrConfig: Pick<Config, 'routesDirectory' | 'virtualRouteConfig' | 'routeFileIgnorePrefix' | 'disableLogging' | 'indexToken' | 'routeToken'>, root: string, tokenRegexes: TokenRegexBundle): Promise<GetRouteNodesResult>;
6
+ export declare function getRouteNodesRecursive(tsrConfig: Pick<Config, 'routesDirectory' | 'routeFileIgnorePrefix' | 'disableLogging' | 'indexToken' | 'routeToken'>, root: string, fullDir: string, nodes: Array<VirtualRouteNode> | undefined, tokenRegexes: TokenRegexBundle, parent?: RouteNode): Promise<{
7
+ children: Array<RouteNode>;
8
+ physicalDirectories: Array<string>;
9
+ }>;
@@ -0,0 +1,12 @@
1
+ require("../../_virtual/_rolldown/runtime.cjs");
2
+ let node_url = require("node:url");
3
+ let tsx_esm_api = require("tsx/esm/api");
4
+ //#region src/filesystem/virtual/loadConfigFile.ts
5
+ async function loadConfigFile(filePath) {
6
+ const fileURL = (0, node_url.pathToFileURL)(filePath).href;
7
+ return await (0, tsx_esm_api.tsImport)(fileURL, "./");
8
+ }
9
+ //#endregion
10
+ exports.loadConfigFile = loadConfigFile;
11
+
12
+ //# sourceMappingURL=loadConfigFile.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loadConfigFile.cjs","names":[],"sources":["../../../../src/filesystem/virtual/loadConfigFile.ts"],"sourcesContent":["import { pathToFileURL } from 'node:url'\nimport { tsImport } from 'tsx/esm/api'\n\nexport async function loadConfigFile(filePath: string) {\n const fileURL = pathToFileURL(filePath).href\n const loaded = await tsImport(fileURL, './')\n return loaded\n}\n"],"mappings":";;;;AAGA,eAAsB,eAAe,UAAkB;CACrD,MAAM,WAAA,GAAA,SAAA,eAAwB,SAAS,CAAC;AAExC,QADe,OAAA,GAAA,YAAA,UAAe,SAAS,KAAK"}
@@ -0,0 +1 @@
1
+ export declare function loadConfigFile(filePath: string): Promise<any>;