@tanstack/router-generator 1.167.1 → 1.167.2
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.
- package/dist/cjs/filesystem/physical/getRouteNodes.cjs +4 -1
- package/dist/cjs/filesystem/physical/getRouteNodes.cjs.map +1 -1
- package/dist/cjs/filesystem/virtual/getRouteNodes.cjs +15 -5
- package/dist/cjs/filesystem/virtual/getRouteNodes.cjs.map +1 -1
- package/dist/cjs/generator.cjs +27 -7
- package/dist/cjs/generator.cjs.map +1 -1
- package/dist/cjs/types.d.cts +6 -0
- package/dist/cjs/utils.cjs +120 -38
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +8 -1
- package/dist/esm/filesystem/physical/getRouteNodes.js +5 -2
- package/dist/esm/filesystem/physical/getRouteNodes.js.map +1 -1
- package/dist/esm/filesystem/virtual/getRouteNodes.js +16 -6
- package/dist/esm/filesystem/virtual/getRouteNodes.js.map +1 -1
- package/dist/esm/generator.js +28 -8
- package/dist/esm/generator.js.map +1 -1
- package/dist/esm/types.d.ts +6 -0
- package/dist/esm/utils.d.ts +8 -1
- package/dist/esm/utils.js +115 -37
- package/dist/esm/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/filesystem/physical/getRouteNodes.ts +13 -0
- package/src/filesystem/virtual/getRouteNodes.ts +32 -6
- package/src/generator.ts +67 -19
- package/src/types.ts +7 -0
- package/src/utils.ts +225 -23
|
@@ -54,8 +54,10 @@ async function getRouteNodes(config, root, tokenRegexes) {
|
|
|
54
54
|
virtualRouteNodes.forEach((node) => {
|
|
55
55
|
const normalizedDir = dir === "./" ? "" : dir;
|
|
56
56
|
const filePath = require_utils.replaceBackslash(node_path.default.join(normalizedDir, node.filePath));
|
|
57
|
+
const prefixPath = require_utils.cleanPath(`/${normalizedDir}`);
|
|
57
58
|
const routePath = require_utils.cleanPath(`/${normalizedDir}${node.routePath}`);
|
|
58
59
|
node.variableName = require_utils.routePathToVariable(require_utils.cleanPath(`/${normalizedDir}/${require_utils.removeExt(node.filePath)}`));
|
|
60
|
+
node._routePathSegmentMetadata = require_utils.joinRoutePathSegmentMetadata(routePath, prefixPath, void 0, node._routePathSegmentMetadata);
|
|
59
61
|
node.routePath = routePath;
|
|
60
62
|
if (node.originalRoutePath) node.originalRoutePath = require_utils.cleanPath(`/${normalizedDir}${node.originalRoutePath}`);
|
|
61
63
|
node.filePath = filePath;
|
|
@@ -144,7 +146,8 @@ async function getRouteNodes(config, root, tokenRegexes) {
|
|
|
144
146
|
routePath,
|
|
145
147
|
variableName,
|
|
146
148
|
_fsRouteType: routeType,
|
|
147
|
-
originalRoutePath
|
|
149
|
+
originalRoutePath,
|
|
150
|
+
_routePathSegmentMetadata: require_utils.createRoutePathSegmentMetadata(routePath, originalRoutePath)
|
|
148
151
|
});
|
|
149
152
|
}
|
|
150
153
|
}));
|
|
@@ -1 +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 cleanPath,\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 '@tanstack/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 normalizedDir = dir === './' ? '' : dir\n const filePath = replaceBackslash(\n path.join(normalizedDir, node.filePath),\n )\n const routePath = cleanPath(`/${normalizedDir}${node.routePath}`)\n\n node.variableName = routePathToVariable(\n cleanPath(`/${normalizedDir}/${removeExt(node.filePath)}`),\n )\n node.routePath = routePath\n // Keep originalRoutePath aligned with routePath for escape detection\n if (node.originalRoutePath) {\n node.originalRoutePath = cleanPath(\n `/${normalizedDir}${node.originalRoutePath}`,\n )\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\n }\n\n return (\n !indexTokenSegmentRegex.test(lastRouteSegment) &&\n !routeTokenSegmentRegex.test(lastRouteSegment) &&\n lastRouteSegment.startsWith('_')\n )\n}\n"],"mappings":";;;;;;;;;;;AAiCA,IAAM,oCAAoC;AAE1C,IAAM,0BAA0B;AAChC,SAAgB,oBAAoB,UAA2B;AAC7D,QAAO,wBAAwB,KAAK,SAAS;;AAG/C,eAAsB,cACpB,QAUA,MACA,cAC8B;CAC9B,MAAM,EAAE,iBAAiB,uBAAuB,2BAC9C;CAEF,MAAM,SAAS,eAAA,QAAQ,EAAE,UAAU,OAAO,gBAAgB,CAAC;CAC3D,MAAM,wBAAwB,IAAI,OAAO,0BAA0B,IAAI,IAAI;CAE3E,MAAM,aAA+B,EAAE;CACvC,MAAM,yBAAwC,EAAE;CAEhD,eAAe,QAAQ,KAAa;EAClC,MAAM,UAAU,UAAA,QAAK,QAAQ,OAAO,iBAAiB,IAAI;EACzD,IAAI,UAAU,MAAM,iBAAI,QAAQ,SAAS,EAAE,eAAe,MAAM,CAAC;AAEjE,YAAU,QAAQ,QAAQ,MAAM;AAC9B,OACE,EAAE,KAAK,WAAW,IAAI,IACrB,yBAAyB,EAAE,KAAK,WAAW,sBAAsB,CAElE,QAAO;AAGT,OAAI,iBAAiB;AACnB,QAAI,uBACF,QACE,EAAE,KAAK,WAAW,gBAAgB,IAClC,CAAC,EAAE,KAAK,MAAM,sBAAsB;AAIxC,WAAO,EAAE,KAAK,WAAW,gBAAgB;;AAG3C,OAAI,uBACF,QAAO,CAAC,EAAE,KAAK,MAA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oB,CAClD,QAAO;AAGT,QACE,CAAC,uBAAuB,KAAK,iBAAiB,IAC9C,CAAC,uBAAuB,KAAK,iBAAiB,IAC9C,iBAAiB,WAAW,IAAI"}
|
|
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 cleanPath,\n createRoutePathSegmentMetadata,\n determineInitialRoutePath,\n escapeRegExp,\n hasEscapedLeadingUnderscore,\n joinRoutePathSegmentMetadata,\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 '@tanstack/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 normalizedDir = dir === './' ? '' : dir\n const filePath = replaceBackslash(\n path.join(normalizedDir, node.filePath),\n )\n const prefixPath = cleanPath(`/${normalizedDir}`)\n const routePath = cleanPath(`/${normalizedDir}${node.routePath}`)\n\n node.variableName = routePathToVariable(\n cleanPath(`/${normalizedDir}/${removeExt(node.filePath)}`),\n )\n node._routePathSegmentMetadata = joinRoutePathSegmentMetadata(\n routePath,\n prefixPath,\n undefined,\n node._routePathSegmentMetadata,\n )\n node.routePath = routePath\n // Keep originalRoutePath aligned with routePath for escape detection\n if (node.originalRoutePath) {\n node.originalRoutePath = cleanPath(\n `/${normalizedDir}${node.originalRoutePath}`,\n )\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 _routePathSegmentMetadata: createRoutePathSegmentMetadata(\n routePath,\n originalRoutePath,\n ),\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\n }\n\n return (\n !indexTokenSegmentRegex.test(lastRouteSegment) &&\n !routeTokenSegmentRegex.test(lastRouteSegment) &&\n lastRouteSegment.startsWith('_')\n )\n}\n"],"mappings":";;;;;;;;;;;AAmCA,IAAM,oCAAoC;AAE1C,IAAM,0BAA0B;AAChC,SAAgB,oBAAoB,UAA2B;AAC7D,QAAO,wBAAwB,KAAK,SAAS;;AAG/C,eAAsB,cACpB,QAUA,MACA,cAC8B;CAC9B,MAAM,EAAE,iBAAiB,uBAAuB,2BAC9C;CAEF,MAAM,SAAS,eAAA,QAAQ,EAAE,UAAU,OAAO,gBAAgB,CAAC;CAC3D,MAAM,wBAAwB,IAAI,OAAO,0BAA0B,IAAI,IAAI;CAE3E,MAAM,aAA+B,EAAE;CACvC,MAAM,yBAAwC,EAAE;CAEhD,eAAe,QAAQ,KAAa;EAClC,MAAM,UAAU,UAAA,QAAK,QAAQ,OAAO,iBAAiB,IAAI;EACzD,IAAI,UAAU,MAAM,iBAAI,QAAQ,SAAS,EAAE,eAAe,MAAM,CAAC;AAEjE,YAAU,QAAQ,QAAQ,MAAM;AAC9B,OACE,EAAE,KAAK,WAAW,IAAI,IACrB,yBAAyB,EAAE,KAAK,WAAW,sBAAsB,CAElE,QAAO;AAGT,OAAI,iBAAiB;AACnB,QAAI,uBACF,QACE,EAAE,KAAK,WAAW,gBAAgB,IAClC,CAAC,EAAE,KAAK,MAAM,sBAAsB;AAIxC,WAAO,EAAE,KAAK,WAAW,gBAAgB;;AAG3C,OAAI,uBACF,QAAO,CAAC,EAAE,KAAK,MAAM,sBAAsB;AAG7C,UAAO;IACP;EAEF,MAAM,oBAAoB,QAAQ,MAAM,WAAW;AACjD,UAAO,OAAO,QAAQ,IAAI,oBAAoB,OAAO,KAAK;IAC1D;AAEF,MAAI,sBAAsB,KAAA,GAAW;GACnC,MAAM,2BAA2B,MAAM,uBAAA,eACrC,UAAA,QAAK,QAAQ,SAAS,kB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AK,iBAAiB,IAC9C,iBAAiB,WAAW,IAAI"}
|
|
@@ -74,9 +74,13 @@ async function getRouteNodesRecursive(tsrConfig, root, fullDir, nodes, tokenRege
|
|
|
74
74
|
}, root, tokenRegexes);
|
|
75
75
|
allPhysicalDirectories.push((0, node_path.resolve)(fullDir, node.directory), ...physicalDirectories);
|
|
76
76
|
routeNodes.forEach((subtreeNode) => {
|
|
77
|
+
const pathPrefix = require_utils.cleanPath(`${parent?.routePath ?? ""}${node.pathPrefix}`);
|
|
78
|
+
const literalPathPrefixSegments = require_utils.createLiteralRoutePathSegmentMetadata(pathPrefix, parent, true);
|
|
79
|
+
const routePath = require_utils.cleanPath(`${pathPrefix}${subtreeNode.routePath}`);
|
|
77
80
|
subtreeNode.variableName = require_utils.routePathToVariable(`${node.pathPrefix}/${require_utils.removeExt(subtreeNode.filePath)}`);
|
|
78
|
-
subtreeNode.
|
|
79
|
-
|
|
81
|
+
subtreeNode._routePathSegmentMetadata = require_utils.joinRoutePathSegmentMetadata(routePath, pathPrefix, literalPathPrefixSegments, subtreeNode._routePathSegmentMetadata);
|
|
82
|
+
subtreeNode.routePath = routePath;
|
|
83
|
+
if (subtreeNode.originalRoutePath) subtreeNode.originalRoutePath = require_utils.cleanPath(`${parent?.originalRoutePath ?? parent?.routePath ?? ""}${node.pathPrefix}${subtreeNode.originalRoutePath}`);
|
|
80
84
|
subtreeNode.filePath = `${node.directory}/${subtreeNode.filePath}`;
|
|
81
85
|
});
|
|
82
86
|
return routeNodes;
|
|
@@ -90,6 +94,7 @@ async function getRouteNodesRecursive(tsrConfig, root, fullDir, nodes, tokenRege
|
|
|
90
94
|
};
|
|
91
95
|
}
|
|
92
96
|
const parentRoutePath = require_utils.removeTrailingSlash(parent?.routePath ?? "/");
|
|
97
|
+
const parentOriginalRoutePath = require_utils.removeTrailingSlash(parent?.originalRoutePath ?? parent?.routePath ?? "/");
|
|
93
98
|
const virtualParentRoutePath = parent?.routePath ?? `/__root`;
|
|
94
99
|
switch (node.type) {
|
|
95
100
|
case "index": {
|
|
@@ -108,7 +113,8 @@ async function getRouteNodesRecursive(tsrConfig, root, fullDir, nodes, tokenRege
|
|
|
108
113
|
let routeNode;
|
|
109
114
|
const { routePath: escapedSegment, originalRoutePath: originalSegment } = require_utils.determineInitialRoutePath(require_utils.removeLeadingSlash(lastSegment));
|
|
110
115
|
const routePath = `${parentRoutePath}${escapedSegment}`;
|
|
111
|
-
const originalRoutePath = `${
|
|
116
|
+
const originalRoutePath = `${parentOriginalRoutePath}${originalSegment}`;
|
|
117
|
+
const routePathSegmentMetadata = require_utils.createLiteralRoutePathSegmentMetadata(routePath, parent, true);
|
|
112
118
|
if (node.file) {
|
|
113
119
|
const { filePath, variableName, fullPath } = getFile(node.file);
|
|
114
120
|
routeNode = {
|
|
@@ -117,6 +123,7 @@ async function getRouteNodesRecursive(tsrConfig, root, fullDir, nodes, tokenRege
|
|
|
117
123
|
variableName,
|
|
118
124
|
routePath,
|
|
119
125
|
originalRoutePath,
|
|
126
|
+
_routePathSegmentMetadata: routePathSegmentMetadata,
|
|
120
127
|
_fsRouteType: "static",
|
|
121
128
|
_virtualParentRoutePath: virtualParentRoutePath
|
|
122
129
|
};
|
|
@@ -126,6 +133,7 @@ async function getRouteNodesRecursive(tsrConfig, root, fullDir, nodes, tokenRege
|
|
|
126
133
|
variableName: require_utils.routePathToVariable(routePath),
|
|
127
134
|
routePath,
|
|
128
135
|
originalRoutePath,
|
|
136
|
+
_routePathSegmentMetadata: routePathSegmentMetadata,
|
|
129
137
|
isVirtual: true,
|
|
130
138
|
_fsRouteType: "static",
|
|
131
139
|
_virtualParentRoutePath: virtualParentRoutePath
|
|
@@ -148,12 +156,14 @@ async function getRouteNodesRecursive(tsrConfig, root, fullDir, nodes, tokenRege
|
|
|
148
156
|
}
|
|
149
157
|
const lastSegment = node.id;
|
|
150
158
|
const { routePath: escapedSegment, originalRoutePath: originalSegment } = require_utils.determineInitialRoutePath(require_utils.removeLeadingSlash(lastSegment));
|
|
159
|
+
const routePath = `${parentRoutePath}${escapedSegment}`;
|
|
151
160
|
const routeNode = {
|
|
152
161
|
fullPath,
|
|
153
162
|
filePath,
|
|
154
163
|
variableName,
|
|
155
|
-
routePath
|
|
156
|
-
originalRoutePath: `${
|
|
164
|
+
routePath,
|
|
165
|
+
originalRoutePath: `${parentOriginalRoutePath}${originalSegment}`,
|
|
166
|
+
_routePathSegmentMetadata: require_utils.joinRoutePathSegmentMetadata(routePath, parentRoutePath, parent?._routePathSegmentMetadata, require_utils.createRoutePathSegmentMetadata(escapedSegment, originalSegment)),
|
|
157
167
|
_fsRouteType: "pathless_layout",
|
|
158
168
|
_virtualParentRoutePath: virtualParentRoutePath
|
|
159
169
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getRouteNodes.cjs","names":[],"sources":["../../../../src/filesystem/virtual/getRouteNodes.ts"],"sourcesContent":["import path, { join, resolve } from 'node:path'\nimport {\n cleanPath,\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 '@tanstack/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 '@tanstack/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 = cleanPath(\n `${parent?.routePath ?? ''}${node.pathPrefix}${subtreeNode.routePath}`,\n )\n // Keep originalRoutePath aligned with routePath for escape detection\n if (subtreeNode.originalRoutePath) {\n subtreeNode.originalRoutePath = cleanPath(\n `${parent?.routePath ?? ''}${node.pathPrefix}${subtreeNode.originalRoutePath}`,\n )\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":";;;;;;;;;AAsBA,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,UAAU;CAEjC,MAAM,EAAE,UAAU,wBAAwB,MAAM,uBAC9C,WACA,MACA,SACA,mBAAmB,UACnB,aACD;CACD,MAAM,WAAW,YAAY;EAC3B;EACA,UAAU,mBAAmB;EAC7B,UAAU,cAAA,kBAAA,GAAA,UAAA,MAAsB,SAAS,mBAAmB,KAAK,CAAC;EAClE,cAAc;EACd,WAAW,IAAI,mBAAA;EACf,cAAc;EACf,CAAC;AAKF,QAAO;EAAE,eAHa,SAAS;EAGP,YAFL,SAAS,MAAM,EAAE;EAEA;EAAqB;;;;;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,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"}
|
|
1
|
+
{"version":3,"file":"getRouteNodes.cjs","names":[],"sources":["../../../../src/filesystem/virtual/getRouteNodes.ts"],"sourcesContent":["import path, { join, resolve } from 'node:path'\nimport {\n cleanPath,\n createLiteralRoutePathSegmentMetadata,\n createRoutePathSegmentMetadata,\n determineInitialRoutePath,\n joinRoutePathSegmentMetadata,\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 '@tanstack/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 '@tanstack/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 const pathPrefix = cleanPath(\n `${parent?.routePath ?? ''}${node.pathPrefix}`,\n )\n const literalPathPrefixSegments =\n createLiteralRoutePathSegmentMetadata(pathPrefix, parent, true)\n const routePath = cleanPath(`${pathPrefix}${subtreeNode.routePath}`)\n subtreeNode.variableName = routePathToVariable(\n `${node.pathPrefix}/${removeExt(subtreeNode.filePath)}`,\n )\n subtreeNode._routePathSegmentMetadata = joinRoutePathSegmentMetadata(\n routePath,\n pathPrefix,\n literalPathPrefixSegments,\n subtreeNode._routePathSegmentMetadata,\n )\n subtreeNode.routePath = routePath\n // Keep originalRoutePath aligned with routePath for escape detection\n if (subtreeNode.originalRoutePath) {\n subtreeNode.originalRoutePath = cleanPath(\n `${parent?.originalRoutePath ?? parent?.routePath ?? ''}${node.pathPrefix}${subtreeNode.originalRoutePath}`,\n )\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 parentOriginalRoutePath = removeTrailingSlash(\n parent?.originalRoutePath ?? parent?.routePath ?? '/',\n )\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 const originalRoutePath = `${parentOriginalRoutePath}${originalSegment}`\n const routePathSegmentMetadata =\n createLiteralRoutePathSegmentMetadata(routePath, parent, true)\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 _routePathSegmentMetadata: routePathSegmentMetadata,\n _fsRouteType: 'static',\n _virtualParentRoutePath: virtualParentRoutePath,\n }\n } else {\n routeNode = {\n filePath: '',\n fullPath: '',\n variableName: routePathToVariable(routePath),\n routePath,\n originalRoutePath,\n _routePathSegmentMetadata: routePathSegmentMetadata,\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 = `${parentOriginalRoutePath}${originalSegment}`\n const routePathSegmentMetadata = joinRoutePathSegmentMetadata(\n routePath,\n parentRoutePath,\n parent?._routePathSegmentMetadata,\n createRoutePathSegmentMetadata(escapedSegment, originalSegment),\n )\n\n const routeNode: RouteNode = {\n fullPath,\n filePath,\n variableName,\n routePath,\n originalRoutePath,\n _routePathSegmentMetadata: routePathSegmentMetadata,\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":";;;;;;;;;AAyBA,SAAS,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AO,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;KAC9D,MAAM,YAAY,GAAG,kBAAkB;KAUvC,MAAM,YAAuB;MAC3B;MACA;MACA;MACA;MACA,mBAbwB,GAAG,0BAA0B;MAcrD,2BAb+B,cAAA,6BAC/B,WACA,iBACA,QAAQ,2BACR,cAAA,+BAA+B,gBAAgB,gBAAgB,CAChE;MASC,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"}
|
package/dist/cjs/generator.cjs
CHANGED
|
@@ -16,6 +16,22 @@ let node_crypto = require("node:crypto");
|
|
|
16
16
|
node_crypto = require_runtime.__toESM(node_crypto);
|
|
17
17
|
let _tanstack_router_core = require("@tanstack/router-core");
|
|
18
18
|
//#region src/generator.ts
|
|
19
|
+
function getRoutePathSegmentMetadataForPath(node, routePath, parentRoutePath) {
|
|
20
|
+
if (!node._routePathSegmentMetadata) return void 0;
|
|
21
|
+
const segments = routePath.split("/");
|
|
22
|
+
const result = new Array(segments.length);
|
|
23
|
+
const parentSegmentCount = require_utils.countRoutePathSegments(parentRoutePath);
|
|
24
|
+
let hasMetadata = false;
|
|
25
|
+
let segmentCount = 0;
|
|
26
|
+
for (let i = 0; i < segments.length; i++) {
|
|
27
|
+
if (!segments[i]) continue;
|
|
28
|
+
const sourceIndex = parentSegmentCount + segmentCount + 1;
|
|
29
|
+
result[i] = node._routePathSegmentMetadata[sourceIndex];
|
|
30
|
+
hasMetadata ||= !!result[i];
|
|
31
|
+
segmentCount++;
|
|
32
|
+
}
|
|
33
|
+
return hasMetadata ? result : void 0;
|
|
34
|
+
}
|
|
19
35
|
var DefaultFileSystem = {
|
|
20
36
|
stat: async (filePath) => {
|
|
21
37
|
const res = await node_fs_promises.stat(filePath, { bigint: true });
|
|
@@ -157,7 +173,7 @@ var Generator = class Generator {
|
|
|
157
173
|
await this.handleRootNode(rootRouteNode);
|
|
158
174
|
const preRouteNodes = require_utils.multiSortBy(beforeRouteNodes, [
|
|
159
175
|
(d) => d.routePath === "/" ? -1 : 1,
|
|
160
|
-
(d) => d.routePath
|
|
176
|
+
(d) => d.routePath === void 0 ? void 0 : require_utils.countSlashSeparatedParts(d.routePath),
|
|
161
177
|
(d) => d.filePath.match(this.indexTokenFilenameRegex) ? 1 : -1,
|
|
162
178
|
(d) => d.filePath.match(Generator.componentPieceRegex) ? 1 : -1,
|
|
163
179
|
(d) => d.filePath.match(this.routeTokenFilenameRegex) ? -1 : 1,
|
|
@@ -277,7 +293,7 @@ var Generator = class Generator {
|
|
|
277
293
|
const indexTokenSegmentRegex = config.indexToken === this.config.indexToken ? this.indexTokenSegmentRegex : require_utils.createTokenRegex(config.indexToken, { type: "segment" });
|
|
278
294
|
const sortedRouteNodes = require_utils.multiSortBy(acc.routeNodes, [
|
|
279
295
|
(d) => d.routePath?.includes(`/__root`) ? -1 : 1,
|
|
280
|
-
(d) => d.routePath
|
|
296
|
+
(d) => d.routePath === void 0 ? void 0 : require_utils.countSlashSeparatedParts(d.routePath),
|
|
281
297
|
(d) => {
|
|
282
298
|
const segments = d.routePath?.split("/").filter(Boolean) ?? [];
|
|
283
299
|
const last = segments[segments.length - 1] ?? "";
|
|
@@ -692,11 +708,16 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${require_uti
|
|
|
692
708
|
if (parentRoute) node.parent = parentRoute;
|
|
693
709
|
node.path = require_utils.determineNodePath(node);
|
|
694
710
|
const trimmedPath = require_utils.trimPathLeft(node.path ?? "");
|
|
695
|
-
const
|
|
711
|
+
const originalPath = node.originalRoutePath && node.parent?.originalRoutePath ? node.originalRoutePath.replace(node.parent.originalRoutePath, "") || "/" : node.originalRoutePath;
|
|
712
|
+
const routePathSegmentMetadata = getRoutePathSegmentMetadataForPath(node, node.path ?? "/", node.parent?.routePath);
|
|
713
|
+
const trimmedOriginalPath = require_utils.trimPathLeft(originalPath ?? "");
|
|
696
714
|
const split = trimmedPath.split("/");
|
|
715
|
+
const pathSplit = (node.path ?? "").split("/");
|
|
697
716
|
const originalSplit = trimmedOriginalPath.split("/");
|
|
698
|
-
|
|
699
|
-
|
|
717
|
+
const lastRouteSegment = split[split.length - 1] ?? trimmedPath;
|
|
718
|
+
const lastOriginalSegment = originalSplit[originalSplit.length - 1] ?? trimmedOriginalPath;
|
|
719
|
+
node.isNonPath = !(routePathSegmentMetadata?.[pathSplit.length - 1])?.literalLeadingUnderscore && require_utils.isSegmentPathless(lastRouteSegment, lastOriginalSegment) || split.every((part) => this.routeGroupPatternRegex.test(part));
|
|
720
|
+
node.cleanedPath = require_utils.removeGroups(require_utils.removeLayoutSegmentsAndUnderscoresWithEscape(node.path, originalPath, routePathSegmentMetadata));
|
|
700
721
|
if (node._fsRouteType === "layout" || node._fsRouteType === "pathless_layout") node.cleanedPath = require_utils.removeTrailingSlash(node.cleanedPath);
|
|
701
722
|
if (!node.isVirtual && [
|
|
702
723
|
"lazy",
|
|
@@ -727,8 +748,7 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${require_uti
|
|
|
727
748
|
node.parent = candidate;
|
|
728
749
|
node.path = node.routePath?.replace(candidate.routePath ?? "", "") || "/";
|
|
729
750
|
const pathRelativeToParent = immediateParentPath.replace(candidate.routePath ?? "", "") || "/";
|
|
730
|
-
|
|
731
|
-
node.cleanedPath = require_utils.removeGroups(require_utils.removeUnderscoresWithEscape(require_utils.removeLayoutSegmentsWithEscape(pathRelativeToParent, originalPathRelativeToParent), originalPathRelativeToParent));
|
|
751
|
+
node.cleanedPath = require_utils.removeGroups(require_utils.removeLayoutSegmentsAndUnderscoresWithEscape(pathRelativeToParent, immediateParentOriginalPath.replace(candidate.originalRoutePath ?? "", "") || "/", getRoutePathSegmentMetadataForPath(node, pathRelativeToParent, candidate.routePath)));
|
|
732
752
|
break;
|
|
733
753
|
}
|
|
734
754
|
if (searchPath === "/") break;
|