@tanstack/start-plugin-core 1.120.4-alpha.2 → 1.120.4-alpha.21
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/constants.cjs +10 -0
- package/dist/cjs/constants.cjs.map +1 -0
- package/dist/cjs/constants.d.cts +4 -0
- package/dist/cjs/nitro/dev-server-plugin.cjs +11 -3
- package/dist/cjs/nitro/dev-server-plugin.cjs.map +1 -1
- package/dist/cjs/nitro/nitro-plugin.cjs +24 -5
- package/dist/cjs/nitro/nitro-plugin.cjs.map +1 -1
- package/dist/cjs/plugin.cjs +49 -15
- package/dist/cjs/plugin.cjs.map +1 -1
- package/dist/cjs/plugin.d.cts +620 -1
- package/dist/cjs/prerender.cjs +19 -15
- package/dist/cjs/prerender.cjs.map +1 -1
- package/dist/cjs/schema.cjs +21 -2
- package/dist/cjs/schema.cjs.map +1 -1
- package/dist/cjs/schema.d.cts +2281 -520
- package/dist/cjs/start-server-routes-plugin/plugin.cjs +6 -2
- package/dist/cjs/start-server-routes-plugin/plugin.cjs.map +1 -1
- package/dist/esm/constants.d.ts +4 -0
- package/dist/esm/constants.js +10 -0
- package/dist/esm/constants.js.map +1 -0
- package/dist/esm/nitro/dev-server-plugin.js +11 -3
- package/dist/esm/nitro/dev-server-plugin.js.map +1 -1
- package/dist/esm/nitro/nitro-plugin.js +24 -5
- package/dist/esm/nitro/nitro-plugin.js.map +1 -1
- package/dist/esm/plugin.d.ts +620 -1
- package/dist/esm/plugin.js +49 -15
- package/dist/esm/plugin.js.map +1 -1
- package/dist/esm/prerender.js +19 -15
- package/dist/esm/prerender.js.map +1 -1
- package/dist/esm/schema.d.ts +2281 -520
- package/dist/esm/schema.js +21 -2
- package/dist/esm/schema.js.map +1 -1
- package/dist/esm/start-server-routes-plugin/plugin.js +6 -2
- package/dist/esm/start-server-routes-plugin/plugin.js.map +1 -1
- package/package.json +11 -5
- package/src/constants.ts +6 -0
- package/src/nitro/dev-server-plugin.ts +14 -4
- package/src/nitro/nitro-plugin.ts +28 -3
- package/src/plugin.ts +64 -15
- package/src/prerender.ts +26 -19
- package/src/schema.ts +26 -1
- package/src/start-server-routes-plugin/plugin.ts +10 -2
|
@@ -162,7 +162,7 @@ Add the file in: "${config.routesDirectory}/${routerGenerator.rootPathId}.tsx"`;
|
|
|
162
162
|
node.cleanedPath = removeGroups(
|
|
163
163
|
routerGenerator.removeUnderscores(removeLayoutSegments(node.path)) ?? ""
|
|
164
164
|
);
|
|
165
|
-
const routeCode = fs.readFileSync(node.fullPath, "utf-8");
|
|
165
|
+
const routeCode = node.fullPath ? fs.readFileSync(node.fullPath, "utf-8") : "";
|
|
166
166
|
if (!node.isVirtualParentRoute && !node.isVirtual) ;
|
|
167
167
|
const cleanedPathIsEmpty = (node.cleanedPath || "").length === 0;
|
|
168
168
|
const nonPathRoute = node._fsRouteType === "pathless_layout" && node.isNonPath;
|
|
@@ -491,7 +491,11 @@ ${((_a = routeNode.children) == null ? void 0 : _a.length) ? `${routeNode.variab
|
|
|
491
491
|
function buildStartDeclarationFile({
|
|
492
492
|
serverRoutesRelativePath
|
|
493
493
|
}) {
|
|
494
|
-
|
|
494
|
+
const serverRoutesPath = routerGenerator.replaceBackslash(serverRoutesRelativePath);
|
|
495
|
+
return [
|
|
496
|
+
'/// <reference types="vite/client" />',
|
|
497
|
+
`import '${serverRoutesPath}'`
|
|
498
|
+
].join("\n") + "\n";
|
|
495
499
|
}
|
|
496
500
|
function removeGroups(s) {
|
|
497
501
|
return s.replace(possiblyNestedRouteGroupPatternRegex, "");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.cjs","sources":["../../../src/start-server-routes-plugin/plugin.ts"],"sourcesContent":["import path, { isAbsolute, join, normalize } from 'node:path'\nimport fs from 'node:fs'\nimport fsp from 'node:fs/promises'\nimport {\n format,\n logging,\n multiSortBy,\n physicalGetRouteNodes,\n removeExt,\n removeUnderscores,\n replaceBackslash,\n resetRegex,\n rootPathId,\n routePathToVariable,\n trimPathLeft,\n virtualGetRouteNodes,\n writeIfDifferent,\n} from '@tanstack/router-generator'\nimport { rootRouteId } from '@tanstack/router-core'\nimport { fillTemplate, getTargetTemplate } from './template'\nimport type { GetRouteNodesResult, RouteNode } from '@tanstack/router-generator'\nimport type { Config } from './config'\nimport type { Plugin } from 'vite'\n\nlet lock = false\nconst checkLock = () => lock\nconst setLock = (bool: boolean) => {\n lock = bool\n}\n\nexport function TanStackStartServerRoutesVite(config: Config): Plugin {\n let ROOT: string = process.cwd()\n\n const getRoutesDirectoryPath = () => {\n return isAbsolute(config.routesDirectory)\n ? config.routesDirectory\n : join(ROOT, config.routesDirectory)\n }\n\n const generate = async () => {\n if (checkLock()) {\n return\n }\n\n setLock(true)\n\n try {\n await generator(config, ROOT)\n } catch (err) {\n console.error(err)\n console.info()\n } finally {\n setLock(false)\n }\n }\n\n const handleFile = async (file: string) => {\n const filePath = normalize(file)\n\n const routesDirectoryPath = getRoutesDirectoryPath()\n if (filePath.startsWith(routesDirectoryPath)) {\n await generate()\n }\n }\n\n return {\n name: 'tanstack-start-server-routes-plugin',\n configureServer(server) {\n server.watcher.on('all', (event, path) => {\n handleFile(path)\n })\n },\n configResolved(config) {\n ROOT = config.root\n },\n async buildStart() {\n await generate()\n // if (this.environment.name === 'server') {\n // }\n },\n sharedDuringBuild: true,\n resolveId(id) {\n if (id === 'tanstack:server-routes') {\n const generatedRouteTreePath = getGeneratedRouteTreePath(ROOT)\n return generatedRouteTreePath\n }\n return null\n },\n }\n}\n\n// Maybe import this from `@tanstack/router-core` in the future???\nlet latestTask = 0\nconst routeGroupPatternRegex = /\\(.+\\)/g\nconst possiblyNestedRouteGroupPatternRegex = /\\([^/]+\\)\\/?/g\n\nlet isFirst = false\nlet skipMessage = false\n\nfunction getGeneratedRouteTreePath(root: string) {\n return path.resolve(root, '.tanstack-start/server-routes/routeTree.gen.ts')\n}\n\nasync function generator(config: Config, root: string) {\n const generatedServerRouteTreePath = getGeneratedRouteTreePath(root)\n const ROUTE_TEMPLATE = getTargetTemplate(config.target)\n const logger = logging({ disabled: config.disableLogging })\n\n if (!isFirst) {\n // logger.log('♻️ Generating server routes...')\n isFirst = true\n } else if (skipMessage) {\n skipMessage = false\n } else {\n // logger.log('♻️ Regenerating server routes...')\n }\n\n const taskId = latestTask + 1\n latestTask = taskId\n\n const checkLatest = () => {\n if (latestTask !== taskId) {\n skipMessage = true\n return false\n }\n\n return true\n }\n\n const start = Date.now()\n\n let getRouteNodesResult: GetRouteNodesResult\n\n if (config.virtualRouteConfig) {\n getRouteNodesResult = await virtualGetRouteNodes(config, root)\n } else {\n getRouteNodesResult = await physicalGetRouteNodes(config, root)\n }\n\n const { rootRouteNode, routeNodes: beforeRouteNodes } = getRouteNodesResult\n if (rootRouteNode === undefined) {\n let errorMessage = `rootRouteNode must not be undefined. Make sure you've added your root route into the route-tree.`\n if (!config.virtualRouteConfig) {\n errorMessage += `\\nMake sure that you add a \"${rootPathId}.tsx\" file to your routes directory.\\nAdd the file in: \"${config.routesDirectory}/${rootPathId}.tsx\"`\n }\n throw new Error(errorMessage)\n }\n\n const preRouteNodes = multiSortBy(beforeRouteNodes, [\n (d) => (d.routePath === '/' ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) =>\n d.filePath.match(new RegExp(`[./]${config.indexToken}[.]`)) ? 1 : -1,\n (d) =>\n d.filePath.match(\n /[./](component|errorComponent|pendingComponent|loader|lazy)[.]/,\n )\n ? 1\n : -1,\n (d) =>\n d.filePath.match(new RegExp(`[./]${config.routeToken}[.]`)) ? -1 : 1,\n (d) => (d.routePath?.endsWith('/') ? -1 : 1),\n (d) => d.routePath,\n ]).filter((d) => ![`/${rootPathId}`].includes(d.routePath || ''))\n\n const routeTree: Array<RouteNode> = []\n\n // Loop over the flat list of routeNodes and\n // build up a tree based on the routeNodes' routePath\n const routeNodes: Array<RouteNode> = []\n\n // the handleRootNode function is not being collapsed into the handleNode function\n // because it requires only a subset of the logic that the handleNode function requires\n // and it's easier to read and maintain this way\n const handleRootNode = async (node?: RouteNode) => {\n if (!node) {\n // currently this is not being handled, but it could be in the future\n // for example to handle a virtual root route\n return\n }\n\n // from here on, we are only handling the root node that's present in the file system\n const routeCode = fs.readFileSync(node.fullPath, 'utf-8')\n\n if (!routeCode) {\n const _rootTemplate = ROUTE_TEMPLATE.rootRoute\n const replaced = await fillTemplate(config, _rootTemplate.template(), {\n tsrImports: _rootTemplate.imports.tsrImports(),\n tsrPath: rootPathId,\n tsrExportStart: _rootTemplate.imports.tsrExportStart(),\n tsrExportEnd: _rootTemplate.imports.tsrExportEnd(),\n })\n\n await writeIfDifferent(\n node.fullPath,\n '', // Empty string because the file doesn't exist yet\n replaced,\n {\n beforeWrite: () => {\n // logger.log(`🟡 Creating ${node.fullPath}`)\n },\n },\n )\n }\n }\n\n await handleRootNode(rootRouteNode)\n\n const handleNode = async (node: RouteNode) => {\n // Do not remove this as we need to set the lastIndex to 0 as it\n // is necessary to reset the regex's index when using the global flag\n // otherwise it might not match the next time it's used\n resetRegex(routeGroupPatternRegex)\n\n let parentRoute = hasParentRoute(routeNodes, node, node.routePath)\n\n // if the parent route is a virtual parent route, we need to find the real parent route\n if (parentRoute?.isVirtualParentRoute && parentRoute.children?.length) {\n // only if this sub-parent route returns a valid parent route, we use it, if not leave it as it\n const possibleParentRoute = hasParentRoute(\n parentRoute.children,\n node,\n node.routePath,\n )\n if (possibleParentRoute) {\n parentRoute = possibleParentRoute\n }\n }\n\n if (parentRoute) node.parent = parentRoute\n\n node.path = determineNodePath(node)\n\n const trimmedPath = trimPathLeft(node.path ?? '')\n\n const split = trimmedPath.split('/')\n const lastRouteSegment = split[split.length - 1] ?? trimmedPath\n\n node.isNonPath =\n lastRouteSegment.startsWith('_') ||\n routeGroupPatternRegex.test(lastRouteSegment)\n\n node.cleanedPath = removeGroups(\n removeUnderscores(removeLayoutSegments(node.path)) ?? '',\n )\n\n const routeCode = fs.readFileSync(node.fullPath, 'utf-8')\n\n // Ensure the boilerplate for the route exists, which can be skipped for virtual parent routes and virtual routes\n if (!node.isVirtualParentRoute && !node.isVirtual) {\n // const escapedRoutePath = node.routePath?.replaceAll('$', '$$') ?? ''\n // let replaced = routeCode\n // await writeIfDifferent(node.fullPath, routeCode, replaced, {\n // beforeWrite: () => {\n // // logger.log(`🟡 Updating ${node.fullPath}`)\n // },\n // })\n }\n\n const cleanedPathIsEmpty = (node.cleanedPath || '').length === 0\n const nonPathRoute =\n node._fsRouteType === 'pathless_layout' && node.isNonPath\n\n node.isVirtualParentRequired =\n node._fsRouteType === 'pathless_layout' || nonPathRoute\n ? !cleanedPathIsEmpty\n : false\n\n if (!node.isVirtual && node.isVirtualParentRequired) {\n const parentRoutePath = removeLastSegmentFromPath(node.routePath) || '/'\n const parentVariableName = routePathToVariable(parentRoutePath)\n\n const anchorRoute = routeNodes.find(\n (d) => d.routePath === parentRoutePath,\n )\n\n if (!anchorRoute) {\n const parentNode: RouteNode = {\n ...node,\n path: removeLastSegmentFromPath(node.path) || '/',\n filePath: removeLastSegmentFromPath(node.filePath) || '/',\n fullPath: removeLastSegmentFromPath(node.fullPath) || '/',\n routePath: parentRoutePath,\n variableName: parentVariableName,\n isVirtual: true,\n _fsRouteType: 'layout', // layout since this route will wrap other routes\n isVirtualParentRoute: true,\n isVirtualParentRequired: false,\n }\n\n parentNode.children = parentNode.children ?? []\n parentNode.children.push(node)\n\n node.parent = parentNode\n\n if (node._fsRouteType === 'pathless_layout') {\n // since `node.path` is used as the `id` on the route definition, we need to update it\n node.path = determineNodePath(node)\n }\n\n await handleNode(parentNode)\n } else {\n anchorRoute.children = anchorRoute.children ?? []\n anchorRoute.children.push(node)\n\n node.parent = anchorRoute\n }\n }\n\n if (\n !routeCode\n .split('\\n')\n .some((line) => line.trim().startsWith('export const ServerRoute'))\n ) {\n return\n }\n\n if (node.parent) {\n if (!node.isVirtualParentRequired) {\n node.parent.children = node.parent.children ?? []\n node.parent.children.push(node)\n }\n } else {\n routeTree.push(node)\n }\n\n routeNodes.push(node)\n }\n\n for (const node of preRouteNodes) {\n await handleNode(node)\n }\n\n // This is run against the `routeNodes` array since it\n // has the accumulated (intended) Server Route nodes\n // Since TSR allows multiple way of defining a route,\n // we need to ensure that a user hasn't defined the\n // same route in multiple ways (i.e. `flat`, `nested`, `virtual`)\n checkRouteFullPathUniqueness(routeNodes, config)\n\n function buildRouteTreeConfig(nodes: Array<RouteNode>, depth = 1): string {\n const children = nodes.map((node) => {\n if (node._fsRouteType === '__root') {\n return\n }\n\n if (node._fsRouteType === 'pathless_layout' && !node.children?.length) {\n return\n }\n\n const route = `${node.variableName}Route`\n\n if (node.children?.length) {\n const childConfigs = buildRouteTreeConfig(node.children, depth + 1)\n\n const childrenDeclaration = `interface ${route}Children {\n ${node.children.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(',')}\n}`\n\n const children = `const ${route}Children: ${route}Children = {\n ${node.children.map((child) => `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`).join(',')}\n}`\n\n const routeWithChildren = `const ${route}WithChildren = ${route}._addFileChildren(${route}Children)`\n\n return [\n childConfigs,\n childrenDeclaration,\n children,\n routeWithChildren,\n ].join('\\n\\n')\n }\n\n return undefined\n })\n\n return children.filter(Boolean).join('\\n\\n')\n }\n\n const routeConfigChildrenText = buildRouteTreeConfig(routeTree)\n\n const sortedRouteNodes = multiSortBy(routeNodes, [\n (d) => (d.routePath?.includes(`/${rootPathId}`) ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) => (d.routePath?.endsWith(config.indexToken) ? -1 : 1),\n (d) => d,\n ])\n\n const imports = Object.entries({\n createFileRoute: sortedRouteNodes.some((d) => d.isVirtual),\n })\n .filter((d) => d[1])\n .map((d) => d[0])\n\n const virtualRouteNodes = sortedRouteNodes.filter((d) => d.isVirtual)\n\n function getImportPath(node: RouteNode) {\n return replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(generatedServerRouteTreePath),\n path.resolve(config.routesDirectory, node.filePath),\n ),\n ),\n )\n }\n\n const rootRouteExists = fs.existsSync(rootRouteNode.fullPath)\n const rootRouteCode = rootRouteExists\n ? fs.readFileSync(rootRouteNode.fullPath, 'utf-8')\n : ''\n const hasServerRootRoute =\n rootRouteExists && rootRouteCode.includes('export const ServerRoute')\n\n const routeImports = [\n ...config.routeTreeFileHeader,\n `// This file was automatically generated by TanStack Router.\n// You should NOT make any changes in this file as it will be overwritten.\n// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.`,\n imports.length\n ? `import { ${imports.join(', ')} } from '${ROUTE_TEMPLATE.fullPkg}'\\n`\n : '',\n '// Import Routes',\n [\n `import type { FileRoutesByPath, CreateServerFileRoute } from '${ROUTE_TEMPLATE.fullPkg}'`,\n `import { createServerRoute, createServerFileRoute } from '${ROUTE_TEMPLATE.fullPkg}'`,\n hasServerRootRoute\n ? `import { ServerRoute as rootRouteImport } from './${getImportPath(rootRouteNode)}'`\n : '',\n ...sortedRouteNodes\n .filter((d) => !d.isVirtual)\n .map((node) => {\n return `import { ServerRoute as ${\n node.variableName\n }RouteImport } from './${getImportPath(node)}'`\n }),\n ].join('\\n'),\n virtualRouteNodes.length ? '// Create Virtual Routes' : '',\n virtualRouteNodes\n .map((node) => {\n return `const ${\n node.variableName\n }RouteImport = createFileRoute('${node.routePath}')()`\n })\n .join('\\n'),\n '// Create/Update Routes',\n !hasServerRootRoute\n ? `\n const rootRoute = createServerRoute()\n `\n : '',\n sortedRouteNodes\n .map((node) => {\n return [\n [\n `const ${node.variableName}Route = ${node.variableName}RouteImport.update({\n ${[\n `id: '${node.path}'`,\n !node.isNonPath ? `path: '${node.cleanedPath}'` : undefined,\n `getParentRoute: () => ${node.parent?.variableName ?? 'root'}Route`,\n ]\n .filter(Boolean)\n .join(',')}\n } as any)`,\n ].join(''),\n ].join('\\n\\n')\n })\n .join('\\n\\n'),\n '',\n\n '// Populate the FileRoutesByPath interface',\n `declare module '${ROUTE_TEMPLATE.fullPkg}' {\n interface FileRoutesByPath {\n ${routeNodes\n .map((routeNode) => {\n const filePathId = routeNode.routePath\n\n return `'${filePathId}': {\n id: '${filePathId}'\n path: '${inferPath(routeNode)}'\n fullPath: '${inferFullPath(routeNode)}'\n preLoaderRoute: typeof ${routeNode.variableName}RouteImport\n parentRoute: typeof ${\n routeNode.isVirtualParentRequired\n ? `${routeNode.parent?.variableName}Route`\n : routeNode.parent?.variableName\n ? `${routeNode.parent.variableName}RouteImport`\n : 'rootRoute'\n }\n }`\n })\n .join('\\n')}\n }\n}`,\n `// Add type-safety to the createFileRoute function across the route tree`,\n routeNodes\n .map((routeNode) => {\n return `declare module './${getImportPath(routeNode)}' {\nconst createServerFileRoute: CreateServerFileRoute<\nFileRoutesByPath['${routeNode.routePath}']['parentRoute'],\nFileRoutesByPath['${routeNode.routePath}']['id'],\nFileRoutesByPath['${routeNode.routePath}']['path'],\nFileRoutesByPath['${routeNode.routePath}']['fullPath'],\n${routeNode.children?.length ? `${routeNode.variableName}RouteChildren` : 'unknown'}\n>\n}`\n })\n .join('\\n'),\n '// Create and export the route tree',\n routeConfigChildrenText,\n `export interface FileRoutesByFullPath {\n ${[...createRouteNodesByFullPath(routeNodes).entries()].map(\n ([fullPath, routeNode]) => {\n return `'${fullPath}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n },\n )}\n}`,\n `export interface FileRoutesByTo {\n ${[...createRouteNodesByTo(routeNodes).entries()].map(([to, routeNode]) => {\n return `'${to}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n })}\n}`,\n `export interface FileRoutesById {\n '${rootRouteId}': typeof rootRoute,\n ${[...createRouteNodesById(routeNodes).entries()].map(([id, routeNode]) => {\n return `'${id}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n })}\n}`,\n `export interface FileRouteTypes {\n fileRoutesByFullPath: FileRoutesByFullPath\n fullPaths: ${routeNodes.length > 0 ? [...createRouteNodesByFullPath(routeNodes).keys()].map((fullPath) => `'${fullPath}'`).join('|') : 'never'}\n fileRoutesByTo: FileRoutesByTo\n to: ${routeNodes.length > 0 ? [...createRouteNodesByTo(routeNodes).keys()].map((to) => `'${to}'`).join('|') : 'never'}\n id: ${[`'${rootRouteId}'`, ...[...createRouteNodesById(routeNodes).keys()].map((id) => `'${id}'`)].join('|')}\n fileRoutesById: FileRoutesById\n}`,\n `export interface RootRouteChildren {\n ${routeTree.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(',')}\n}`,\n `const rootRouteChildren: RootRouteChildren = {\n ${routeTree.map((child) => `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`).join(',')}\n}`,\n `export const routeTree = rootRoute._addFileChildren(rootRouteChildren)._addFileTypes<FileRouteTypes>()`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n const createRouteManifest = () => {\n const routesManifest = {\n [rootRouteId]: {\n filePath: rootRouteNode.filePath,\n children: routeTree.map((d) => d.routePath),\n },\n ...Object.fromEntries(\n routeNodes.map((d) => {\n const filePathId = d.routePath\n\n return [\n filePathId,\n {\n filePath: d.filePath,\n parent: d.parent?.routePath ? d.parent.routePath : undefined,\n children: d.children?.map((childRoute) => childRoute.routePath),\n },\n ]\n }),\n ),\n }\n\n return JSON.stringify(\n {\n routes: routesManifest,\n },\n null,\n 2,\n )\n }\n\n const includeManifest = ['react', 'solid']\n const routeConfigFileContent = !includeManifest.includes(config.target)\n ? routeImports\n : [\n routeImports,\n '\\n',\n '/* ROUTE_MANIFEST_START',\n createRouteManifest(),\n 'ROUTE_MANIFEST_END */',\n ].join('\\n')\n\n if (!checkLatest()) return\n\n const existingRouteTreeContent = await fsp\n .readFile(path.resolve(generatedServerRouteTreePath), 'utf-8')\n .catch((err) => {\n if (err.code === 'ENOENT') {\n return ''\n }\n\n throw err\n })\n\n if (!checkLatest()) return\n\n // Ensure the directory exists\n await fsp.mkdir(path.dirname(path.resolve(generatedServerRouteTreePath)), {\n recursive: true,\n })\n\n if (!checkLatest()) return\n\n // Write the route tree file, if it has changed\n const routeTreeWriteResult = await writeIfDifferent(\n path.resolve(generatedServerRouteTreePath),\n await format(existingRouteTreeContent, config),\n await format(routeConfigFileContent, config),\n {\n beforeWrite: () => {\n // logger.log(`🟡 Updating ${generatedRouteTreePath}`)\n },\n },\n )\n\n // Write declaration file\n const startDeclarationFilePath = path.join(\n path.resolve(root, config.srcDirectory),\n 'tanstack-start.d.ts',\n )\n const serverRoutesRelativePath = removeExt(\n path.relative(\n path.dirname(startDeclarationFilePath),\n generatedServerRouteTreePath,\n ),\n )\n const startDeclarationFileContent = buildStartDeclarationFile({\n serverRoutesRelativePath,\n })\n if (!fs.existsSync(startDeclarationFilePath)) {\n await writeIfDifferent(\n startDeclarationFilePath,\n '',\n startDeclarationFileContent,\n {\n beforeWrite: () => {\n logger.log(`🟡 Creating tanstack-start.d.ts`)\n },\n },\n )\n } else {\n const existingDeclarationFileContent = await fsp\n .readFile(startDeclarationFilePath, 'utf-8')\n .catch((err) => {\n if (err.code === 'ENOENT') {\n return ''\n }\n throw err\n })\n await writeIfDifferent(\n startDeclarationFilePath,\n existingDeclarationFileContent,\n startDeclarationFileContent,\n {\n beforeWrite: () => {\n logger.log(`🟡 Updating tanstack-start.d.ts`)\n },\n },\n )\n }\n\n if (routeTreeWriteResult && !checkLatest()) {\n return\n }\n\n // logger.log(\n // `✅ Processed ${routeNodes.length === 1 ? 'server route' : 'server routes'} in ${\n // Date.now() - start\n // }ms`,\n // )\n}\n\nfunction buildStartDeclarationFile({\n serverRoutesRelativePath,\n}: {\n serverRoutesRelativePath: string\n}) {\n return [`import '${serverRoutesRelativePath}'`].join('\\n') + '\\n'\n}\n\nfunction removeGroups(s: string) {\n return s.replace(possiblyNestedRouteGroupPatternRegex, '')\n}\n\n/**\n * The `node.path` is used as the `id` in the route definition.\n * This function checks if the given node has a parent and if so, it determines the correct path for the given node.\n * @param node - The node to determine the path for.\n * @returns The correct path for the given node.\n */\nfunction determineNodePath(node: RouteNode) {\n return (node.path = node.parent\n ? node.routePath?.replace(node.parent.routePath ?? '', '') || '/'\n : node.routePath)\n}\n\n/**\n * Removes the last segment from a given path. Segments are considered to be separated by a '/'.\n *\n * @param {string} routePath - The path from which to remove the last segment. Defaults to '/'.\n * @returns {string} The path with the last segment removed.\n * @example\n * removeLastSegmentFromPath('/workspace/_auth/foo') // '/workspace/_auth'\n */\nfunction removeLastSegmentFromPath(routePath: string = '/'): string {\n const segments = routePath.split('/')\n segments.pop() // Remove the last segment\n return segments.join('/')\n}\n\n/**\n * Removes all segments from a given path that start with an underscore ('_').\n *\n * @param {string} routePath - The path from which to remove segments. Defaults to '/'.\n * @returns {string} The path with all underscore-prefixed segments removed.\n * @example\n * removeLayoutSegments('/workspace/_auth/foo') // '/workspace/foo'\n */\nfunction removeLayoutSegments(routePath: string = '/'): string {\n const segments = routePath.split('/')\n const newSegments = segments.filter((segment) => !segment.startsWith('_'))\n return newSegments.join('/')\n}\n\nfunction hasParentRoute(\n routes: Array<RouteNode>,\n node: RouteNode,\n routePathToCheck: string | undefined,\n): RouteNode | null {\n if (!routePathToCheck || routePathToCheck === '/') {\n return null\n }\n\n const sortedNodes = multiSortBy(routes, [\n (d) => d.routePath!.length * -1,\n (d) => d.variableName,\n ]).filter((d) => d.routePath !== `/${rootPathId}`)\n\n for (const route of sortedNodes) {\n if (route.routePath === '/') continue\n\n if (\n routePathToCheck.startsWith(`${route.routePath}/`) &&\n route.routePath !== routePathToCheck\n ) {\n return route\n }\n }\n\n const segments = routePathToCheck.split('/')\n segments.pop() // Remove the last segment\n const parentRoutePath = segments.join('/')\n\n return hasParentRoute(routes, node, parentRoutePath)\n}\n\n/**\n * Gets the final variable name for a route\n */\nconst getResolvedRouteNodeVariableName = (routeNode: RouteNode): string => {\n return routeNode.children?.length\n ? `${routeNode.variableName}RouteWithChildren`\n : `${routeNode.variableName}Route`\n}\n\n/**\n * Creates a map from fullPath to routeNode\n */\nconst createRouteNodesByFullPath = (\n routeNodes: Array<RouteNode>,\n): Map<string, RouteNode> => {\n return new Map(\n routeNodes.map((routeNode) => [inferFullPath(routeNode), routeNode]),\n )\n}\n\n/**\n * Create a map from 'to' to a routeNode\n */\nconst createRouteNodesByTo = (\n routeNodes: Array<RouteNode>,\n): Map<string, RouteNode> => {\n return new Map(\n dedupeBranchesAndIndexRoutes(routeNodes).map((routeNode) => [\n inferTo(routeNode),\n routeNode,\n ]),\n )\n}\n\n/**\n * Create a map from 'id' to a routeNode\n */\nconst createRouteNodesById = (\n routeNodes: Array<RouteNode>,\n): Map<string, RouteNode> => {\n return new Map(\n routeNodes.map((routeNode) => {\n const id = routeNode.routePath ?? ''\n return [id, routeNode]\n }),\n )\n}\n\n/**\n * Infers the full path for use by TS\n */\nconst inferFullPath = (routeNode: RouteNode): string => {\n const fullPath = removeGroups(\n removeUnderscores(removeLayoutSegments(routeNode.routePath)) ?? '',\n )\n\n return routeNode.cleanedPath === '/' ? fullPath : fullPath.replace(/\\/$/, '')\n}\n\n/**\n * Infers the path for use by TS\n */\nconst inferPath = (routeNode: RouteNode): string => {\n return routeNode.cleanedPath === '/'\n ? routeNode.cleanedPath\n : (routeNode.cleanedPath?.replace(/\\/$/, '') ?? '')\n}\n\n/**\n * Infers to path\n */\nconst inferTo = (routeNode: RouteNode): string => {\n const fullPath = inferFullPath(routeNode)\n\n if (fullPath === '/') return fullPath\n\n return fullPath.replace(/\\/$/, '')\n}\n\n/**\n * Dedupes branches and index routes\n */\nconst dedupeBranchesAndIndexRoutes = (\n routes: Array<RouteNode>,\n): Array<RouteNode> => {\n return routes.filter((route) => {\n if (route.children?.find((child) => child.cleanedPath === '/')) return false\n return true\n })\n}\n\nfunction checkUnique<TElement>(routes: Array<TElement>, key: keyof TElement) {\n // Check no two routes have the same `key`\n // if they do, throw an error with the conflicting filePaths\n const keys = routes.map((d) => d[key])\n const uniqueKeys = new Set(keys)\n if (keys.length !== uniqueKeys.size) {\n const duplicateKeys = keys.filter((d, i) => keys.indexOf(d) !== i)\n const conflictingFiles = routes.filter((d) =>\n duplicateKeys.includes(d[key]),\n )\n return conflictingFiles\n }\n return undefined\n}\n\nfunction checkRouteFullPathUniqueness(\n _routes: Array<RouteNode>,\n config: Config,\n) {\n const routes = _routes.map((d) => {\n const inferredFullPath = inferFullPath(d)\n return { ...d, inferredFullPath }\n })\n\n const conflictingFiles = checkUnique(routes, 'inferredFullPath')\n\n if (conflictingFiles !== undefined) {\n const errorMessage = `Conflicting configuration paths were found for the following route${conflictingFiles.length > 1 ? 's' : ''}: ${conflictingFiles\n .map((p) => `\"${p.inferredFullPath}\"`)\n .join(', ')}.\nPlease ensure each Server Route has a unique full path.\nConflicting files: \\n ${conflictingFiles.map((d) => path.resolve(config.routesDirectory, d.filePath)).join('\\n ')}\\n`\n console.error(errorMessage)\n process.exit(1)\n }\n}\n"],"names":["isAbsolute","join","normalize","path","config","getTargetTemplate","logging","virtualGetRouteNodes","physicalGetRouteNodes","rootPathId","multiSortBy","fillTemplate","writeIfDifferent","resetRegex","trimPathLeft","removeUnderscores","routePathToVariable","children","replaceBackslash","removeExt","rootRouteId","format"],"mappings":";;;;;;;;AAwBA,IAAI,OAAO;AACX,MAAM,YAAY,MAAM;AACxB,MAAM,UAAU,CAAC,SAAkB;AAC1B,SAAA;AACT;AAEO,SAAS,8BAA8B,QAAwB;AAChE,MAAA,OAAe,QAAQ,IAAI;AAE/B,QAAM,yBAAyB,MAAM;AAC5B,WAAAA,KAAA,WAAW,OAAO,eAAe,IACpC,OAAO,kBACPC,UAAK,MAAM,OAAO,eAAe;AAAA,EACvC;AAEA,QAAM,WAAW,YAAY;AAC3B,QAAI,aAAa;AACf;AAAA,IAAA;AAGF,YAAQ,IAAI;AAER,QAAA;AACI,YAAA,UAAU,QAAQ,IAAI;AAAA,aACrB,KAAK;AACZ,cAAQ,MAAM,GAAG;AACjB,cAAQ,KAAK;AAAA,IAAA,UACb;AACA,cAAQ,KAAK;AAAA,IAAA;AAAA,EAEjB;AAEM,QAAA,aAAa,OAAO,SAAiB;AACnC,UAA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AAU,MAAM,gBAAgB,KAAa,QAAA;AAChE,WAAA;AAAA,EAAA,CACR;AACH;AAEA,SAAS,YAAsB,QAAyB,KAAqB;AAG3E,QAAM,OAAO,OAAO,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC;AAC/B,QAAA,aAAa,IAAI,IAAI,IAAI;AAC3B,MAAA,KAAK,WAAW,WAAW,MAAM;AAC7B,UAAA,gBAAgB,KAAK,OAAO,CAAC,GAAG,MAAM,KAAK,QAAQ,CAAC,MAAM,CAAC;AACjE,UAAM,mBAAmB,OAAO;AAAA,MAAO,CAAC,MACtC,cAAc,SAAS,EAAE,GAAG,CAAC;AAAA,IAC/B;AACO,WAAA;AAAA,EAAA;AAEF,SAAA;AACT;AAEA,SAAS,6BACP,SACA,QACA;AACA,QAAM,SAAS,QAAQ,IAAI,CAAC,MAAM;AAC1B,UAAA,mBAAmB,cAAc,CAAC;AACjC,WAAA,EAAE,GAAG,GAAG,iBAAiB;AAAA,EAAA,CACjC;AAEK,QAAA,mBAAmB,YAAY,QAAQ,kBAAkB;AAE/D,MAAI,qBAAqB,QAAW;AAClC,UAAM,eAAe,qEAAqE,iBAAiB,SAAS,IAAI,MAAM,EAAE,KAAK,iBAClI,IAAI,CAAC,MAAM,IAAI,EAAE,gBAAgB,GAAG,EACpC,KAAK,IAAI,CAAC;AAAA;AAAA;AAAA,GAEO,iBAAiB,IAAI,CAAC,MAAM,KAAK,QAAQ,OAAO,iBAAiB,EAAE,QAAQ,CAAC,EAAE,KAAK,KAAK,CAAC;AAAA;AAC7G,YAAQ,MAAM,YAAY;AAC1B,YAAQ,KAAK,CAAC;AAAA,EAAA;AAElB;;"}
|
|
1
|
+
{"version":3,"file":"plugin.cjs","sources":["../../../src/start-server-routes-plugin/plugin.ts"],"sourcesContent":["import path, { isAbsolute, join, normalize } from 'node:path'\nimport fs from 'node:fs'\nimport fsp from 'node:fs/promises'\nimport {\n format,\n logging,\n multiSortBy,\n physicalGetRouteNodes,\n removeExt,\n removeUnderscores,\n replaceBackslash,\n resetRegex,\n rootPathId,\n routePathToVariable,\n trimPathLeft,\n virtualGetRouteNodes,\n writeIfDifferent,\n} from '@tanstack/router-generator'\nimport { rootRouteId } from '@tanstack/router-core'\nimport { fillTemplate, getTargetTemplate } from './template'\nimport type { GetRouteNodesResult, RouteNode } from '@tanstack/router-generator'\nimport type { Config } from './config'\nimport type { Plugin } from 'vite'\n\nlet lock = false\nconst checkLock = () => lock\nconst setLock = (bool: boolean) => {\n lock = bool\n}\n\nexport function TanStackStartServerRoutesVite(config: Config): Plugin {\n let ROOT: string = process.cwd()\n\n const getRoutesDirectoryPath = () => {\n return isAbsolute(config.routesDirectory)\n ? config.routesDirectory\n : join(ROOT, config.routesDirectory)\n }\n\n const generate = async () => {\n if (checkLock()) {\n return\n }\n\n setLock(true)\n\n try {\n await generator(config, ROOT)\n } catch (err) {\n console.error(err)\n console.info()\n } finally {\n setLock(false)\n }\n }\n\n const handleFile = async (file: string) => {\n const filePath = normalize(file)\n\n const routesDirectoryPath = getRoutesDirectoryPath()\n if (filePath.startsWith(routesDirectoryPath)) {\n await generate()\n }\n }\n\n return {\n name: 'tanstack-start-server-routes-plugin',\n configureServer(server) {\n server.watcher.on('all', (event, path) => {\n handleFile(path)\n })\n },\n configResolved(config) {\n ROOT = config.root\n },\n async buildStart() {\n await generate()\n // if (this.environment.name === 'server') {\n // }\n },\n sharedDuringBuild: true,\n resolveId(id) {\n if (id === 'tanstack:server-routes') {\n const generatedRouteTreePath = getGeneratedRouteTreePath(ROOT)\n return generatedRouteTreePath\n }\n return null\n },\n }\n}\n\n// Maybe import this from `@tanstack/router-core` in the future???\nlet latestTask = 0\nconst routeGroupPatternRegex = /\\(.+\\)/g\nconst possiblyNestedRouteGroupPatternRegex = /\\([^/]+\\)\\/?/g\n\nlet isFirst = false\nlet skipMessage = false\n\nfunction getGeneratedRouteTreePath(root: string) {\n return path.resolve(root, '.tanstack-start/server-routes/routeTree.gen.ts')\n}\n\nasync function generator(config: Config, root: string) {\n const generatedServerRouteTreePath = getGeneratedRouteTreePath(root)\n const ROUTE_TEMPLATE = getTargetTemplate(config.target)\n const logger = logging({ disabled: config.disableLogging })\n\n if (!isFirst) {\n // logger.log('♻️ Generating server routes...')\n isFirst = true\n } else if (skipMessage) {\n skipMessage = false\n } else {\n // logger.log('♻️ Regenerating server routes...')\n }\n\n const taskId = latestTask + 1\n latestTask = taskId\n\n const checkLatest = () => {\n if (latestTask !== taskId) {\n skipMessage = true\n return false\n }\n\n return true\n }\n\n const start = Date.now()\n\n let getRouteNodesResult: GetRouteNodesResult\n\n if (config.virtualRouteConfig) {\n getRouteNodesResult = await virtualGetRouteNodes(config, root)\n } else {\n getRouteNodesResult = await physicalGetRouteNodes(config, root)\n }\n\n const { rootRouteNode, routeNodes: beforeRouteNodes } = getRouteNodesResult\n if (rootRouteNode === undefined) {\n let errorMessage = `rootRouteNode must not be undefined. Make sure you've added your root route into the route-tree.`\n if (!config.virtualRouteConfig) {\n errorMessage += `\\nMake sure that you add a \"${rootPathId}.tsx\" file to your routes directory.\\nAdd the file in: \"${config.routesDirectory}/${rootPathId}.tsx\"`\n }\n throw new Error(errorMessage)\n }\n\n const preRouteNodes = multiSortBy(beforeRouteNodes, [\n (d) => (d.routePath === '/' ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) =>\n d.filePath.match(new RegExp(`[./]${config.indexToken}[.]`)) ? 1 : -1,\n (d) =>\n d.filePath.match(\n /[./](component|errorComponent|pendingComponent|loader|lazy)[.]/,\n )\n ? 1\n : -1,\n (d) =>\n d.filePath.match(new RegExp(`[./]${config.routeToken}[.]`)) ? -1 : 1,\n (d) => (d.routePath?.endsWith('/') ? -1 : 1),\n (d) => d.routePath,\n ]).filter((d) => ![`/${rootPathId}`].includes(d.routePath || ''))\n\n const routeTree: Array<RouteNode> = []\n\n // Loop over the flat list of routeNodes and\n // build up a tree based on the routeNodes' routePath\n const routeNodes: Array<RouteNode> = []\n\n // the handleRootNode function is not being collapsed into the handleNode function\n // because it requires only a subset of the logic that the handleNode function requires\n // and it's easier to read and maintain this way\n const handleRootNode = async (node?: RouteNode) => {\n if (!node) {\n // currently this is not being handled, but it could be in the future\n // for example to handle a virtual root route\n return\n }\n\n // from here on, we are only handling the root node that's present in the file system\n const routeCode = fs.readFileSync(node.fullPath, 'utf-8')\n\n if (!routeCode) {\n const _rootTemplate = ROUTE_TEMPLATE.rootRoute\n const replaced = await fillTemplate(config, _rootTemplate.template(), {\n tsrImports: _rootTemplate.imports.tsrImports(),\n tsrPath: rootPathId,\n tsrExportStart: _rootTemplate.imports.tsrExportStart(),\n tsrExportEnd: _rootTemplate.imports.tsrExportEnd(),\n })\n\n await writeIfDifferent(\n node.fullPath,\n '', // Empty string because the file doesn't exist yet\n replaced,\n {\n beforeWrite: () => {\n // logger.log(`🟡 Creating ${node.fullPath}`)\n },\n },\n )\n }\n }\n\n await handleRootNode(rootRouteNode)\n\n const handleNode = async (node: RouteNode) => {\n // Do not remove this as we need to set the lastIndex to 0 as it\n // is necessary to reset the regex's index when using the global flag\n // otherwise it might not match the next time it's used\n resetRegex(routeGroupPatternRegex)\n\n let parentRoute = hasParentRoute(routeNodes, node, node.routePath)\n\n // if the parent route is a virtual parent route, we need to find the real parent route\n if (parentRoute?.isVirtualParentRoute && parentRoute.children?.length) {\n // only if this sub-parent route returns a valid parent route, we use it, if not leave it as it\n const possibleParentRoute = hasParentRoute(\n parentRoute.children,\n node,\n node.routePath,\n )\n if (possibleParentRoute) {\n parentRoute = possibleParentRoute\n }\n }\n\n if (parentRoute) node.parent = parentRoute\n\n node.path = determineNodePath(node)\n\n const trimmedPath = trimPathLeft(node.path ?? '')\n\n const split = trimmedPath.split('/')\n const lastRouteSegment = split[split.length - 1] ?? trimmedPath\n\n node.isNonPath =\n lastRouteSegment.startsWith('_') ||\n routeGroupPatternRegex.test(lastRouteSegment)\n\n node.cleanedPath = removeGroups(\n removeUnderscores(removeLayoutSegments(node.path)) ?? '',\n )\n\n const routeCode = node.fullPath\n ? fs.readFileSync(node.fullPath, 'utf-8')\n : ''\n\n // Ensure the boilerplate for the route exists, which can be skipped for virtual parent routes and virtual routes\n if (!node.isVirtualParentRoute && !node.isVirtual) {\n // const escapedRoutePath = node.routePath?.replaceAll('$', '$$') ?? ''\n // let replaced = routeCode\n // await writeIfDifferent(node.fullPath, routeCode, replaced, {\n // beforeWrite: () => {\n // // logger.log(`🟡 Updating ${node.fullPath}`)\n // },\n // })\n }\n\n const cleanedPathIsEmpty = (node.cleanedPath || '').length === 0\n const nonPathRoute =\n node._fsRouteType === 'pathless_layout' && node.isNonPath\n\n node.isVirtualParentRequired =\n node._fsRouteType === 'pathless_layout' || nonPathRoute\n ? !cleanedPathIsEmpty\n : false\n\n if (!node.isVirtual && node.isVirtualParentRequired) {\n const parentRoutePath = removeLastSegmentFromPath(node.routePath) || '/'\n const parentVariableName = routePathToVariable(parentRoutePath)\n\n const anchorRoute = routeNodes.find(\n (d) => d.routePath === parentRoutePath,\n )\n\n if (!anchorRoute) {\n const parentNode: RouteNode = {\n ...node,\n path: removeLastSegmentFromPath(node.path) || '/',\n filePath: removeLastSegmentFromPath(node.filePath) || '/',\n fullPath: removeLastSegmentFromPath(node.fullPath) || '/',\n routePath: parentRoutePath,\n variableName: parentVariableName,\n isVirtual: true,\n _fsRouteType: 'layout', // layout since this route will wrap other routes\n isVirtualParentRoute: true,\n isVirtualParentRequired: false,\n }\n\n parentNode.children = parentNode.children ?? []\n parentNode.children.push(node)\n\n node.parent = parentNode\n\n if (node._fsRouteType === 'pathless_layout') {\n // since `node.path` is used as the `id` on the route definition, we need to update it\n node.path = determineNodePath(node)\n }\n\n await handleNode(parentNode)\n } else {\n anchorRoute.children = anchorRoute.children ?? []\n anchorRoute.children.push(node)\n\n node.parent = anchorRoute\n }\n }\n\n if (\n !routeCode\n .split('\\n')\n .some((line) => line.trim().startsWith('export const ServerRoute'))\n ) {\n return\n }\n\n if (node.parent) {\n if (!node.isVirtualParentRequired) {\n node.parent.children = node.parent.children ?? []\n node.parent.children.push(node)\n }\n } else {\n routeTree.push(node)\n }\n\n routeNodes.push(node)\n }\n\n for (const node of preRouteNodes) {\n await handleNode(node)\n }\n\n // This is run against the `routeNodes` array since it\n // has the accumulated (intended) Server Route nodes\n // Since TSR allows multiple way of defining a route,\n // we need to ensure that a user hasn't defined the\n // same route in multiple ways (i.e. `flat`, `nested`, `virtual`)\n checkRouteFullPathUniqueness(routeNodes, config)\n\n function buildRouteTreeConfig(nodes: Array<RouteNode>, depth = 1): string {\n const children = nodes.map((node) => {\n if (node._fsRouteType === '__root') {\n return\n }\n\n if (node._fsRouteType === 'pathless_layout' && !node.children?.length) {\n return\n }\n\n const route = `${node.variableName}Route`\n\n if (node.children?.length) {\n const childConfigs = buildRouteTreeConfig(node.children, depth + 1)\n\n const childrenDeclaration = `interface ${route}Children {\n ${node.children.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(',')}\n}`\n\n const children = `const ${route}Children: ${route}Children = {\n ${node.children.map((child) => `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`).join(',')}\n}`\n\n const routeWithChildren = `const ${route}WithChildren = ${route}._addFileChildren(${route}Children)`\n\n return [\n childConfigs,\n childrenDeclaration,\n children,\n routeWithChildren,\n ].join('\\n\\n')\n }\n\n return undefined\n })\n\n return children.filter(Boolean).join('\\n\\n')\n }\n\n const routeConfigChildrenText = buildRouteTreeConfig(routeTree)\n\n const sortedRouteNodes = multiSortBy(routeNodes, [\n (d) => (d.routePath?.includes(`/${rootPathId}`) ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) => (d.routePath?.endsWith(config.indexToken) ? -1 : 1),\n (d) => d,\n ])\n\n const imports = Object.entries({\n createFileRoute: sortedRouteNodes.some((d) => d.isVirtual),\n })\n .filter((d) => d[1])\n .map((d) => d[0])\n\n const virtualRouteNodes = sortedRouteNodes.filter((d) => d.isVirtual)\n\n function getImportPath(node: RouteNode) {\n return replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(generatedServerRouteTreePath),\n path.resolve(config.routesDirectory, node.filePath),\n ),\n ),\n )\n }\n\n const rootRouteExists = fs.existsSync(rootRouteNode.fullPath)\n const rootRouteCode = rootRouteExists\n ? fs.readFileSync(rootRouteNode.fullPath, 'utf-8')\n : ''\n const hasServerRootRoute =\n rootRouteExists && rootRouteCode.includes('export const ServerRoute')\n\n const routeImports = [\n ...config.routeTreeFileHeader,\n `// This file was automatically generated by TanStack Router.\n// You should NOT make any changes in this file as it will be overwritten.\n// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.`,\n imports.length\n ? `import { ${imports.join(', ')} } from '${ROUTE_TEMPLATE.fullPkg}'\\n`\n : '',\n '// Import Routes',\n [\n `import type { FileRoutesByPath, CreateServerFileRoute } from '${ROUTE_TEMPLATE.fullPkg}'`,\n `import { createServerRoute, createServerFileRoute } from '${ROUTE_TEMPLATE.fullPkg}'`,\n hasServerRootRoute\n ? `import { ServerRoute as rootRouteImport } from './${getImportPath(rootRouteNode)}'`\n : '',\n ...sortedRouteNodes\n .filter((d) => !d.isVirtual)\n .map((node) => {\n return `import { ServerRoute as ${\n node.variableName\n }RouteImport } from './${getImportPath(node)}'`\n }),\n ].join('\\n'),\n virtualRouteNodes.length ? '// Create Virtual Routes' : '',\n virtualRouteNodes\n .map((node) => {\n return `const ${\n node.variableName\n }RouteImport = createFileRoute('${node.routePath}')()`\n })\n .join('\\n'),\n '// Create/Update Routes',\n !hasServerRootRoute\n ? `\n const rootRoute = createServerRoute()\n `\n : '',\n sortedRouteNodes\n .map((node) => {\n return [\n [\n `const ${node.variableName}Route = ${node.variableName}RouteImport.update({\n ${[\n `id: '${node.path}'`,\n !node.isNonPath ? `path: '${node.cleanedPath}'` : undefined,\n `getParentRoute: () => ${node.parent?.variableName ?? 'root'}Route`,\n ]\n .filter(Boolean)\n .join(',')}\n } as any)`,\n ].join(''),\n ].join('\\n\\n')\n })\n .join('\\n\\n'),\n '',\n\n '// Populate the FileRoutesByPath interface',\n `declare module '${ROUTE_TEMPLATE.fullPkg}' {\n interface FileRoutesByPath {\n ${routeNodes\n .map((routeNode) => {\n const filePathId = routeNode.routePath\n\n return `'${filePathId}': {\n id: '${filePathId}'\n path: '${inferPath(routeNode)}'\n fullPath: '${inferFullPath(routeNode)}'\n preLoaderRoute: typeof ${routeNode.variableName}RouteImport\n parentRoute: typeof ${\n routeNode.isVirtualParentRequired\n ? `${routeNode.parent?.variableName}Route`\n : routeNode.parent?.variableName\n ? `${routeNode.parent.variableName}RouteImport`\n : 'rootRoute'\n }\n }`\n })\n .join('\\n')}\n }\n}`,\n `// Add type-safety to the createFileRoute function across the route tree`,\n routeNodes\n .map((routeNode) => {\n return `declare module './${getImportPath(routeNode)}' {\nconst createServerFileRoute: CreateServerFileRoute<\nFileRoutesByPath['${routeNode.routePath}']['parentRoute'],\nFileRoutesByPath['${routeNode.routePath}']['id'],\nFileRoutesByPath['${routeNode.routePath}']['path'],\nFileRoutesByPath['${routeNode.routePath}']['fullPath'],\n${routeNode.children?.length ? `${routeNode.variableName}RouteChildren` : 'unknown'}\n>\n}`\n })\n .join('\\n'),\n '// Create and export the route tree',\n routeConfigChildrenText,\n `export interface FileRoutesByFullPath {\n ${[...createRouteNodesByFullPath(routeNodes).entries()].map(\n ([fullPath, routeNode]) => {\n return `'${fullPath}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n },\n )}\n}`,\n `export interface FileRoutesByTo {\n ${[...createRouteNodesByTo(routeNodes).entries()].map(([to, routeNode]) => {\n return `'${to}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n })}\n}`,\n `export interface FileRoutesById {\n '${rootRouteId}': typeof rootRoute,\n ${[...createRouteNodesById(routeNodes).entries()].map(([id, routeNode]) => {\n return `'${id}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n })}\n}`,\n `export interface FileRouteTypes {\n fileRoutesByFullPath: FileRoutesByFullPath\n fullPaths: ${routeNodes.length > 0 ? [...createRouteNodesByFullPath(routeNodes).keys()].map((fullPath) => `'${fullPath}'`).join('|') : 'never'}\n fileRoutesByTo: FileRoutesByTo\n to: ${routeNodes.length > 0 ? [...createRouteNodesByTo(routeNodes).keys()].map((to) => `'${to}'`).join('|') : 'never'}\n id: ${[`'${rootRouteId}'`, ...[...createRouteNodesById(routeNodes).keys()].map((id) => `'${id}'`)].join('|')}\n fileRoutesById: FileRoutesById\n}`,\n `export interface RootRouteChildren {\n ${routeTree.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(',')}\n}`,\n `const rootRouteChildren: RootRouteChildren = {\n ${routeTree.map((child) => `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`).join(',')}\n}`,\n `export const routeTree = rootRoute._addFileChildren(rootRouteChildren)._addFileTypes<FileRouteTypes>()`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n const createRouteManifest = () => {\n const routesManifest = {\n [rootRouteId]: {\n filePath: rootRouteNode.filePath,\n children: routeTree.map((d) => d.routePath),\n },\n ...Object.fromEntries(\n routeNodes.map((d) => {\n const filePathId = d.routePath\n\n return [\n filePathId,\n {\n filePath: d.filePath,\n parent: d.parent?.routePath ? d.parent.routePath : undefined,\n children: d.children?.map((childRoute) => childRoute.routePath),\n },\n ]\n }),\n ),\n }\n\n return JSON.stringify(\n {\n routes: routesManifest,\n },\n null,\n 2,\n )\n }\n\n const includeManifest = ['react', 'solid']\n const routeConfigFileContent = !includeManifest.includes(config.target)\n ? routeImports\n : [\n routeImports,\n '\\n',\n '/* ROUTE_MANIFEST_START',\n createRouteManifest(),\n 'ROUTE_MANIFEST_END */',\n ].join('\\n')\n\n if (!checkLatest()) return\n\n const existingRouteTreeContent = await fsp\n .readFile(path.resolve(generatedServerRouteTreePath), 'utf-8')\n .catch((err) => {\n if (err.code === 'ENOENT') {\n return ''\n }\n\n throw err\n })\n\n if (!checkLatest()) return\n\n // Ensure the directory exists\n await fsp.mkdir(path.dirname(path.resolve(generatedServerRouteTreePath)), {\n recursive: true,\n })\n\n if (!checkLatest()) return\n\n // Write the route tree file, if it has changed\n const routeTreeWriteResult = await writeIfDifferent(\n path.resolve(generatedServerRouteTreePath),\n await format(existingRouteTreeContent, config),\n await format(routeConfigFileContent, config),\n {\n beforeWrite: () => {\n // logger.log(`🟡 Updating ${generatedRouteTreePath}`)\n },\n },\n )\n\n // Write declaration file\n const startDeclarationFilePath = path.join(\n path.resolve(root, config.srcDirectory),\n 'tanstack-start.d.ts',\n )\n const serverRoutesRelativePath = removeExt(\n path.relative(\n path.dirname(startDeclarationFilePath),\n generatedServerRouteTreePath,\n ),\n )\n const startDeclarationFileContent = buildStartDeclarationFile({\n serverRoutesRelativePath,\n })\n if (!fs.existsSync(startDeclarationFilePath)) {\n await writeIfDifferent(\n startDeclarationFilePath,\n '',\n startDeclarationFileContent,\n {\n beforeWrite: () => {\n logger.log(`🟡 Creating tanstack-start.d.ts`)\n },\n },\n )\n } else {\n const existingDeclarationFileContent = await fsp\n .readFile(startDeclarationFilePath, 'utf-8')\n .catch((err) => {\n if (err.code === 'ENOENT') {\n return ''\n }\n throw err\n })\n await writeIfDifferent(\n startDeclarationFilePath,\n existingDeclarationFileContent,\n startDeclarationFileContent,\n {\n beforeWrite: () => {\n logger.log(`🟡 Updating tanstack-start.d.ts`)\n },\n },\n )\n }\n\n if (routeTreeWriteResult && !checkLatest()) {\n return\n }\n\n // logger.log(\n // `✅ Processed ${routeNodes.length === 1 ? 'server route' : 'server routes'} in ${\n // Date.now() - start\n // }ms`,\n // )\n}\n\nfunction buildStartDeclarationFile({\n serverRoutesRelativePath,\n}: {\n serverRoutesRelativePath: string\n}) {\n const serverRoutesPath = replaceBackslash(serverRoutesRelativePath)\n return (\n [\n '/// <reference types=\"vite/client\" />',\n `import '${serverRoutesPath}'`,\n ].join('\\n') + '\\n'\n )\n}\n\nfunction removeGroups(s: string) {\n return s.replace(possiblyNestedRouteGroupPatternRegex, '')\n}\n\n/**\n * The `node.path` is used as the `id` in the route definition.\n * This function checks if the given node has a parent and if so, it determines the correct path for the given node.\n * @param node - The node to determine the path for.\n * @returns The correct path for the given node.\n */\nfunction determineNodePath(node: RouteNode) {\n return (node.path = node.parent\n ? node.routePath?.replace(node.parent.routePath ?? '', '') || '/'\n : node.routePath)\n}\n\n/**\n * Removes the last segment from a given path. Segments are considered to be separated by a '/'.\n *\n * @param {string} routePath - The path from which to remove the last segment. Defaults to '/'.\n * @returns {string} The path with the last segment removed.\n * @example\n * removeLastSegmentFromPath('/workspace/_auth/foo') // '/workspace/_auth'\n */\nfunction removeLastSegmentFromPath(routePath: string = '/'): string {\n const segments = routePath.split('/')\n segments.pop() // Remove the last segment\n return segments.join('/')\n}\n\n/**\n * Removes all segments from a given path that start with an underscore ('_').\n *\n * @param {string} routePath - The path from which to remove segments. Defaults to '/'.\n * @returns {string} The path with all underscore-prefixed segments removed.\n * @example\n * removeLayoutSegments('/workspace/_auth/foo') // '/workspace/foo'\n */\nfunction removeLayoutSegments(routePath: string = '/'): string {\n const segments = routePath.split('/')\n const newSegments = segments.filter((segment) => !segment.startsWith('_'))\n return newSegments.join('/')\n}\n\nfunction hasParentRoute(\n routes: Array<RouteNode>,\n node: RouteNode,\n routePathToCheck: string | undefined,\n): RouteNode | null {\n if (!routePathToCheck || routePathToCheck === '/') {\n return null\n }\n\n const sortedNodes = multiSortBy(routes, [\n (d) => d.routePath!.length * -1,\n (d) => d.variableName,\n ]).filter((d) => d.routePath !== `/${rootPathId}`)\n\n for (const route of sortedNodes) {\n if (route.routePath === '/') continue\n\n if (\n routePathToCheck.startsWith(`${route.routePath}/`) &&\n route.routePath !== routePathToCheck\n ) {\n return route\n }\n }\n\n const segments = routePathToCheck.split('/')\n segments.pop() // Remove the last segment\n const parentRoutePath = segments.join('/')\n\n return hasParentRoute(routes, node, parentRoutePath)\n}\n\n/**\n * Gets the final variable name for a route\n */\nconst getResolvedRouteNodeVariableName = (routeNode: RouteNode): string => {\n return routeNode.children?.length\n ? `${routeNode.variableName}RouteWithChildren`\n : `${routeNode.variableName}Route`\n}\n\n/**\n * Creates a map from fullPath to routeNode\n */\nconst createRouteNodesByFullPath = (\n routeNodes: Array<RouteNode>,\n): Map<string, RouteNode> => {\n return new Map(\n routeNodes.map((routeNode) => [inferFullPath(routeNode), routeNode]),\n )\n}\n\n/**\n * Create a map from 'to' to a routeNode\n */\nconst createRouteNodesByTo = (\n routeNodes: Array<RouteNode>,\n): Map<string, RouteNode> => {\n return new Map(\n dedupeBranchesAndIndexRoutes(routeNodes).map((routeNode) => [\n inferTo(routeNode),\n routeNode,\n ]),\n )\n}\n\n/**\n * Create a map from 'id' to a routeNode\n */\nconst createRouteNodesById = (\n routeNodes: Array<RouteNode>,\n): Map<string, RouteNode> => {\n return new Map(\n routeNodes.map((routeNode) => {\n const id = routeNode.routePath ?? ''\n return [id, routeNode]\n }),\n )\n}\n\n/**\n * Infers the full path for use by TS\n */\nconst inferFullPath = (routeNode: RouteNode): string => {\n const fullPath = removeGroups(\n removeUnderscores(removeLayoutSegments(routeNode.routePath)) ?? '',\n )\n\n return routeNode.cleanedPath === '/' ? fullPath : fullPath.replace(/\\/$/, '')\n}\n\n/**\n * Infers the path for use by TS\n */\nconst inferPath = (routeNode: RouteNode): string => {\n return routeNode.cleanedPath === '/'\n ? routeNode.cleanedPath\n : (routeNode.cleanedPath?.replace(/\\/$/, '') ?? '')\n}\n\n/**\n * Infers to path\n */\nconst inferTo = (routeNode: RouteNode): string => {\n const fullPath = inferFullPath(routeNode)\n\n if (fullPath === '/') return fullPath\n\n return fullPath.replace(/\\/$/, '')\n}\n\n/**\n * Dedupes branches and index routes\n */\nconst dedupeBranchesAndIndexRoutes = (\n routes: Array<RouteNode>,\n): Array<RouteNode> => {\n return routes.filter((route) => {\n if (route.children?.find((child) => child.cleanedPath === '/')) return false\n return true\n })\n}\n\nfunction checkUnique<TElement>(routes: Array<TElement>, key: keyof TElement) {\n // Check no two routes have the same `key`\n // if they do, throw an error with the conflicting filePaths\n const keys = routes.map((d) => d[key])\n const uniqueKeys = new Set(keys)\n if (keys.length !== uniqueKeys.size) {\n const duplicateKeys = keys.filter((d, i) => keys.indexOf(d) !== i)\n const conflictingFiles = routes.filter((d) =>\n duplicateKeys.includes(d[key]),\n )\n return conflictingFiles\n }\n return undefined\n}\n\nfunction checkRouteFullPathUniqueness(\n _routes: Array<RouteNode>,\n config: Config,\n) {\n const routes = _routes.map((d) => {\n const inferredFullPath = inferFullPath(d)\n return { ...d, inferredFullPath }\n })\n\n const conflictingFiles = checkUnique(routes, 'inferredFullPath')\n\n if (conflictingFiles !== undefined) {\n const errorMessage = `Conflicting configuration paths were found for the following route${conflictingFiles.length > 1 ? 's' : ''}: ${conflictingFiles\n .map((p) => `\"${p.inferredFullPath}\"`)\n .join(', ')}.\nPlease ensure each Server Route has a unique full path.\nConflicting files: \\n ${conflictingFiles.map((d) => path.resolve(config.routesDirectory, d.filePath)).join('\\n ')}\\n`\n console.error(errorMessage)\n process.exit(1)\n }\n}\n"],"names":["isAbsolute","join","normalize","path","config","getTargetTemplate","logging","virtualGetRouteNodes","physicalGetRouteNodes","rootPathId","multiSortBy","fillTemplate","writeIfDifferent","resetRegex","trimPathLeft","removeUnderscores","routePathToVariable","children","replaceBackslash","removeExt","rootRouteId","format"],"mappings":";;;;;;;;AAwBA,IAAI,OAAO;AACX,MAAM,YAAY,MAAM;AACxB,MAAM,UAAU,CAAC,SAAkB;AAC1B,SAAA;AACT;AAEO,SAAS,8BAA8B,QAAwB;AAChE,MAAA,OAAe,QAAQ,IAAI;AAE/B,QAAM,yBAAyB,MAAM;AAC5B,WAAAA,KAAA,WAAW,OAAO,eAAe,IACpC,OAAO,kBACPC,UAAK,MAAM,OAAO,eAAe;AAAA,EACvC;AAEA,QAAM,WAAW,YAAY;AAC3B,QAAI,aAAa;AACf;AAAA,IAAA;AAGF,YAAQ,IAAI;AAER,QAAA;AACI,YAAA,UAAU,QAAQ,IAAI;AAAA,aACrB,KAAK;AACZ,cAAQ,MAAM,GAAG;AAC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-0,0 +1,10 @@
|
|
|
1
|
+
const VITE_ENVIRONMENT_NAMES = {
|
|
2
|
+
// 'ssr' is chosen as the name for the server environment to ensure backwards compatibility
|
|
3
|
+
// with vite plugins that are not compatible with the new vite environment API (e.g. tailwindcss)
|
|
4
|
+
server: "ssr",
|
|
5
|
+
client: "client"
|
|
6
|
+
};
|
|
7
|
+
export {
|
|
8
|
+
VITE_ENVIRONMENT_NAMES
|
|
9
|
+
};
|
|
10
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","sources":["../../src/constants.ts"],"sourcesContent":["export const VITE_ENVIRONMENT_NAMES = {\n // 'ssr' is chosen as the name for the server environment to ensure backwards compatibility\n // with vite plugins that are not compatible with the new vite environment API (e.g. tailwindcss)\n server: 'ssr',\n client: 'client',\n} as const\n"],"names":[],"mappings":"AAAO,MAAM,yBAAyB;AAAA;AAAA;AAAA,EAGpC,QAAQ;AAAA,EACR,QAAQ;AACV;"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createEvent, sendWebResponse, getHeader } from "h3";
|
|
2
2
|
import { isRunnableDevEnvironment } from "vite";
|
|
3
3
|
import { extractHtmlScripts } from "../extractHtmlScripts.js";
|
|
4
|
+
import { VITE_ENVIRONMENT_NAMES } from "../constants.js";
|
|
4
5
|
function devServerPlugin() {
|
|
5
6
|
let isTest = false;
|
|
6
7
|
return {
|
|
@@ -19,10 +20,17 @@ function devServerPlugin() {
|
|
|
19
20
|
viteDevServer.middlewares.use(async (req, res) => {
|
|
20
21
|
var _a;
|
|
21
22
|
const event = createEvent(req, res);
|
|
22
|
-
const serverEnv = viteDevServer.environments[
|
|
23
|
+
const serverEnv = viteDevServer.environments[VITE_ENVIRONMENT_NAMES.server];
|
|
23
24
|
try {
|
|
24
|
-
if (!serverEnv
|
|
25
|
-
throw new Error(
|
|
25
|
+
if (!serverEnv) {
|
|
26
|
+
throw new Error(
|
|
27
|
+
`Server environment ${VITE_ENVIRONMENT_NAMES.server} not found`
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
if (!isRunnableDevEnvironment(serverEnv)) {
|
|
31
|
+
throw new Error(
|
|
32
|
+
`Expected server environment ${VITE_ENVIRONMENT_NAMES.server} to be a RunnableDevEnvironment. This can be caused by multiple vite versions being installed in the project.`
|
|
33
|
+
);
|
|
26
34
|
}
|
|
27
35
|
if (cachedScripts === void 0) {
|
|
28
36
|
const templateHtml = `<html><head></head><body></body></html>`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-server-plugin.js","sources":["../../../src/nitro/dev-server-plugin.ts"],"sourcesContent":["import { createEvent, getHeader, sendWebResponse } from 'h3'\nimport { isRunnableDevEnvironment } from 'vite'\nimport { extractHtmlScripts } from '../extractHtmlScripts'\nimport type { Connect, Plugin, ViteDevServer } from 'vite'\n\ndeclare global {\n // eslint-disable-next-line no-var\n var TSS_INJECTED_HEAD_SCRIPTS: string | undefined\n}\n\nexport function devServerPlugin(): Plugin {\n // let config: UserConfig\n let isTest = false\n\n return {\n name: 'start-dev-ssr-plugin',\n config(userConfig, { mode }) {\n // config = userConfig\n isTest = isTest ? isTest : mode === 'test'\n },\n configureServer(viteDevServer) {\n if (isTest) {\n return\n }\n\n ;(globalThis as any).viteDevServer = viteDevServer\n\n return () => {\n remove_html_middlewares(viteDevServer.middlewares)\n let cachedScripts: string | undefined\n viteDevServer.middlewares.use(async (req, res) => {\n const event = createEvent(req, res)\n const serverEnv = viteDevServer.environments[
|
|
1
|
+
{"version":3,"file":"dev-server-plugin.js","sources":["../../../src/nitro/dev-server-plugin.ts"],"sourcesContent":["import { createEvent, getHeader, sendWebResponse } from 'h3'\nimport { isRunnableDevEnvironment } from 'vite'\nimport { extractHtmlScripts } from '../extractHtmlScripts'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport type { Connect, DevEnvironment, Plugin, ViteDevServer } from 'vite'\n\ndeclare global {\n // eslint-disable-next-line no-var\n var TSS_INJECTED_HEAD_SCRIPTS: string | undefined\n}\n\nexport function devServerPlugin(): Plugin {\n // let config: UserConfig\n let isTest = false\n\n return {\n name: 'start-dev-ssr-plugin',\n config(userConfig, { mode }) {\n // config = userConfig\n isTest = isTest ? isTest : mode === 'test'\n },\n configureServer(viteDevServer) {\n if (isTest) {\n return\n }\n\n ;(globalThis as any).viteDevServer = viteDevServer\n\n return () => {\n remove_html_middlewares(viteDevServer.middlewares)\n let cachedScripts: string | undefined\n viteDevServer.middlewares.use(async (req, res) => {\n const event = createEvent(req, res)\n const serverEnv = viteDevServer.environments[\n VITE_ENVIRONMENT_NAMES.server\n ] as DevEnvironment | undefined\n\n try {\n if (!serverEnv) {\n throw new Error(\n `Server environment ${VITE_ENVIRONMENT_NAMES.server} not found`,\n )\n }\n if (!isRunnableDevEnvironment(serverEnv)) {\n throw new Error(\n `Expected server environment ${VITE_ENVIRONMENT_NAMES.server} to be a RunnableDevEnvironment. This can be caused by multiple vite versions being installed in the project.`,\n )\n }\n if (cachedScripts === undefined) {\n const templateHtml = `<html><head></head><body></body></html>`\n const transformedHtml = await viteDevServer.transformIndexHtml(\n req.url || '/',\n templateHtml,\n )\n const scripts = extractHtmlScripts(transformedHtml)\n globalThis.TSS_INJECTED_HEAD_SCRIPTS = scripts\n .map((script) => script.content ?? '')\n .join(';')\n }\n const serverEntry = await serverEnv.runner.import(\n '/~start/server-entry',\n )\n const response = await serverEntry['default'](event)\n\n return sendWebResponse(event, response)\n } catch (e) {\n console.error(e)\n viteDevServer.ssrFixStacktrace(e as Error)\n\n if (\n getHeader(event, 'content-type')?.includes('application/json')\n ) {\n return sendWebResponse(\n event,\n new Response(\n JSON.stringify(\n {\n status: 500,\n error: 'Internal Server Error',\n message:\n 'An unexpected error occurred. Please try again later.',\n timestamp: new Date().toISOString(),\n },\n null,\n 2,\n ),\n {\n status: 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n ),\n )\n }\n\n return sendWebResponse(\n event,\n new Response(\n `\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Error</title>\n <script type=\"module\">\n import { ErrorOverlay } from '/@vite/client'\n document.body.appendChild(new ErrorOverlay(${JSON.stringify(\n prepareError(req, e),\n ).replace(/</g, '\\\\u003c')}))\n </script>\n </head>\n <body>\n </body>\n </html>\n `,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n },\n ),\n )\n }\n })\n }\n },\n }\n}\n\n/**\n * Removes Vite internal middleware\n *\n * @param server\n */\nfunction remove_html_middlewares(server: ViteDevServer['middlewares']) {\n const html_middlewares = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n ]\n for (let i = server.stack.length - 1; i > 0; i--) {\n if (\n html_middlewares.includes(\n // @ts-expect-error\n server.stack[i].handle.name,\n )\n ) {\n server.stack.splice(i, 1)\n }\n }\n}\n\n/**\n * Formats error for SSR message in error overlay\n * @param req\n * @param error\n * @returns\n */\nfunction prepareError(req: Connect.IncomingMessage, error: unknown) {\n const e = error as Error\n return {\n message: `An error occured while server rendering ${req.url}:\\n\\n\\t${\n typeof e === 'string' ? e : e.message\n } `,\n stack: typeof e === 'string' ? '' : e.stack,\n }\n}\n"],"names":[],"mappings":";;;;AAWO,SAAS,kBAA0B;AAExC,MAAI,SAAS;AAEN,SAAA;AAAA,IACL,MAAM;AAAA,IACN,OAAO,YAAY,EAAE,QAAQ;AAElB,eAAA,SAAS,SAAS,SAAS;AAAA,IACtC;AAAA,IACA,gBAAgB,eAAe;AAC7B,UAAI,QAAQ;AACV;AAAA,MAAA;AAGA,iBAAmB,gBAAgB;AAErC,aAAO,MAAM;AACX,gCAAwB,cAAc,WAAW;AAC7C,YAAA;AACJ,sBAAc,YAAY,IAAI,OAAO,KAAK,QAAQ;;AAC1C,gBAAA,QAAQ,YAAY,KAAK,GAAG;AAClC,gBAAM,YAAY,cAAc,aAC9B,uBAAuB,MACzB;AAEI,c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,kBAChD,aAAa,KAAK,CAAC;AAAA,gBAAA,EACnB,QAAQ,MAAM,SAAS,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAO9B;AAAA,kBACE,QAAQ;AAAA,kBACR,SAAS;AAAA,oBACP,gBAAgB;AAAA,kBAAA;AAAA,gBAClB;AAAA,cACF;AAAA,YAEJ;AAAA,UAAA;AAAA,QACF,CACD;AAAA,MACH;AAAA,IAAA;AAAA,EAEJ;AACF;AAOA,SAAS,wBAAwB,QAAsC;AACrE,QAAM,mBAAmB;AAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,WAAS,IAAI,OAAO,MAAM,SAAS,GAAG,IAAI,GAAG,KAAK;AAChD,QACE,iBAAiB;AAAA;AAAA,MAEf,OAAO,MAAM,CAAC,EAAE,OAAO;AAAA,IAAA,GAEzB;AACO,aAAA,MAAM,OAAO,GAAG,CAAC;AAAA,IAAA;AAAA,EAC1B;AAEJ;AAQA,SAAS,aAAa,KAA8B,OAAgB;AAClE,QAAM,IAAI;AACH,SAAA;AAAA,IACL,SAAS,2CAA2C,IAAI,GAAG;AAAA;AAAA,GACzD,OAAO,MAAM,WAAW,IAAI,EAAE,OAChC;AAAA,IACA,OAAO,OAAO,MAAM,WAAW,KAAK,EAAE;AAAA,EACxC;AACF;"}
|
|
@@ -4,6 +4,7 @@ import { createNitro, build } from "nitropack";
|
|
|
4
4
|
import { resolve, dirname } from "pathe";
|
|
5
5
|
import { clientDistDir, ssrEntryFile } from "../plugin.js";
|
|
6
6
|
import { prerender } from "../prerender.js";
|
|
7
|
+
import { VITE_ENVIRONMENT_NAMES } from "../constants.js";
|
|
7
8
|
import { devServerPlugin } from "./dev-server-plugin.js";
|
|
8
9
|
import { buildNitroEnvironment } from "./build-nitro.js";
|
|
9
10
|
function nitroPlugin(options, getSsrBundle) {
|
|
@@ -13,7 +14,7 @@ function nitroPlugin(options, getSsrBundle) {
|
|
|
13
14
|
{
|
|
14
15
|
name: "tanstack-vite-plugin-nitro",
|
|
15
16
|
configEnvironment(name) {
|
|
16
|
-
if (name ===
|
|
17
|
+
if (name === VITE_ENVIRONMENT_NAMES.server) {
|
|
17
18
|
return {
|
|
18
19
|
build: {
|
|
19
20
|
commonjsOptions: {
|
|
@@ -34,9 +35,9 @@ function nitroPlugin(options, getSsrBundle) {
|
|
|
34
35
|
builder: {
|
|
35
36
|
sharedPlugins: true,
|
|
36
37
|
async buildApp(builder) {
|
|
37
|
-
var _a;
|
|
38
|
-
const clientEnv = builder.environments[
|
|
39
|
-
const serverEnv = builder.environments[
|
|
38
|
+
var _a, _b;
|
|
39
|
+
const clientEnv = builder.environments[VITE_ENVIRONMENT_NAMES.client];
|
|
40
|
+
const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server];
|
|
40
41
|
if (!clientEnv) {
|
|
41
42
|
throw new Error("Client environment not found");
|
|
42
43
|
}
|
|
@@ -69,7 +70,25 @@ function nitroPlugin(options, getSsrBundle) {
|
|
|
69
70
|
};
|
|
70
71
|
const nitro = await createNitro(nitroConfig);
|
|
71
72
|
await buildNitroEnvironment(nitro, () => build(nitro));
|
|
72
|
-
if ((_a = options.
|
|
73
|
+
if ((_a = options.spa) == null ? void 0 : _a.enabled) {
|
|
74
|
+
options.prerender = {
|
|
75
|
+
...options.prerender,
|
|
76
|
+
enabled: true
|
|
77
|
+
};
|
|
78
|
+
const maskUrl = new URL(
|
|
79
|
+
options.spa.maskPath,
|
|
80
|
+
"http://localhost"
|
|
81
|
+
);
|
|
82
|
+
maskUrl.searchParams.set("__TSS_SHELL", "true");
|
|
83
|
+
options.pages.push({
|
|
84
|
+
path: maskUrl.toString().replace("http://localhost", ""),
|
|
85
|
+
prerender: options.spa.prerender,
|
|
86
|
+
sitemap: {
|
|
87
|
+
exclude: true
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
if ((_b = options.prerender) == null ? void 0 : _b.enabled) {
|
|
73
92
|
await prerender({
|
|
74
93
|
options,
|
|
75
94
|
nitro,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nitro-plugin.js","sources":["../../../src/nitro/nitro-plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { rmSync } from 'node:fs'\nimport { build, createNitro } from 'nitropack'\nimport { dirname, resolve } from 'pathe'\nimport { clientDistDir, ssrEntryFile } from '../plugin'\nimport { prerender } from '../prerender'\nimport { devServerPlugin } from './dev-server-plugin'\nimport { buildNitroEnvironment } from './build-nitro'\nimport type { EnvironmentOptions, PluginOption, Rollup } from 'vite'\nimport type { NitroConfig } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\n\nexport function nitroPlugin(\n options: TanStackStartOutputConfig,\n getSsrBundle: () => Rollup.OutputBundle,\n): Array<PluginOption> {\n const buildPreset =\n process.env['START_TARGET'] ?? (options.target as string | undefined)\n\n return [\n devServerPlugin(),\n {\n name: 'tanstack-vite-plugin-nitro',\n configEnvironment(name) {\n if (name ===
|
|
1
|
+
{"version":3,"file":"nitro-plugin.js","sources":["../../../src/nitro/nitro-plugin.ts"],"sourcesContent":["import path from 'node:path'\nimport { rmSync } from 'node:fs'\nimport { build, createNitro } from 'nitropack'\nimport { dirname, resolve } from 'pathe'\nimport { clientDistDir, ssrEntryFile } from '../plugin'\nimport { prerender } from '../prerender'\nimport { VITE_ENVIRONMENT_NAMES } from '../constants'\nimport { devServerPlugin } from './dev-server-plugin'\nimport { buildNitroEnvironment } from './build-nitro'\nimport type { EnvironmentOptions, PluginOption, Rollup } from 'vite'\nimport type { NitroConfig } from 'nitropack'\nimport type { TanStackStartOutputConfig } from '../plugin'\n\nexport function nitroPlugin(\n options: TanStackStartOutputConfig,\n getSsrBundle: () => Rollup.OutputBundle,\n): Array<PluginOption> {\n const buildPreset =\n process.env['START_TARGET'] ?? (options.target as string | undefined)\n\n return [\n devServerPlugin(),\n {\n name: 'tanstack-vite-plugin-nitro',\n configEnvironment(name) {\n if (name === VITE_ENVIRONMENT_NAMES.server) {\n return {\n build: {\n commonjsOptions: {\n include: [],\n },\n ssr: true,\n sourcemap: true,\n rollupOptions: {\n input: '/~start/server-entry',\n },\n },\n } satisfies EnvironmentOptions\n }\n\n return null\n },\n config() {\n return {\n builder: {\n sharedPlugins: true,\n async buildApp(builder) {\n const clientEnv =\n builder.environments[VITE_ENVIRONMENT_NAMES.client]\n const serverEnv =\n builder.environments[VITE_ENVIRONMENT_NAMES.server]\n\n if (!clientEnv) {\n throw new Error('Client environment not found')\n }\n\n if (!serverEnv) {\n throw new Error('SSR environment not found')\n }\n\n const clientOutputDir = resolve(options.root, clientDistDir)\n rmSync(clientOutputDir, { recursive: true, force: true })\n await builder.build(clientEnv)\n\n await builder.build(serverEnv)\n\n const nitroConfig: NitroConfig = {\n dev: false,\n // TODO do we need this? should this be made configurable?\n compatibilityDate: '2024-11-19',\n logLevel: 3,\n preset: buildPreset,\n publicAssets: [\n {\n dir: path.resolve(options.root, clientDistDir),\n },\n ],\n typescript: {\n generateTsConfig: false,\n },\n prerender: undefined,\n renderer: ssrEntryFile,\n rollupConfig: {\n plugins: [virtualBundlePlugin(getSsrBundle())],\n },\n }\n\n const nitro = await createNitro(nitroConfig)\n\n await buildNitroEnvironment(nitro, () => build(nitro))\n\n if (options.spa?.enabled) {\n options.prerender = {\n ...options.prerender,\n enabled: true,\n }\n\n const maskUrl = new URL(\n options.spa.maskPath,\n 'http://localhost',\n )\n\n maskUrl.searchParams.set('__TSS_SHELL', 'true')\n\n options.pages.push({\n path: maskUrl.toString().replace('http://localhost', ''),\n prerender: options.spa.prerender,\n sitemap: {\n exclude: true,\n },\n })\n }\n\n if (options.prerender?.enabled) {\n await prerender({\n options,\n nitro,\n builder,\n })\n }\n\n // if (nitroConfig.prerender?.routes?.length && options.sitemap) {\n // console.log('Building Sitemap...')\n // // sitemap needs to be built after all directories are built\n // await buildSitemap({\n // host: options.sitemap.host,\n // routes: nitroConfig.prerender.routes,\n // outputDir: resolve(options.root, 'dist/public'),\n // })\n // }\n\n // console.log(\n // `\\n\\n✅ Client and server bundles successfully built.`,\n // )\n },\n },\n }\n },\n },\n ]\n}\n\nfunction virtualBundlePlugin(ssrBundle: Rollup.OutputBundle): Rollup.Plugin {\n type VirtualModule = { code: string; map: string | null }\n const _modules = new Map<string, VirtualModule>()\n\n // group chunks and source maps\n for (const [fileName, content] of Object.entries(ssrBundle)) {\n if (content.type === 'chunk') {\n const virtualModule: VirtualModule = {\n code: content.code,\n map: null,\n }\n const maybeMap = ssrBundle[`${fileName}.map`]\n if (maybeMap && maybeMap.type === 'asset') {\n virtualModule.map = maybeMap.source as string\n }\n _modules.set(fileName, virtualModule)\n _modules.set(resolve(fileName), virtualModule)\n }\n }\n\n return {\n name: 'virtual-bundle',\n resolveId(id, importer) {\n if (_modules.has(id)) {\n return resolve(id)\n }\n\n if (importer) {\n const resolved = resolve(dirname(importer), id)\n if (_modules.has(resolved)) {\n return resolved\n }\n }\n return null\n },\n load(id) {\n const m = _modules.get(id)\n if (!m) {\n return null\n }\n return m\n },\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AAagB,SAAA,YACd,SACA,cACqB;AACrB,QAAM,cACJ,QAAQ,IAAI,cAAc,KAAM,QAAQ;AAEnC,SAAA;AAAA,IACL,gBAAgB;AAAA,IAChB;AAAA,MACE,MAAM;AAAA,MACN,kBAAkB,MAAM;AAClB,YAAA,SAAS,uBAAuB,QAAQ;AACnC,iBAAA;AAAA,YACL,OAAO;AAAA,cACL,iBAAiB;AAAA,gBACf,SAAS,CAAA;AAAA,cACX;AAAA,cACA,KAAK;AAAA,cACL,WAAW;AAAA,cACX,eAAe;AAAA,gBACb,OAAO;AAAA,cAAA;AAAA,YACT;AAAA,UAEJ;AAAA,QAAA;AAGK,eAAA;AAAA,MACT;AAAA,MACA,SAAS;AACA,eAAA;AAAA,UACL,SAAS;AAAA,YACP,eAAe;AAAA,YACf,MAAM,SAAS,SAAS;;AACtB,oBAAM,YACJ,QAAQ,aAAa,uBAAuB,MAAM;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