@analogjs/platform 3.0.0-beta.5 → 3.0.0-beta.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/migrations/migrate-to-separated-plugins/migrate-to-separated-plugins.js +2 -1
  2. package/migrations/migrate-to-separated-plugins/migrate-to-separated-plugins.js.map +1 -1
  3. package/migrations/migrate-vitest-builder-aliases/migrate-vitest-builder-aliases.js +2 -1
  4. package/migrations/migrate-vitest-builder-aliases/migrate-vitest-builder-aliases.js.map +1 -1
  5. package/package.json +12 -9
  6. package/src/lib/content-plugin.js +12 -3
  7. package/src/lib/content-plugin.js.map +1 -1
  8. package/src/lib/deps-plugin.d.ts +1 -1
  9. package/src/lib/deps-plugin.js +11 -7
  10. package/src/lib/deps-plugin.js.map +1 -1
  11. package/src/lib/discover-library-routes.d.ts +3 -3
  12. package/src/lib/discover-library-routes.js +4 -4
  13. package/src/lib/discover-library-routes.js.map +1 -1
  14. package/src/lib/get-page-endpoints.d.ts +25 -0
  15. package/src/lib/get-page-endpoints.js +29 -0
  16. package/src/lib/get-page-endpoints.js.map +1 -0
  17. package/src/lib/nitro/analog-nitro-plugin.d.ts +6 -6
  18. package/src/lib/nitro/analog-nitro-plugin.js +116 -47
  19. package/src/lib/nitro/analog-nitro-plugin.js.map +1 -1
  20. package/src/lib/nitro/angular-linker-plugin.d.ts +4 -2
  21. package/src/lib/nitro/angular-linker-plugin.js +24 -38
  22. package/src/lib/nitro/angular-linker-plugin.js.map +1 -1
  23. package/src/lib/nitro/build-sitemap.js +2 -2
  24. package/src/lib/nitro/build-sitemap.js.map +1 -1
  25. package/src/lib/nitro/get-page-handlers.d.ts +4 -19
  26. package/src/lib/nitro/get-page-handlers.js +9 -26
  27. package/src/lib/nitro/get-page-handlers.js.map +1 -1
  28. package/src/lib/nitro/i18n-prerender.d.ts +2 -1
  29. package/src/lib/nitro/i18n-prerender.js +10 -7
  30. package/src/lib/nitro/i18n-prerender.js.map +1 -1
  31. package/src/lib/nitro/server-fn-endpoints.d.ts +3 -1
  32. package/src/lib/nitro/server-fn-endpoints.js +14 -5
  33. package/src/lib/nitro/server-fn-endpoints.js.map +1 -1
  34. package/src/lib/nx-plugin/executors.json +0 -7
  35. package/src/lib/nx-plugin/src/generators/app/compat.d.ts +2 -1
  36. package/src/lib/nx-plugin/src/generators/app/compat.js +4 -1
  37. package/src/lib/nx-plugin/src/generators/app/compat.js.map +1 -1
  38. package/src/lib/nx-plugin/src/generators/app/generator.js +7 -2
  39. package/src/lib/nx-plugin/src/generators/app/generator.js.map +1 -1
  40. package/src/lib/nx-plugin/src/generators/app/lib/add-tailwind-helpers.js +2 -2
  41. package/src/lib/nx-plugin/src/generators/app/lib/add-tailwind-helpers.js.map +1 -1
  42. package/src/lib/nx-plugin/src/generators/app/versions/minimum-supported-versions.d.ts +3 -1
  43. package/src/lib/nx-plugin/src/generators/app/versions/minimum-supported-versions.js +5 -1
  44. package/src/lib/nx-plugin/src/generators/app/versions/minimum-supported-versions.js.map +1 -1
  45. package/src/lib/nx-plugin/src/generators/init/compat.d.ts +2 -1
  46. package/src/lib/nx-plugin/src/generators/init/compat.js +4 -1
  47. package/src/lib/nx-plugin/src/generators/init/compat.js.map +1 -1
  48. package/src/lib/nx-plugin/src/generators/init/lib/add-analog-dependencies.js +2 -2
  49. package/src/lib/nx-plugin/src/generators/init/lib/add-analog-dependencies.js.map +1 -1
  50. package/src/lib/nx-plugin/src/generators/page/compat.d.ts +2 -1
  51. package/src/lib/nx-plugin/src/generators/page/compat.js +4 -1
  52. package/src/lib/nx-plugin/src/generators/page/compat.js.map +1 -1
  53. package/src/lib/nx-plugin/src/generators/preset/__snapshots__/generator.spec.ts.snap +4 -0
  54. package/src/lib/nx-plugin/src/generators/preset/generator.js +5 -2
  55. package/src/lib/nx-plugin/src/generators/preset/generator.js.map +1 -1
  56. package/src/lib/nx-plugin/src/utils/versions/dev-dependencies.d.ts +2 -2
  57. package/src/lib/nx-plugin/src/utils/versions/dev-dependencies.js +7 -3
  58. package/src/lib/nx-plugin/src/utils/versions/dev-dependencies.js.map +1 -1
  59. package/src/lib/nx-plugin/src/utils/versions/versions.d.ts +9 -6
  60. package/src/lib/nx-plugin/src/utils/versions/versions.js +13 -7
  61. package/src/lib/nx-plugin/src/utils/versions/versions.js.map +1 -1
  62. package/src/lib/options.d.ts +16 -0
  63. package/src/lib/platform-plugin.js +2 -0
  64. package/src/lib/platform-plugin.js.map +1 -1
  65. package/src/lib/route-file-discovery.js +8 -4
  66. package/src/lib/route-file-discovery.js.map +1 -1
  67. package/src/lib/route-idiom-diagnostics.js +23 -8
  68. package/src/lib/route-idiom-diagnostics.js.map +1 -1
  69. package/src/lib/route-manifest.d.ts +1 -1
  70. package/src/lib/route-manifest.js +6 -6
  71. package/src/lib/route-manifest.js.map +1 -1
  72. package/src/lib/router-plugin.js +7 -3
  73. package/src/lib/router-plugin.js.map +1 -1
  74. package/src/lib/server-plugin.d.ts +9 -0
  75. package/src/lib/server-plugin.js +170 -0
  76. package/src/lib/server-plugin.js.map +1 -0
  77. package/src/lib/typed-routes-plugin.js +6 -5
  78. package/src/lib/typed-routes-plugin.js.map +1 -1
  79. package/src/server-mode-plugin.js +1 -0
  80. package/src/server-mode-plugin.js.map +1 -1
  81. package/src/lib/nx-plugin/src/executors/vite-dev-server/compat.d.ts +0 -3
  82. package/src/lib/nx-plugin/src/executors/vite-dev-server/compat.js +0 -7
  83. package/src/lib/nx-plugin/src/executors/vite-dev-server/compat.js.map +0 -1
  84. package/src/lib/nx-plugin/src/executors/vite-dev-server/schema.d.ts +0 -1
  85. package/src/lib/nx-plugin/src/executors/vite-dev-server/schema.json +0 -101
  86. package/src/lib/nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.d.ts +0 -2
  87. package/src/lib/nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.js +0 -6
  88. package/src/lib/nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"route-idiom-diagnostics.js","names":[],"sources":["../../../src/lib/route-idiom-diagnostics.ts"],"sourcesContent":["import { parseSync, type OxcError, type Severity } from 'oxc-parser';\nimport { relative } from 'node:path';\nimport { normalizePath } from 'vite';\n\nexport interface AnalogRouteIdiomDiagnostic {\n code: string;\n severity: 'error' | 'warning';\n message: string;\n details?: string;\n}\n\nexport interface AnalyzeAnalogRouteFileOptions {\n filename: string;\n code: string;\n routeFiles?: string[];\n}\n\nconst PAGE_FILE_RE = /\\.page\\.ts$/;\nconst ROUTER_OUTLET_RE = /\\bRouterOutlet\\b|<router-outlet(?:\\s|>)/;\n\nexport function analyzeAnalogRouteFile(\n options: AnalyzeAnalogRouteFileOptions,\n): AnalogRouteIdiomDiagnostic[] {\n const { filename, code, routeFiles = [] } = options;\n const parseResult = parseSync(filename, code, {\n lang: 'ts',\n sourceType: 'module',\n range: true,\n showSemanticErrors: true,\n });\n\n const parseDiagnostics = parseResult.errors.map((error) =>\n toParseDiagnostic(error),\n );\n\n if (parseDiagnostics.some((diagnostic) => diagnostic.severity === 'error')) {\n return parseDiagnostics;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const program: any = parseResult.program;\n const exportedBindings = collectExportedBindings(program);\n const routeMetaBindingName = exportedBindings.routeMeta;\n const diagnostics = [...parseDiagnostics];\n\n const routeMetaInfo = routeMetaBindingName\n ? getRouteMetaInfo(program, routeMetaBindingName)\n : null;\n\n if (!exportedBindings.hasDefaultExport && !routeMetaInfo?.hasRedirect) {\n diagnostics.push({\n code: 'missing-default-export',\n severity: 'warning',\n message:\n 'Route files should default-export the page component, unless they are redirect-only routes.',\n details:\n 'Add `export default class ...` or define `routeMeta.redirectTo` for a redirect route.',\n });\n }\n\n if (exportedBindings.hasDefaultExport && routeMetaInfo?.hasRedirect) {\n diagnostics.push({\n code: 'redirect-with-component',\n severity: 'warning',\n message: 'Redirect routes should not also export a page component.',\n details:\n 'Analog ignores the default export when `routeMeta.redirectTo` is present. Remove the component export or remove the redirect.',\n });\n }\n\n if (\n routeMetaInfo?.hasRedirect &&\n routeMetaInfo.redirectTo &&\n !routeMetaInfo.redirectTo.startsWith('/')\n ) {\n diagnostics.push({\n code: 'relative-redirect',\n severity: 'warning',\n message: '`routeMeta.redirectTo` should use an absolute path.',\n details:\n 'Nested redirects are documented to use absolute targets such as `/cities/new-york`.',\n });\n }\n\n if (\n isLikelyLayoutRoute(filename, routeFiles) &&\n !ROUTER_OUTLET_RE.test(code)\n ) {\n diagnostics.push({\n code: 'layout-without-router-outlet',\n severity: 'warning',\n message:\n 'This route file looks like a layout shell, but it does not reference `RouterOutlet` or `<router-outlet>`.',\n details:\n 'Parent layout pages usually import `RouterOutlet` and render an outlet so child routes have somewhere to mount.',\n });\n }\n\n return diagnostics;\n}\n\nexport function formatAnalogRouteIdiomDiagnostic(\n diagnostic: AnalogRouteIdiomDiagnostic,\n filename: string,\n workspaceRoot: string,\n): string {\n const displayName = toDisplayPath(filename, workspaceRoot);\n const header = `[Analog] ${displayName} (${diagnostic.code})`;\n const severity = diagnostic.severity.toUpperCase();\n\n if (diagnostic.details) {\n return `${header}\\n${severity}: ${diagnostic.message}\\n${diagnostic.details}`;\n }\n\n return `${header}\\n${severity}: ${diagnostic.message}`;\n}\n\nfunction toDisplayPath(filename: string, workspaceRoot: string): string {\n const normalizedFilename = normalizePath(filename);\n const normalizedRoot = normalizePath(workspaceRoot);\n const relativePath = normalizePath(\n relative(normalizedRoot, normalizedFilename),\n );\n\n if (relativePath && !relativePath.startsWith('..')) {\n return `/${relativePath}`;\n }\n\n return normalizedFilename;\n}\n\nfunction toParseDiagnostic(error: OxcError): AnalogRouteIdiomDiagnostic {\n return {\n code: 'oxc-parse',\n severity: error.severity === severityError ? 'error' : 'warning',\n message: error.message,\n details: error.codeframe ?? error.helpMessage ?? undefined,\n };\n}\n\nconst severityError: Severity = 'Error';\n\nfunction isLikelyLayoutRoute(filename: string, routeFiles: string[]): boolean {\n if (!PAGE_FILE_RE.test(filename)) {\n return false;\n }\n\n const routeStem = filename.replace(PAGE_FILE_RE, '');\n return routeFiles.some(\n (routeFile) =>\n routeFile !== filename && routeFile.startsWith(`${routeStem}/`),\n );\n}\n\nfunction getRouteMetaInfo(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n program: any,\n bindingName: string,\n): {\n hasRedirect: boolean;\n redirectTo?: string;\n} | null {\n const routeMetaNode = getExportedBindingInitializer(program, bindingName);\n\n if (routeMetaNode?.type !== 'ObjectExpression') {\n return null;\n }\n\n let redirectTo: string | undefined;\n\n for (const property of routeMetaNode.properties ?? []) {\n if (property?.type !== 'Property') {\n continue;\n }\n\n const keyName = getPropertyName(property.key);\n if (keyName !== 'redirectTo') {\n continue;\n }\n\n redirectTo = getStringValue(property.value);\n }\n\n return {\n hasRedirect: typeof redirectTo === 'string' && redirectTo.length > 0,\n redirectTo,\n };\n}\n\nfunction getExportedBindingInitializer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n program: any,\n bindingName: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any | undefined {\n for (const statement of program.body ?? []) {\n if (statement?.type === 'VariableDeclaration') {\n const initializer = getVariableInitializer(statement, bindingName);\n if (initializer) {\n return initializer;\n }\n continue;\n }\n\n if (\n statement?.type === 'ExportNamedDeclaration' &&\n statement.declaration?.type === 'VariableDeclaration'\n ) {\n const initializer = getVariableInitializer(\n statement.declaration,\n bindingName,\n );\n if (initializer) {\n return initializer;\n }\n }\n }\n\n return undefined;\n}\n\nfunction getVariableInitializer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n declaration: any,\n bindingName: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any | undefined {\n for (const declarator of declaration.declarations ?? []) {\n if (\n declarator.id?.type === 'Identifier' &&\n declarator.id.name === bindingName\n ) {\n return declarator.init;\n }\n }\n\n return undefined;\n}\n\nfunction collectExportedBindings(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n program: any,\n): {\n hasDefaultExport: boolean;\n routeMeta?: string;\n} {\n let hasDefaultExport = false;\n let routeMeta: string | undefined;\n\n for (const statement of program.body ?? []) {\n if (statement?.type === 'ExportDefaultDeclaration') {\n hasDefaultExport = true;\n continue;\n }\n\n if (statement?.type !== 'ExportNamedDeclaration') {\n continue;\n }\n\n const declaration = statement.declaration;\n if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations ?? []) {\n if (declarator.id?.type !== 'Identifier') {\n continue;\n }\n\n if (declarator.id.name === 'routeMeta') {\n routeMeta = 'routeMeta';\n }\n }\n }\n\n for (const specifier of statement.specifiers ?? []) {\n if (\n specifier?.type !== 'ExportSpecifier' ||\n specifier.local?.type !== 'Identifier'\n ) {\n continue;\n }\n\n if (specifier.exported?.type !== 'Identifier') {\n continue;\n }\n\n if (specifier.exported.name === 'routeMeta') {\n routeMeta = specifier.local.name;\n }\n }\n }\n\n return {\n hasDefaultExport,\n routeMeta,\n };\n}\n\nfunction getPropertyName(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: any,\n): string | undefined {\n if (node?.type === 'Identifier') {\n return node.name;\n }\n\n if (\n (node?.type === 'Literal' || node?.type === 'StringLiteral') &&\n typeof node.value === 'string'\n ) {\n return node.value;\n }\n\n return undefined;\n}\n\nfunction getStringValue(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: any,\n): string | undefined {\n if (\n (node?.type === 'Literal' || node?.type === 'StringLiteral') &&\n typeof node.value === 'string'\n ) {\n return node.value;\n }\n\n if (\n node?.type === 'TemplateLiteral' &&\n node.expressions?.length === 0 &&\n node.quasis?.length === 1\n ) {\n return node.quasis[0].value.cooked ?? node.quasis[0].value.raw;\n }\n\n return undefined;\n}\n"],"mappings":";;;;AAiBA,IAAM,eAAe;AACrB,IAAM,mBAAmB;AAEzB,SAAgB,uBACd,SAC8B;CAC9B,MAAM,EAAE,UAAU,MAAM,aAAa,CAAC,MAAM;CAC5C,MAAM,cAAc,UAA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version":3,"file":"route-idiom-diagnostics.js","names":[],"sources":["../../../src/lib/route-idiom-diagnostics.ts"],"sourcesContent":["import { parseSync, type OxcError, type Severity } from 'oxc-parser';\nimport { relative } from 'node:path';\nimport { normalizePath } from 'vite';\n\nexport interface AnalogRouteIdiomDiagnostic {\n code: string;\n severity: 'error' | 'warning';\n message: string;\n details?: string;\n}\n\nexport interface AnalyzeAnalogRouteFileOptions {\n filename: string;\n code: string;\n routeFiles?: string[];\n}\n\nconst PAGE_FILE_RE = /\\.page\\.ts$/;\nconst ROUTER_OUTLET_RE = /\\bRouterOutlet\\b|<router-outlet(?:\\s|>)/;\n\n// Valid AST node types: grouping parentheses, as, satisfies, angle-bracket type assertion\nconst WRAPPER_EXPRESSIONS = new Set([\n 'ParenthesizedExpression',\n 'TSAsExpression',\n 'TSSatisfiesExpression',\n 'TSTypeAssertion',\n]);\n\nexport function analyzeAnalogRouteFile(\n options: AnalyzeAnalogRouteFileOptions,\n): AnalogRouteIdiomDiagnostic[] {\n const { filename, code, routeFiles = [] } = options;\n const parseResult = parseSync(filename, code, {\n lang: 'ts',\n sourceType: 'module',\n range: true,\n showSemanticErrors: true,\n });\n\n const parseDiagnostics = parseResult.errors.map((error) =>\n toParseDiagnostic(error),\n );\n\n if (parseDiagnostics.some((diagnostic) => diagnostic.severity === 'error')) {\n return parseDiagnostics;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const program: any = parseResult.program;\n const exportedBindings = collectExportedBindings(program);\n const routeMetaBindingName = exportedBindings.routeMeta;\n const diagnostics = [...parseDiagnostics];\n\n const routeMetaInfo = routeMetaBindingName\n ? getRouteMetaInfo(program, routeMetaBindingName)\n : null;\n\n if (!exportedBindings.hasDefaultExport && !routeMetaInfo?.hasRedirect) {\n diagnostics.push({\n code: 'missing-default-export',\n severity: 'warning',\n message:\n 'Route files should default-export the page component, unless they are redirect-only routes.',\n details:\n 'Add `export default class ...` or define `routeMeta.redirectTo` for a redirect route.',\n });\n }\n\n if (exportedBindings.hasDefaultExport && routeMetaInfo?.hasRedirect) {\n diagnostics.push({\n code: 'redirect-with-component',\n severity: 'warning',\n message: 'Redirect routes should not also export a page component.',\n details:\n 'Analog ignores the default export when `routeMeta.redirectTo` is present. Remove the component export or remove the redirect.',\n });\n }\n\n if (\n routeMetaInfo?.redirectTarget &&\n !routeMetaInfo.redirectTarget.startsWith('/')\n ) {\n diagnostics.push({\n code: 'relative-redirect',\n severity: 'warning',\n message: '`routeMeta.redirectTo` should use an absolute path.',\n details:\n 'Nested redirects are documented to use absolute targets such as `/cities/new-york`.',\n });\n }\n\n if (\n isLikelyLayoutRoute(filename, routeFiles) &&\n !ROUTER_OUTLET_RE.test(code)\n ) {\n diagnostics.push({\n code: 'layout-without-router-outlet',\n severity: 'warning',\n message:\n 'This route file looks like a layout shell, but it does not reference `RouterOutlet` or `<router-outlet>`.',\n details:\n 'Parent layout pages usually import `RouterOutlet` and render an outlet so child routes have somewhere to mount.',\n });\n }\n\n return diagnostics;\n}\n\nexport function formatAnalogRouteIdiomDiagnostic(\n diagnostic: AnalogRouteIdiomDiagnostic,\n filename: string,\n workspaceRoot: string,\n): string {\n const displayName = toDisplayPath(filename, workspaceRoot);\n const header = `[Analog] ${displayName} (${diagnostic.code})`;\n const severity = diagnostic.severity.toUpperCase();\n\n if (diagnostic.details) {\n return `${header}\\n${severity}: ${diagnostic.message}\\n${diagnostic.details}`;\n }\n\n return `${header}\\n${severity}: ${diagnostic.message}`;\n}\n\nfunction toDisplayPath(filename: string, workspaceRoot: string): string {\n const normalizedFilename = normalizePath(filename);\n const normalizedRoot = normalizePath(workspaceRoot);\n const relativePath = normalizePath(\n relative(normalizedRoot, normalizedFilename),\n );\n\n if (relativePath && !relativePath.startsWith('..')) {\n return `/${relativePath}`;\n }\n\n return normalizedFilename;\n}\n\nfunction toParseDiagnostic(error: OxcError): AnalogRouteIdiomDiagnostic {\n return {\n code: 'oxc-parse',\n severity: error.severity === severityError ? 'error' : 'warning',\n message: error.message,\n details: error.codeframe ?? error.helpMessage ?? undefined,\n };\n}\n\nconst severityError: Severity = 'Error';\n\nfunction isLikelyLayoutRoute(filename: string, routeFiles: string[]): boolean {\n if (!PAGE_FILE_RE.test(filename)) {\n return false;\n }\n\n const routeStem = filename.replace(PAGE_FILE_RE, '');\n return routeFiles.some(\n (routeFile) =>\n routeFile !== filename && routeFile.startsWith(`${routeStem}/`),\n );\n}\n\nfunction getRouteMetaInfo(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n program: any,\n bindingName: string,\n): {\n hasRedirect: boolean;\n redirectTarget?: string;\n} | null {\n const routeMetaNode = unwrapExpression(\n getExportedBindingInitializer(program, bindingName),\n );\n\n if (routeMetaNode?.type !== 'ObjectExpression') {\n return null;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let redirectTo: any;\n\n for (const property of routeMetaNode.properties ?? []) {\n if (property?.type !== 'Property') {\n continue;\n }\n\n const keyName = getPropertyName(property.key);\n\n if (keyName !== 'redirectTo') {\n continue;\n }\n\n redirectTo = property.value;\n }\n\n const value = unwrapExpression(redirectTo);\n\n if (!value || isNullish(value)) {\n return { hasRedirect: false };\n }\n\n return {\n hasRedirect: true,\n redirectTarget: getStaticRedirectTarget(value),\n };\n}\n\nfunction getExportedBindingInitializer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n program: any,\n bindingName: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any | undefined {\n for (const statement of program.body ?? []) {\n if (statement?.type === 'VariableDeclaration') {\n const initializer = getVariableInitializer(statement, bindingName);\n if (initializer) {\n return initializer;\n }\n continue;\n }\n\n if (\n statement?.type === 'ExportNamedDeclaration' &&\n statement.declaration?.type === 'VariableDeclaration'\n ) {\n const initializer = getVariableInitializer(\n statement.declaration,\n bindingName,\n );\n if (initializer) {\n return initializer;\n }\n }\n }\n\n return undefined;\n}\n\nfunction getVariableInitializer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n declaration: any,\n bindingName: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any | undefined {\n for (const declarator of declaration.declarations ?? []) {\n if (\n declarator.id?.type === 'Identifier' &&\n declarator.id.name === bindingName\n ) {\n return declarator.init;\n }\n }\n\n return undefined;\n}\n\nfunction collectExportedBindings(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n program: any,\n): {\n hasDefaultExport: boolean;\n routeMeta?: string;\n} {\n let hasDefaultExport = false;\n let routeMeta: string | undefined;\n\n for (const statement of program.body ?? []) {\n if (statement?.type === 'ExportDefaultDeclaration') {\n hasDefaultExport = true;\n continue;\n }\n\n if (statement?.type !== 'ExportNamedDeclaration') {\n continue;\n }\n\n const declaration = statement.declaration;\n if (declaration?.type === 'VariableDeclaration') {\n for (const declarator of declaration.declarations ?? []) {\n if (declarator.id?.type !== 'Identifier') {\n continue;\n }\n\n if (declarator.id.name === 'routeMeta') {\n routeMeta = 'routeMeta';\n }\n }\n }\n\n for (const specifier of statement.specifiers ?? []) {\n if (\n specifier?.type !== 'ExportSpecifier' ||\n specifier.local?.type !== 'Identifier'\n ) {\n continue;\n }\n\n if (specifier.exported?.type !== 'Identifier') {\n continue;\n }\n\n if (specifier.exported.name === 'routeMeta') {\n routeMeta = specifier.local.name;\n }\n }\n }\n\n return {\n hasDefaultExport,\n routeMeta,\n };\n}\n\nfunction getPropertyName(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: any,\n): string | undefined {\n if (node?.type === 'Identifier') {\n return node.name;\n }\n\n if (\n (node?.type === 'Literal' || node?.type === 'StringLiteral') &&\n typeof node.value === 'string'\n ) {\n return node.value;\n }\n\n return undefined;\n}\n\nfunction getStaticRedirectTarget(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: any,\n): string | undefined {\n if (\n (node.type === 'Literal' || node.type === 'StringLiteral') &&\n typeof node.value === 'string'\n ) {\n return node.value;\n }\n\n if (node.type === 'TemplateLiteral') {\n const lead = node.quasis?.[0]?.value.cooked ?? node.quasis?.[0]?.value.raw;\n return lead || undefined;\n }\n\n return undefined;\n}\n\nfunction isNullish(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: any,\n): boolean {\n return (\n (node.type === 'Literal' && node.value === null) ||\n (node.type === 'Identifier' && node.name === 'undefined') ||\n (node.type === 'UnaryExpression' && node.operator === 'void')\n );\n}\n\nfunction unwrapExpression(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any | undefined {\n while (node && WRAPPER_EXPRESSIONS.has(node.type)) {\n node = node.expression;\n }\n\n return node;\n}\n"],"mappings":";;;;AAiBA,IAAM,eAAe;AACrB,IAAM,mBAAmB;AAGzB,IAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,uBACd,SAC8B;CAC9B,MAAM,EAAE,UAAU,MAAM,aAAa,CAAC,MAAM;CAC5C,MAAM,cAAc,UAAU,UAAU,MAAM;EAC5C,MAAM;EACN,YAAY;EACZ,OAAO;EACP,oBAAoB;CACtB,CAAC;CAED,MAAM,mBAAmB,YAAY,OAAO,KAAK,UAC/C,kBAAkB,KAAK,CACzB;CAEA,IAAI,iBAAiB,MAAM,eAAe,WAAW,aAAa,OAAO,GACvE,OAAO;CAIT,MAAM,UAAe,YAAY;CACjC,MAAM,mBAAmB,wBAAwB,OAAO;CACxD,MAAM,uBAAuB,iBAAiB;CAC9C,MAAM,cAAc,CAAC,GAAG,gBAAgB;CAExC,MAAM,gBAAgB,uBAClB,iBAAiB,SAAS,oBAAoB,IAC9C;CAEJ,IAAI,CAAC,iBAAiB,oBAAoB,CAAC,eAAe,aACxD,YAAY,KAAK;EACf,MAAM;EACN,UAAU;EACV,SACE;EACF,SACE;CACJ,CAAC;CAGH,IAAI,iBAAiB,oBAAoB,eAAe,aACtD,YAAY,KAAK;EACf,MAAM;EACN,UAAU;EACV,SAAS;EACT,SACE;CACJ,CAAC;CAGH,IACE,eAAe,kBAC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EAEhB;EAGF,KAAK,MAAM,aAAa,UAAU,cAAc,CAAC,GAAG;GAClD,IACE,WAAW,SAAS,qBACpB,UAAU,OAAO,SAAS,cAE1B;GAGF,IAAI,UAAU,UAAU,SAAS,cAC/B;GAGF,IAAI,UAAU,SAAS,SAAS,aAC9B,YAAY,UAAU,MAAM;EAEhC;CACF;CAEA,OAAO;EACL;EACA;CACF;AACF;AAEA,SAAS,gBAEP,MACoB;CACpB,IAAI,MAAM,SAAS,cACjB,OAAO,KAAK;CAGd,KACG,MAAM,SAAS,aAAa,MAAM,SAAS,oBAC5C,OAAO,KAAK,UAAU,UAEtB,OAAO,KAAK;AAIhB;AAEA,SAAS,wBAEP,MACoB;CACpB,KACG,KAAK,SAAS,aAAa,KAAK,SAAS,oBAC1C,OAAO,KAAK,UAAU,UAEtB,OAAO,KAAK;CAGd,IAAI,KAAK,SAAS,mBAEhB,QADa,KAAK,SAAS,EAAE,EAAE,MAAM,UAAU,KAAK,SAAS,EAAE,EAAE,MAAM,QACxD,KAAA;AAInB;AAEA,SAAS,UAEP,MACS;CACT,OACG,KAAK,SAAS,aAAa,KAAK,UAAU,QAC1C,KAAK,SAAS,gBAAgB,KAAK,SAAS,eAC5C,KAAK,SAAS,qBAAqB,KAAK,aAAa;AAE1D;AAEA,SAAS,iBAEP,MAEiB;CACjB,OAAO,QAAQ,oBAAoB,IAAI,KAAK,IAAI,GAC9C,OAAO,KAAK;CAGd,OAAO;AACT"}
@@ -65,7 +65,7 @@ export interface RouteManifest {
65
65
  * (`/libs/shared/feature/src/content/`) uniformly.
66
66
  * 2. `[\\/](?:app[\\/]pages|src[\\/]content)[\\/]` — non-anchored
67
67
  * fallback for paths where the directory marker appears mid-string.
68
- * 3. `\.page\.(js|ts)$` — strips page file extensions.
68
+ * 3. `\.page\.(js|ts|tsrx)$` — strips page file extensions.
69
69
  * 4. `\.(ts|md)$` — strips remaining file extensions.
70
70
  *
71
71
  * Examples:
@@ -13,7 +13,7 @@
13
13
  * (`/libs/shared/feature/src/content/`) uniformly.
14
14
  * 2. `[\\/](?:app[\\/]pages|src[\\/]content)[\\/]` — non-anchored
15
15
  * fallback for paths where the directory marker appears mid-string.
16
- * 3. `\.page\.(js|ts)$` — strips page file extensions.
16
+ * 3. `\.page\.(js|ts|tsrx)$` — strips page file extensions.
17
17
  * 4. `\.(ts|md)$` — strips remaining file extensions.
18
18
  *
19
19
  * Examples:
@@ -27,7 +27,7 @@
27
27
  * - '/libs/shared/feature/src/content/test.md' -> '/test'
28
28
  */
29
29
  function filenameToRoutePath(filename) {
30
- let path = filename.replace(/^(?:[a-zA-Z]:[\\/])?(.*?)[\\/](?:routes|pages|content)[\\/]|(?:[\\/](?:app[\\/]pages|src[\\/]content)[\\/])|(\.page\.(js|ts)$)|(\.(ts|md)$)/g, "");
30
+ let path = filename.replace(/^(?:[a-zA-Z]:[\\/])?(.*?)[\\/](?:routes|pages|content)[\\/]|(?:[\\/](?:app[\\/]pages|src[\\/]content)[\\/])|(\.page\.(js|ts|tsrx)$)|(\.(ts|md)$)/g, "");
31
31
  const brackets = [];
32
32
  path = path.replace(/\[\[?\.{0,3}[^\]]*\]?\]/g, (match) => {
33
33
  brackets.push(match);
@@ -48,7 +48,7 @@ function filenameToRoutePath(filename) {
48
48
  * changes to the regex must be kept in sync between both functions.
49
49
  */
50
50
  function filenameToRouteId(filename) {
51
- let path = filename.replace(/^(?:[a-zA-Z]:[\\/])?(.*?)[\\/](?:routes|pages|content)[\\/]|(?:[\\/](?:app[\\/]pages|src[\\/]content)[\\/])|(\.page\.(js|ts)$)|(\.(ts|md)$)/g, "");
51
+ let path = filename.replace(/^(?:[a-zA-Z]:[\\/])?(.*?)[\\/](?:routes|pages|content)[\\/]|(?:[\\/](?:app[\\/]pages|src[\\/]content)[\\/])|(\.page\.(js|ts|tsrx)$)|(\.(ts|md)$)/g, "");
52
52
  const brackets = [];
53
53
  path = path.replace(/\(.*?\)|\[\[?\.{0,3}[^\]]*\]?\]/g, (match) => {
54
54
  brackets.push(match);
@@ -114,8 +114,8 @@ function generateRouteManifest(filenames, collisionPriority) {
114
114
  const winner = seenByFullPath.get(collisionKey);
115
115
  if (winner.filename === filename) continue;
116
116
  const isLayoutIndexPair = (a, b) => {
117
- const indexRe = /\/index\.(page\.)?(ts|js|md)$/;
118
- const layoutRe = /\.(page\.)?(ts|js)$/;
117
+ const indexRe = /\/index\.(page\.)?(ts|tsrx|js|md)$/;
118
+ const layoutRe = /\.(page\.)?(ts|tsrx|js)$/;
119
119
  if (indexRe.test(a) && layoutRe.test(b)) return a.replace(indexRe, "") === b.replace(layoutRe, "");
120
120
  return false;
121
121
  };
@@ -199,7 +199,7 @@ function canonicalRoutesByFullPath(routes) {
199
199
  }
200
200
  /** A route file's path within its pages directory, e.g. `users/[id]`. */
201
201
  function toRouteFileKey(filename) {
202
- return filename.replace(/^.*?[\\/](?:routes|pages|content)[\\/]|\.page\.(?:js|ts)$|\.(?:ts|md)$/g, "");
202
+ return filename.replace(/^.*?[\\/](?:routes|pages|content)[\\/]|\.page\.(?:js|ts|tsrx)$|\.(?:ts|md)$/g, "");
203
203
  }
204
204
  function isPathlessLayoutId(id) {
205
205
  const segments = id.split("/").filter(Boolean);
@@ -1 +1 @@
1
- {"version":3,"file":"route-manifest.js","names":[],"sources":["../../../src/lib/route-manifest.ts"],"sourcesContent":["/**\n * Route-manifest engine for typed file routes.\n *\n * Pure functions (no Angular dependencies) for converting discovered\n * filenames into typed route manifests and generated declarations.\n */\n\nexport interface RouteParamInfo {\n name: string;\n type: 'dynamic' | 'catchAll' | 'optionalCatchAll';\n}\n\nexport interface RouteEntry {\n /** Stable structural route id derived from the source filename */\n id: string;\n /** The route path segment relative to the nearest existing parent route */\n path: string;\n /** The fully resolved navigation path pattern (e.g., '/users/[id]') */\n fullPath: string;\n /** Extracted parameter information */\n params: RouteParamInfo[];\n /** Original filename that produced this route */\n filename: string;\n /** Type of source that produced this route */\n kind: 'page' | 'content';\n /** Parent route id, or null for top-level routes */\n parentId: string | null;\n /** Child route ids */\n children: string[];\n /** Whether the source filename represents an index route */\n isIndex: boolean;\n /** Whether the source filename includes route-group/pathless segments */\n isGroup: boolean;\n /** Whether the route contains a required catch-all parameter */\n isCatchAll: boolean;\n /** Whether the route contains an optional catch-all parameter */\n isOptionalCatchAll: boolean;\n /** Layout files that wrap this route, outermost first */\n layouts: string[];\n}\n\nexport interface RouteCollision {\n fullPath: string;\n keptFile: string;\n droppedFile: string;\n /** True when both files have the same collision priority (hard error). */\n samePriority: boolean;\n}\n\nexport interface RouteManifest {\n routes: RouteEntry[];\n collisions: RouteCollision[];\n /** Canonical route per fullPath — precomputed once to avoid redundant work. */\n canonicalByFullPath: Map<string, RouteEntry>;\n /** Full paths defined by more than one file, such as a layout and its index page. */\n sharedFullPaths: Set<string>;\n}\n\n/**\n * Converts a discovered filename to a route path pattern.\n *\n * Uses the same stripping rules as the existing route system\n * but preserves bracket param syntax instead of converting to\n * Angular's `:param` syntax.\n *\n * The regex applies four alternations (left to right, all replaced with ''):\n * 1. `^(.*?)[\\\\/](?:routes|pages|content)[\\\\/]` — anchored, strips everything\n * up to and including the first /routes/, /pages/, or /content/ segment.\n * Handles app-local paths (`/src/app/pages/`) AND additional dirs\n * (`/libs/shared/feature/src/content/`) uniformly.\n * 2. `[\\\\/](?:app[\\\\/]pages|src[\\\\/]content)[\\\\/]` — non-anchored\n * fallback for paths where the directory marker appears mid-string.\n * 3. `\\.page\\.(js|ts)$` — strips page file extensions.\n * 4. `\\.(ts|md)$` — strips remaining file extensions.\n *\n * Examples:\n * - '/src/app/pages/index.page.ts' -> '/'\n * - '/src/app/pages/about.page.ts' -> '/about'\n * - '/src/app/pages/users/[id].page.ts' -> '/users/[id]'\n * - '/src/app/pages/blog.[slug].page.ts' -> '/blog/[slug]'\n * - '/src/app/pages/(auth)/login.page.ts' -> '/login'\n * - '/src/app/pages/docs/[...slug].page.ts' -> '/docs/[...slug]'\n * - '/src/app/pages/shop/[[...category]].page.ts' -> '/shop/[[...category]]'\n * - '/libs/shared/feature/src/content/test.md' -> '/test'\n */\nexport function filenameToRoutePath(filename: string): string {\n let path = filename.replace(\n /^(?:[a-zA-Z]:[\\\\/])?(.*?)[\\\\/](?:routes|pages|content)[\\\\/]|(?:[\\\\/](?:app[\\\\/]pages|src[\\\\/]content)[\\\\/])|(\\.page\\.(js|ts)$)|(\\.(ts|md)$)/g,\n '',\n );\n\n const brackets: string[] = [];\n path = path.replace(/\\[\\[?\\.{0,3}[^\\]]*\\]?\\]/g, (match) => {\n brackets.push(match);\n // eslint-disable-next-line no-control-regex\n return `\\0B${brackets.length - 1}\\0`;\n });\n // Match the runtime router: strip index segments and groups before dots.\n path = path\n .replace(/\\(.*?\\)/g, '')\n .replace(/(^|[./])index(?=[./]|$)/g, '$1')\n .replace(/\\./g, '/');\n // eslint-disable-next-line no-control-regex\n path = path.replace(/\\0B(\\d+)\\0/g, (_, idx) => brackets[Number(idx)]);\n return '/' + path.split('/').filter(Boolean).join('/');\n}\n\n/**\n * Converts a discovered filename to a stable structural route id.\n *\n * Unlike `filenameToRoutePath`, this preserves route groups and `index`\n * segments so that multiple files resolving to the same URL shape can still\n * have distinct structural identities in the generated route tree metadata.\n *\n * Uses the same directory-stripping regex as `filenameToRoutePath` —\n * changes to the regex must be kept in sync between both functions.\n */\nexport function filenameToRouteId(filename: string): string {\n let path = filename.replace(\n /^(?:[a-zA-Z]:[\\\\/])?(.*?)[\\\\/](?:routes|pages|content)[\\\\/]|(?:[\\\\/](?:app[\\\\/]pages|src[\\\\/]content)[\\\\/])|(\\.page\\.(js|ts)$)|(\\.(ts|md)$)/g,\n '',\n );\n\n const brackets: string[] = [];\n path = path.replace(/\\(.*?\\)|\\[\\[?\\.{0,3}[^\\]]*\\]?\\]/g, (match) => {\n brackets.push(match);\n // eslint-disable-next-line no-control-regex\n return `\\0B${brackets.length - 1}\\0`;\n });\n path = path.replace(/\\./g, '/');\n // eslint-disable-next-line no-control-regex\n path = path.replace(/\\0B(\\d+)\\0/g, (_, idx) => brackets[Number(idx)]);\n\n const segments = path.split('/').filter(Boolean);\n\n return '/' + segments.join('/');\n}\n\n/**\n * Extracts parameter information from a route path pattern.\n */\nexport function extractRouteParams(routePath: string): RouteParamInfo[] {\n const params: RouteParamInfo[] = [];\n\n for (const match of routePath.matchAll(/\\[\\[\\.\\.\\.([^\\]]+)\\]\\]/g)) {\n params.push({ name: match[1], type: 'optionalCatchAll' });\n }\n for (const match of routePath.matchAll(/(?<!\\[)\\[\\.\\.\\.([^\\]]+)\\](?!\\])/g)) {\n params.push({ name: match[1], type: 'catchAll' });\n }\n for (const match of routePath.matchAll(/(?<!\\[)\\[(?!\\.)([^\\]]+)\\](?!\\])/g)) {\n params.push({ name: match[1], type: 'dynamic' });\n }\n\n return params;\n}\n\n/**\n * Generates a route manifest from a list of discovered filenames.\n *\n * @param collisionPriority - Optional callback that returns a numeric priority\n * for each filename (lower wins). When provided, this replaces the default\n * hard-coded path-substring heuristic with config-derived precedence.\n */\nexport function generateRouteManifest(\n filenames: string[],\n collisionPriority?: (filename: string) => number,\n): RouteManifest {\n const routes: RouteEntry[] = [];\n const collisions: RouteCollision[] = [];\n const sharedFullPaths = new Set<string>();\n const seenByFullPath = new Map<\n string,\n { filename: string; priority: number }\n >();\n const getPriority = collisionPriority ?? getCollisionPriority;\n\n // Prefer app-local route files over shared/external sources when two files\n // resolve to the same URL. This keeps `additionalPagesDirs` additive instead\n // of unexpectedly overriding the route that lives inside the app itself.\n const prioritizedFilenames = [...filenames].sort((a, b) => {\n const aPriority = getPriority(a);\n const bPriority = getPriority(b);\n if (aPriority !== bPriority) {\n return aPriority - bPriority;\n }\n return a.localeCompare(b);\n });\n\n // Layout routes are a file and a folder with the same name, so users.page.ts\n // wraps users/[id].page.ts but not users.[id].page.ts. Folders from all\n // pages dirs share one tree.\n const layoutByKey = new Map<string, string>();\n for (const filename of prioritizedFilenames) {\n const key = toRouteFileKey(filename);\n if (!filename.endsWith('.md') && !layoutByKey.has(key)) {\n layoutByKey.set(key, filename);\n }\n }\n\n for (const filename of prioritizedFilenames) {\n const fullPath = filenameToRoutePath(filename);\n const params = extractRouteParams(fullPath);\n const id = filenameToRouteId(filename);\n const isPathlessLayout = isPathlessLayoutId(id);\n // Different pathless branches can select the same URL with canMatch guards.\n const groupScope = id.slice(0, id.lastIndexOf(')') + 1);\n const collisionKey = JSON.stringify([fullPath, groupScope]);\n\n const currentPriority = getPriority(filename);\n\n // Pathless layouts (e.g. (auth).page.ts) are structural wrappers that\n // render a <router-outlet> — they coexist with index.page.ts at the same\n // fullPath without collision. The Angular router handles them as nested\n // layout routes, not competing page components.\n if (!isPathlessLayout) {\n if (seenByFullPath.has(collisionKey)) {\n const winner = seenByFullPath.get(collisionKey)!;\n if (winner.filename === filename) {\n continue;\n }\n // A layout file (e.g., docs.page.ts) and its index child\n // (e.g., docs/index.page.ts) intentionally share the same route\n // path — the layout wraps the index as a parent-child pair.\n const isLayoutIndexPair = (a: string, b: string) => {\n const indexRe = /\\/index\\.(page\\.)?(ts|js|md)$/;\n const layoutRe = /\\.(page\\.)?(ts|js)$/;\n if (indexRe.test(a) && layoutRe.test(b)) {\n const dir = a.replace(indexRe, '');\n const layout = b.replace(layoutRe, '');\n return dir === layout;\n }\n return false;\n };\n if (\n isLayoutIndexPair(winner.filename, filename) ||\n isLayoutIndexPair(filename, winner.filename)\n ) {\n sharedFullPaths.add(fullPath);\n continue;\n }\n collisions.push({\n fullPath,\n keptFile: winner.filename,\n droppedFile: filename,\n samePriority: winner.priority === currentPriority,\n });\n console.warn(\n `[Analog] Route collision: '${fullPath}' is defined by both ` +\n `'${winner.filename}' and '${filename}'. ` +\n `Keeping '${winner.filename}' based on route source precedence and skipping duplicate.`,\n );\n continue;\n }\n seenByFullPath.set(collisionKey, { filename, priority: currentPriority });\n }\n\n const segments = toRouteFileKey(filename).split('/');\n const layouts: string[] = [];\n for (let i = 1; i < segments.length; i++) {\n const layout = layoutByKey.get(segments.slice(0, i).join('/'));\n if (layout) layouts.push(layout);\n }\n\n routes.push({\n id,\n path: fullPath,\n fullPath,\n params,\n filename,\n kind: filename.endsWith('.md') ? 'content' : 'page',\n parentId: null,\n children: [],\n isIndex: id === '/index' || id.endsWith('/index'),\n isGroup: isPathlessLayout,\n isCatchAll: params.some((param) => param.type === 'catchAll'),\n isOptionalCatchAll: params.some(\n (param) => param.type === 'optionalCatchAll',\n ),\n layouts,\n });\n }\n\n routes.sort((a, b) => {\n const aW = getRouteWeight(a.fullPath);\n const bW = getRouteWeight(b.fullPath);\n if (aW !== bW) return aW - bW;\n return a.fullPath.localeCompare(b.fullPath);\n });\n\n const routeByFullPath = canonicalRoutesByFullPath(routes);\n\n const routeById = new Map(routes.map((route) => [route.id, route]));\n\n for (const route of routes) {\n // Use structural id-based parent lookup for any route whose id\n // contains a group segment — this wires group children (e.g.\n // /(auth)/sign-up) to their pathless layout parent (/(auth)).\n // This also correctly handles nested groups like\n // /dashboard/(settings)/profile: findNearestParentById walks up\n // id segments and finds /(settings) if it exists, otherwise falls\n // through to fullPathParent which resolves to /dashboard.\n // Non-group routes always use the canonical fullPath-based lookup.\n const hasGroupSegment = route.id.includes('/(');\n const structuralParent = hasGroupSegment\n ? findNearestParentById(route.id, routeById)\n : undefined;\n const fullPathParent = findNearestParentRoute(\n route.fullPath,\n routeByFullPath,\n );\n const parent = structuralParent ?? fullPathParent;\n route.parentId = parent?.id ?? null;\n route.path = computeLocalPath(route.fullPath, parent?.fullPath ?? null);\n }\n\n for (const route of routes) {\n if (route.parentId) {\n routeById.get(route.parentId)?.children.push(route.id);\n }\n if (routeByFullPath.get(route.fullPath) !== route) {\n sharedFullPaths.add(route.fullPath);\n }\n }\n\n return {\n routes,\n collisions,\n canonicalByFullPath: routeByFullPath,\n sharedFullPaths,\n };\n}\n\nfunction canonicalRoutesByFullPath(\n routes: RouteEntry[],\n): Map<string, RouteEntry> {\n const map = new Map<string, RouteEntry>();\n for (const route of routes) {\n const existing = map.get(route.fullPath);\n if (!existing) {\n map.set(route.fullPath, route);\n } else if (existing.isGroup && !route.isGroup) {\n // Non-group routes always take precedence over group layouts.\n map.set(route.fullPath, route);\n } else if (existing.isGroup && route.isGroup) {\n // Both are group layouts — tiebreak by id to ensure stable selection\n // regardless of filesystem or glob ordering across platforms.\n if (route.id.localeCompare(existing.id) < 0) {\n map.set(route.fullPath, route);\n }\n }\n }\n return map;\n}\n\n/** A route file's path within its pages directory, e.g. `users/[id]`. */\nfunction toRouteFileKey(filename: string): string {\n return filename.replace(\n /^.*?[\\\\/](?:routes|pages|content)[\\\\/]|\\.page\\.(?:js|ts)$|\\.(?:ts|md)$/g,\n '',\n );\n}\n\nfunction isPathlessLayoutId(id: string): boolean {\n const segments = id.split('/').filter(Boolean);\n if (segments.length === 0) return false;\n return /^\\([^)]*\\)$/.test(segments[segments.length - 1]);\n}\n\nfunction getRouteWeight(path: string): number {\n if (path.includes('[[...')) return 3;\n if (path.includes('[...')) return 2;\n if (path.includes('[')) return 1;\n return 0;\n}\n\nfunction getCollisionPriority(filename: string): number {\n if (\n filename.includes('/src/app/pages/') ||\n filename.includes('/app/pages/') ||\n filename.includes('/src/content/')\n ) {\n return 0;\n }\n\n return 1;\n}\n\n/** Import specifiers for a page module's typed exports. */\nexport interface RouteModuleImports {\n routeMeta?: string;\n load?: string;\n}\n\n/**\n * Generates the route-table section for the combined generated route module.\n *\n * `resolveModuleImports` adds `routeMeta` and `load` types for pages whose\n * URL is defined by a single file, along with the `routeMeta` of the layouts\n * that wrap them. URLs shared by several files, such as a layout and its\n * index page, are ambiguous and only get params and query types.\n */\nexport function generateRouteTableDeclaration(\n manifest: RouteManifest,\n resolveModuleImports?: (filename: string) => RouteModuleImports | undefined,\n): string {\n const lines: string[] = [];\n lines.push('/** @noprettier */');\n lines.push('// This file is auto-generated by @analogjs/platform');\n lines.push(\"import type {} from '@analogjs/router';\");\n lines.push(\"declare module '@analogjs/router' {\");\n lines.push(' interface AnalogRouteTable {');\n\n const importType = (specifier: string, name: string) =>\n `typeof import(${JSON.stringify(specifier)}).${name}`;\n\n for (const route of manifest.canonicalByFullPath.values()) {\n const paramsType = generateParamsType(route.params);\n const queryType = 'Record<string, string | string[] | undefined>';\n\n lines.push(` ${JSON.stringify(route.fullPath)}: {`);\n lines.push(` params: ${paramsType};`);\n lines.push(` query: ${queryType};`);\n if (\n resolveModuleImports &&\n route.kind === 'page' &&\n !manifest.sharedFullPaths.has(route.fullPath)\n ) {\n const layoutRouteMeta = route.layouts.flatMap((layout) => {\n const specifier = resolveModuleImports(layout)?.routeMeta;\n return specifier ? [importType(specifier, 'routeMeta')] : [];\n });\n const imports = resolveModuleImports(route.filename);\n if (layoutRouteMeta.length) {\n lines.push(` layoutRouteMeta: [${layoutRouteMeta.join(', ')}];`);\n }\n if (imports?.routeMeta) {\n lines.push(\n ` routeMeta: ${importType(imports.routeMeta, 'routeMeta')};`,\n );\n }\n if (imports?.load) {\n lines.push(` load: ${importType(imports.load, 'load')};`);\n }\n }\n lines.push(` };`);\n }\n\n lines.push(' }');\n lines.push('}');\n lines.push('');\n lines.push('export {};');\n lines.push('');\n\n return lines.join('\\n');\n}\n\nfunction generateParamsType(params: RouteParamInfo[]): string {\n if (params.length === 0) return 'Record<string, never>';\n\n const entries = params.map((p) => {\n const key = isValidIdentifier(p.name) ? p.name : JSON.stringify(p.name);\n switch (p.type) {\n case 'dynamic':\n return `${key}: string`;\n case 'catchAll':\n return `${key}: string[]`;\n case 'optionalCatchAll':\n return `${key}?: string[]`;\n }\n });\n\n return `{ ${entries.join('; ')} }`;\n}\n\nfunction isValidIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\nfunction findNearestParentById(\n id: string,\n routesById: Map<string, RouteEntry>,\n): RouteEntry | undefined {\n if (id === '/') {\n return undefined;\n }\n\n const segments = id.split('/').filter(Boolean);\n for (let index = segments.length - 1; index > 0; index--) {\n const candidate = '/' + segments.slice(0, index).join('/');\n const route = routesById.get(candidate);\n if (route) {\n return route;\n }\n }\n\n return undefined;\n}\n\nfunction findNearestParentRoute(\n fullPath: string,\n routesByFullPath: Map<string, RouteEntry>,\n): RouteEntry | undefined {\n if (fullPath === '/') {\n return undefined;\n }\n\n const segments = fullPath.slice(1).split('/');\n for (let index = segments.length - 1; index > 0; index--) {\n const candidate = '/' + segments.slice(0, index).join('/');\n const route = routesByFullPath.get(candidate);\n if (route) {\n return route;\n }\n }\n\n return undefined;\n}\n\nfunction computeLocalPath(\n fullPath: string,\n parentFullPath: string | null,\n): string {\n if (fullPath === '/') {\n return '/';\n }\n\n if (!parentFullPath) {\n return fullPath.slice(1);\n }\n\n const suffix = fullPath.slice(parentFullPath.length).replace(/^\\/+/, '');\n return suffix || '/';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAgB,oBAAoB,UAA0B;CAC5D,IAAI,OAAO,SAAS,QAClB,gJACA,EACF;CAEA,MAAM,WAAqB,CAAC;CAC5B,OAAO,KAAK,QAAQ,6BAA6B,UAAU;EACzD,SAAS,KAAK,KAAK;EAEnB,OAAO,MAAM,SAAS,SAAS,EAAE;CACnC,CAAC;CAED,OAAO,KACJ,QAAQ,YAAY,EAAE,CAAC,CACvB,QAAQ,4BAA4B,IAAI,CAAC,CACzC,QAAQ,OAAO,GAAG;CAErB,OAAO,KAAK,QAAQ,gBAAgB,GAAG,QAAQ,SAAS,OAAO,GAAG,EAAE;CACpE,OAAO,MAAM,KAAK,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;AACvD;;;;;;;;;;;AAYA,SAAgB,kBAAkB,UAA0B;CAC1D,IAAI,OAAO,SAAS,QAClB,gJACA,EACF;CAEA,MAAM,WAAqB,CAAC;CAC5B,OAAO,KAAK,QAAQ,qCAAqC,UAAU;EACjE,SAAS,KAAK,KAAK;EAEnB,OAAO,MAAM,SAAS,SAAS,EAAE;CACnC,CAAC;CACD,OAAO,KAAK,QAAQ,OAAO,GAAG;CAE9B,OAAO,KAAK,QA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AAuB;CAChD,OAAO,6BAA6B,KAAK,IAAI;AAC/C;AAEA,SAAS,sBACP,IACA,YACwB;CACxB,IAAI,OAAO,KACT;CAGF,MAAM,WAAW,GAAG,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;CAC7C,KAAK,IAAI,QAAQ,SAAS,SAAS,GAAG,QAAQ,GAAG,SAAS;EACxD,MAAM,YAAY,MAAM,SAAS,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,GAAG;EACzD,MAAM,QAAQ,WAAW,IAAI,SAAS;EACtC,IAAI,OACF,OAAO;CAEX;AAGF;AAEA,SAAS,uBACP,UACA,kBACwB;CACxB,IAAI,aAAa,KACf;CAGF,MAAM,WAAW,SAAS,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG;CAC5C,KAAK,IAAI,QAAQ,SAAS,SAAS,GAAG,QAAQ,GAAG,SAAS;EACxD,MAAM,YAAY,MAAM,SAAS,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,GAAG;EACzD,MAAM,QAAQ,iBAAiB,IAAI,SAAS;EAC5C,IAAI,OACF,OAAO;CAEX;AAGF;AAEA,SAAS,iBACP,UACA,gBACQ;CACR,IAAI,aAAa,KACf,OAAO;CAGT,IAAI,CAAC,gBACH,OAAO,SAAS,MAAM,CAAC;CAIzB,OADe,SAAS,MAAM,eAAe,MAAM,CAAC,CAAC,QAAQ,QAAQ,EAC9D,KAAU;AACnB"}
1
+ {"version":3,"file":"route-manifest.js","names":[],"sources":["../../../src/lib/route-manifest.ts"],"sourcesContent":["/**\n * Route-manifest engine for typed file routes.\n *\n * Pure functions (no Angular dependencies) for converting discovered\n * filenames into typed route manifests and generated declarations.\n */\n\nexport interface RouteParamInfo {\n name: string;\n type: 'dynamic' | 'catchAll' | 'optionalCatchAll';\n}\n\nexport interface RouteEntry {\n /** Stable structural route id derived from the source filename */\n id: string;\n /** The route path segment relative to the nearest existing parent route */\n path: string;\n /** The fully resolved navigation path pattern (e.g., '/users/[id]') */\n fullPath: string;\n /** Extracted parameter information */\n params: RouteParamInfo[];\n /** Original filename that produced this route */\n filename: string;\n /** Type of source that produced this route */\n kind: 'page' | 'content';\n /** Parent route id, or null for top-level routes */\n parentId: string | null;\n /** Child route ids */\n children: string[];\n /** Whether the source filename represents an index route */\n isIndex: boolean;\n /** Whether the source filename includes route-group/pathless segments */\n isGroup: boolean;\n /** Whether the route contains a required catch-all parameter */\n isCatchAll: boolean;\n /** Whether the route contains an optional catch-all parameter */\n isOptionalCatchAll: boolean;\n /** Layout files that wrap this route, outermost first */\n layouts: string[];\n}\n\nexport interface RouteCollision {\n fullPath: string;\n keptFile: string;\n droppedFile: string;\n /** True when both files have the same collision priority (hard error). */\n samePriority: boolean;\n}\n\nexport interface RouteManifest {\n routes: RouteEntry[];\n collisions: RouteCollision[];\n /** Canonical route per fullPath — precomputed once to avoid redundant work. */\n canonicalByFullPath: Map<string, RouteEntry>;\n /** Full paths defined by more than one file, such as a layout and its index page. */\n sharedFullPaths: Set<string>;\n}\n\n/**\n * Converts a discovered filename to a route path pattern.\n *\n * Uses the same stripping rules as the existing route system\n * but preserves bracket param syntax instead of converting to\n * Angular's `:param` syntax.\n *\n * The regex applies four alternations (left to right, all replaced with ''):\n * 1. `^(.*?)[\\\\/](?:routes|pages|content)[\\\\/]` — anchored, strips everything\n * up to and including the first /routes/, /pages/, or /content/ segment.\n * Handles app-local paths (`/src/app/pages/`) AND additional dirs\n * (`/libs/shared/feature/src/content/`) uniformly.\n * 2. `[\\\\/](?:app[\\\\/]pages|src[\\\\/]content)[\\\\/]` — non-anchored\n * fallback for paths where the directory marker appears mid-string.\n * 3. `\\.page\\.(js|ts|tsrx)$` — strips page file extensions.\n * 4. `\\.(ts|md)$` — strips remaining file extensions.\n *\n * Examples:\n * - '/src/app/pages/index.page.ts' -> '/'\n * - '/src/app/pages/about.page.ts' -> '/about'\n * - '/src/app/pages/users/[id].page.ts' -> '/users/[id]'\n * - '/src/app/pages/blog.[slug].page.ts' -> '/blog/[slug]'\n * - '/src/app/pages/(auth)/login.page.ts' -> '/login'\n * - '/src/app/pages/docs/[...slug].page.ts' -> '/docs/[...slug]'\n * - '/src/app/pages/shop/[[...category]].page.ts' -> '/shop/[[...category]]'\n * - '/libs/shared/feature/src/content/test.md' -> '/test'\n */\nexport function filenameToRoutePath(filename: string): string {\n let path = filename.replace(\n /^(?:[a-zA-Z]:[\\\\/])?(.*?)[\\\\/](?:routes|pages|content)[\\\\/]|(?:[\\\\/](?:app[\\\\/]pages|src[\\\\/]content)[\\\\/])|(\\.page\\.(js|ts|tsrx)$)|(\\.(ts|md)$)/g,\n '',\n );\n\n const brackets: string[] = [];\n path = path.replace(/\\[\\[?\\.{0,3}[^\\]]*\\]?\\]/g, (match) => {\n brackets.push(match);\n // eslint-disable-next-line no-control-regex\n return `\\0B${brackets.length - 1}\\0`;\n });\n // Match the runtime router: strip index segments and groups before dots.\n path = path\n .replace(/\\(.*?\\)/g, '')\n .replace(/(^|[./])index(?=[./]|$)/g, '$1')\n .replace(/\\./g, '/');\n // eslint-disable-next-line no-control-regex\n path = path.replace(/\\0B(\\d+)\\0/g, (_, idx) => brackets[Number(idx)]);\n return '/' + path.split('/').filter(Boolean).join('/');\n}\n\n/**\n * Converts a discovered filename to a stable structural route id.\n *\n * Unlike `filenameToRoutePath`, this preserves route groups and `index`\n * segments so that multiple files resolving to the same URL shape can still\n * have distinct structural identities in the generated route tree metadata.\n *\n * Uses the same directory-stripping regex as `filenameToRoutePath` —\n * changes to the regex must be kept in sync between both functions.\n */\nexport function filenameToRouteId(filename: string): string {\n let path = filename.replace(\n /^(?:[a-zA-Z]:[\\\\/])?(.*?)[\\\\/](?:routes|pages|content)[\\\\/]|(?:[\\\\/](?:app[\\\\/]pages|src[\\\\/]content)[\\\\/])|(\\.page\\.(js|ts|tsrx)$)|(\\.(ts|md)$)/g,\n '',\n );\n\n const brackets: string[] = [];\n path = path.replace(/\\(.*?\\)|\\[\\[?\\.{0,3}[^\\]]*\\]?\\]/g, (match) => {\n brackets.push(match);\n // eslint-disable-next-line no-control-regex\n return `\\0B${brackets.length - 1}\\0`;\n });\n path = path.replace(/\\./g, '/');\n // eslint-disable-next-line no-control-regex\n path = path.replace(/\\0B(\\d+)\\0/g, (_, idx) => brackets[Number(idx)]);\n\n const segments = path.split('/').filter(Boolean);\n\n return '/' + segments.join('/');\n}\n\n/**\n * Extracts parameter information from a route path pattern.\n */\nexport function extractRouteParams(routePath: string): RouteParamInfo[] {\n const params: RouteParamInfo[] = [];\n\n for (const match of routePath.matchAll(/\\[\\[\\.\\.\\.([^\\]]+)\\]\\]/g)) {\n params.push({ name: match[1], type: 'optionalCatchAll' });\n }\n for (const match of routePath.matchAll(/(?<!\\[)\\[\\.\\.\\.([^\\]]+)\\](?!\\])/g)) {\n params.push({ name: match[1], type: 'catchAll' });\n }\n for (const match of routePath.matchAll(/(?<!\\[)\\[(?!\\.)([^\\]]+)\\](?!\\])/g)) {\n params.push({ name: match[1], type: 'dynamic' });\n }\n\n return params;\n}\n\n/**\n * Generates a route manifest from a list of discovered filenames.\n *\n * @param collisionPriority - Optional callback that returns a numeric priority\n * for each filename (lower wins). When provided, this replaces the default\n * hard-coded path-substring heuristic with config-derived precedence.\n */\nexport function generateRouteManifest(\n filenames: string[],\n collisionPriority?: (filename: string) => number,\n): RouteManifest {\n const routes: RouteEntry[] = [];\n const collisions: RouteCollision[] = [];\n const sharedFullPaths = new Set<string>();\n const seenByFullPath = new Map<\n string,\n { filename: string; priority: number }\n >();\n const getPriority = collisionPriority ?? getCollisionPriority;\n\n // Prefer app-local route files over shared/external sources when two files\n // resolve to the same URL. This keeps `additionalPagesDirs` additive instead\n // of unexpectedly overriding the route that lives inside the app itself.\n const prioritizedFilenames = [...filenames].sort((a, b) => {\n const aPriority = getPriority(a);\n const bPriority = getPriority(b);\n if (aPriority !== bPriority) {\n return aPriority - bPriority;\n }\n return a.localeCompare(b);\n });\n\n // Layout routes are a file and a folder with the same name, so users.page.ts\n // wraps users/[id].page.ts but not users.[id].page.ts. Folders from all\n // pages dirs share one tree.\n const layoutByKey = new Map<string, string>();\n for (const filename of prioritizedFilenames) {\n const key = toRouteFileKey(filename);\n if (!filename.endsWith('.md') && !layoutByKey.has(key)) {\n layoutByKey.set(key, filename);\n }\n }\n\n for (const filename of prioritizedFilenames) {\n const fullPath = filenameToRoutePath(filename);\n const params = extractRouteParams(fullPath);\n const id = filenameToRouteId(filename);\n const isPathlessLayout = isPathlessLayoutId(id);\n // Different pathless branches can select the same URL with canMatch guards.\n const groupScope = id.slice(0, id.lastIndexOf(')') + 1);\n const collisionKey = JSON.stringify([fullPath, groupScope]);\n\n const currentPriority = getPriority(filename);\n\n // Pathless layouts (e.g. (auth).page.ts) are structural wrappers that\n // render a <router-outlet> — they coexist with index.page.ts at the same\n // fullPath without collision. The Angular router handles them as nested\n // layout routes, not competing page components.\n if (!isPathlessLayout) {\n if (seenByFullPath.has(collisionKey)) {\n const winner = seenByFullPath.get(collisionKey)!;\n if (winner.filename === filename) {\n continue;\n }\n // A layout file (e.g., docs.page.ts) and its index child\n // (e.g., docs/index.page.ts) intentionally share the same route\n // path — the layout wraps the index as a parent-child pair.\n const isLayoutIndexPair = (a: string, b: string) => {\n const indexRe = /\\/index\\.(page\\.)?(ts|tsrx|js|md)$/;\n const layoutRe = /\\.(page\\.)?(ts|tsrx|js)$/;\n if (indexRe.test(a) && layoutRe.test(b)) {\n const dir = a.replace(indexRe, '');\n const layout = b.replace(layoutRe, '');\n return dir === layout;\n }\n return false;\n };\n if (\n isLayoutIndexPair(winner.filename, filename) ||\n isLayoutIndexPair(filename, winner.filename)\n ) {\n sharedFullPaths.add(fullPath);\n continue;\n }\n collisions.push({\n fullPath,\n keptFile: winner.filename,\n droppedFile: filename,\n samePriority: winner.priority === currentPriority,\n });\n console.warn(\n `[Analog] Route collision: '${fullPath}' is defined by both ` +\n `'${winner.filename}' and '${filename}'. ` +\n `Keeping '${winner.filename}' based on route source precedence and skipping duplicate.`,\n );\n continue;\n }\n seenByFullPath.set(collisionKey, { filename, priority: currentPriority });\n }\n\n const segments = toRouteFileKey(filename).split('/');\n const layouts: string[] = [];\n for (let i = 1; i < segments.length; i++) {\n const layout = layoutByKey.get(segments.slice(0, i).join('/'));\n if (layout) layouts.push(layout);\n }\n\n routes.push({\n id,\n path: fullPath,\n fullPath,\n params,\n filename,\n kind: filename.endsWith('.md') ? 'content' : 'page',\n parentId: null,\n children: [],\n isIndex: id === '/index' || id.endsWith('/index'),\n isGroup: isPathlessLayout,\n isCatchAll: params.some((param) => param.type === 'catchAll'),\n isOptionalCatchAll: params.some(\n (param) => param.type === 'optionalCatchAll',\n ),\n layouts,\n });\n }\n\n routes.sort((a, b) => {\n const aW = getRouteWeight(a.fullPath);\n const bW = getRouteWeight(b.fullPath);\n if (aW !== bW) return aW - bW;\n return a.fullPath.localeCompare(b.fullPath);\n });\n\n const routeByFullPath = canonicalRoutesByFullPath(routes);\n\n const routeById = new Map(routes.map((route) => [route.id, route]));\n\n for (const route of routes) {\n // Use structural id-based parent lookup for any route whose id\n // contains a group segment — this wires group children (e.g.\n // /(auth)/sign-up) to their pathless layout parent (/(auth)).\n // This also correctly handles nested groups like\n // /dashboard/(settings)/profile: findNearestParentById walks up\n // id segments and finds /(settings) if it exists, otherwise falls\n // through to fullPathParent which resolves to /dashboard.\n // Non-group routes always use the canonical fullPath-based lookup.\n const hasGroupSegment = route.id.includes('/(');\n const structuralParent = hasGroupSegment\n ? findNearestParentById(route.id, routeById)\n : undefined;\n const fullPathParent = findNearestParentRoute(\n route.fullPath,\n routeByFullPath,\n );\n const parent = structuralParent ?? fullPathParent;\n route.parentId = parent?.id ?? null;\n route.path = computeLocalPath(route.fullPath, parent?.fullPath ?? null);\n }\n\n for (const route of routes) {\n if (route.parentId) {\n routeById.get(route.parentId)?.children.push(route.id);\n }\n if (routeByFullPath.get(route.fullPath) !== route) {\n sharedFullPaths.add(route.fullPath);\n }\n }\n\n return {\n routes,\n collisions,\n canonicalByFullPath: routeByFullPath,\n sharedFullPaths,\n };\n}\n\nfunction canonicalRoutesByFullPath(\n routes: RouteEntry[],\n): Map<string, RouteEntry> {\n const map = new Map<string, RouteEntry>();\n for (const route of routes) {\n const existing = map.get(route.fullPath);\n if (!existing) {\n map.set(route.fullPath, route);\n } else if (existing.isGroup && !route.isGroup) {\n // Non-group routes always take precedence over group layouts.\n map.set(route.fullPath, route);\n } else if (existing.isGroup && route.isGroup) {\n // Both are group layouts — tiebreak by id to ensure stable selection\n // regardless of filesystem or glob ordering across platforms.\n if (route.id.localeCompare(existing.id) < 0) {\n map.set(route.fullPath, route);\n }\n }\n }\n return map;\n}\n\n/** A route file's path within its pages directory, e.g. `users/[id]`. */\nfunction toRouteFileKey(filename: string): string {\n return filename.replace(\n /^.*?[\\\\/](?:routes|pages|content)[\\\\/]|\\.page\\.(?:js|ts|tsrx)$|\\.(?:ts|md)$/g,\n '',\n );\n}\n\nfunction isPathlessLayoutId(id: string): boolean {\n const segments = id.split('/').filter(Boolean);\n if (segments.length === 0) return false;\n return /^\\([^)]*\\)$/.test(segments[segments.length - 1]);\n}\n\nfunction getRouteWeight(path: string): number {\n if (path.includes('[[...')) return 3;\n if (path.includes('[...')) return 2;\n if (path.includes('[')) return 1;\n return 0;\n}\n\nfunction getCollisionPriority(filename: string): number {\n if (\n filename.includes('/src/app/pages/') ||\n filename.includes('/app/pages/') ||\n filename.includes('/src/content/')\n ) {\n return 0;\n }\n\n return 1;\n}\n\n/** Import specifiers for a page module's typed exports. */\nexport interface RouteModuleImports {\n routeMeta?: string;\n load?: string;\n}\n\n/**\n * Generates the route-table section for the combined generated route module.\n *\n * `resolveModuleImports` adds `routeMeta` and `load` types for pages whose\n * URL is defined by a single file, along with the `routeMeta` of the layouts\n * that wrap them. URLs shared by several files, such as a layout and its\n * index page, are ambiguous and only get params and query types.\n */\nexport function generateRouteTableDeclaration(\n manifest: RouteManifest,\n resolveModuleImports?: (filename: string) => RouteModuleImports | undefined,\n): string {\n const lines: string[] = [];\n lines.push('/** @noprettier */');\n lines.push('// This file is auto-generated by @analogjs/platform');\n lines.push(\"import type {} from '@analogjs/router';\");\n lines.push(\"declare module '@analogjs/router' {\");\n lines.push(' interface AnalogRouteTable {');\n\n const importType = (specifier: string, name: string) =>\n `typeof import(${JSON.stringify(specifier)}).${name}`;\n\n for (const route of manifest.canonicalByFullPath.values()) {\n const paramsType = generateParamsType(route.params);\n const queryType = 'Record<string, string | string[] | undefined>';\n\n lines.push(` ${JSON.stringify(route.fullPath)}: {`);\n lines.push(` params: ${paramsType};`);\n lines.push(` query: ${queryType};`);\n if (\n resolveModuleImports &&\n route.kind === 'page' &&\n !manifest.sharedFullPaths.has(route.fullPath)\n ) {\n const layoutRouteMeta = route.layouts.flatMap((layout) => {\n const specifier = resolveModuleImports(layout)?.routeMeta;\n return specifier ? [importType(specifier, 'routeMeta')] : [];\n });\n const imports = resolveModuleImports(route.filename);\n if (layoutRouteMeta.length) {\n lines.push(` layoutRouteMeta: [${layoutRouteMeta.join(', ')}];`);\n }\n if (imports?.routeMeta) {\n lines.push(\n ` routeMeta: ${importType(imports.routeMeta, 'routeMeta')};`,\n );\n }\n if (imports?.load) {\n lines.push(` load: ${importType(imports.load, 'load')};`);\n }\n }\n lines.push(` };`);\n }\n\n lines.push(' }');\n lines.push('}');\n lines.push('');\n lines.push('export {};');\n lines.push('');\n\n return lines.join('\\n');\n}\n\nfunction generateParamsType(params: RouteParamInfo[]): string {\n if (params.length === 0) return 'Record<string, never>';\n\n const entries = params.map((p) => {\n const key = isValidIdentifier(p.name) ? p.name : JSON.stringify(p.name);\n switch (p.type) {\n case 'dynamic':\n return `${key}: string`;\n case 'catchAll':\n return `${key}: string[]`;\n case 'optionalCatchAll':\n return `${key}?: string[]`;\n }\n });\n\n return `{ ${entries.join('; ')} }`;\n}\n\nfunction isValidIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\nfunction findNearestParentById(\n id: string,\n routesById: Map<string, RouteEntry>,\n): RouteEntry | undefined {\n if (id === '/') {\n return undefined;\n }\n\n const segments = id.split('/').filter(Boolean);\n for (let index = segments.length - 1; index > 0; index--) {\n const candidate = '/' + segments.slice(0, index).join('/');\n const route = routesById.get(candidate);\n if (route) {\n return route;\n }\n }\n\n return undefined;\n}\n\nfunction findNearestParentRoute(\n fullPath: string,\n routesByFullPath: Map<string, RouteEntry>,\n): RouteEntry | undefined {\n if (fullPath === '/') {\n return undefined;\n }\n\n const segments = fullPath.slice(1).split('/');\n for (let index = segments.length - 1; index > 0; index--) {\n const candidate = '/' + segments.slice(0, index).join('/');\n const route = routesByFullPath.get(candidate);\n if (route) {\n return route;\n }\n }\n\n return undefined;\n}\n\nfunction computeLocalPath(\n fullPath: string,\n parentFullPath: string | null,\n): string {\n if (fullPath === '/') {\n return '/';\n }\n\n if (!parentFullPath) {\n return fullPath.slice(1);\n }\n\n const suffix = fullPath.slice(parentFullPath.length).replace(/^\\/+/, '');\n return suffix || '/';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAgB,oBAAoB,UAA0B;CAC5D,IAAI,OAAO,SAAS,QAClB,qJACA,EACF;CAEA,MAAM,WAAqB,CAAC;CAC5B,OAAO,KAAK,QAAQ,6BAA6B,UAAU;EACzD,SAAS,KAAK,KAAK;EAEnB,OAAO,MAAM,SAAS,SAAS,EAAE;CACnC,CAAC;CAED,OAAO,KACJ,QAAQ,YAAY,EAAE,CAAC,CACvB,QAAQ,4BAA4B,IAAI,CAAC,CACzC,QAAQ,OAAO,GAAG;CAErB,OAAO,KAAK,QAAQ,gBAAgB,GAAG,QAAQ,SAAS,OAAO,GAAG,EAAE;CACpE,OAAO,MAAM,KAAK,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;AACvD;;;;;;;;;;;AAYA,SAAgB,kBAAkB,UAA0B;CAC1D,IAAI,OAAO,SAAS,QAClB,qJACA,EACF;CAEA,MAAM,WAAqB,CAAC;CAC5B,O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AAO,GAAG,IAAI;GAChB,KAAK,YACH,OAAO,GAAG,IAAI;GAChB,KAAK,oBACH,OAAO,GAAG,IAAI;EAClB;CACF,CAEY,CAAA,CAAQ,KAAK,IAAI,EAAE;AACjC;AAEA,SAAS,kBAAkB,MAAuB;CAChD,OAAO,6BAA6B,KAAK,IAAI;AAC/C;AAEA,SAAS,sBACP,IACA,YACwB;CACxB,IAAI,OAAO,KACT;CAGF,MAAM,WAAW,GAAG,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;CAC7C,KAAK,IAAI,QAAQ,SAAS,SAAS,GAAG,QAAQ,GAAG,SAAS;EACxD,MAAM,YAAY,MAAM,SAAS,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,GAAG;EACzD,MAAM,QAAQ,WAAW,IAAI,SAAS;EACtC,IAAI,OACF,OAAO;CAEX;AAGF;AAEA,SAAS,uBACP,UACA,kBACwB;CACxB,IAAI,aAAa,KACf;CAGF,MAAM,WAAW,SAAS,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG;CAC5C,KAAK,IAAI,QAAQ,SAAS,SAAS,GAAG,QAAQ,GAAG,SAAS;EACxD,MAAM,YAAY,MAAM,SAAS,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,GAAG;EACzD,MAAM,QAAQ,iBAAiB,IAAI,SAAS;EAC5C,IAAI,OACF,OAAO;CAEX;AAGF;AAEA,SAAS,iBACP,UACA,gBACQ;CACR,IAAI,aAAa,KACf,OAAO;CAGT,IAAI,CAAC,gBACH,OAAO,SAAS,MAAM,CAAC;CAIzB,OADe,SAAS,MAAM,eAAe,MAAM,CAAC,CAAC,QAAQ,QAAQ,EAC9D,KAAU;AACnB"}
@@ -49,7 +49,11 @@ function routerPlugin(options) {
49
49
  return getRouteLikeDirs().some((dir) => normalizedPath === dir || normalizedPath.startsWith(`${dir}/`));
50
50
  };
51
51
  const discoverRouteFiles = () => {
52
- routeFilesCache ??= globSync([`${root}/src/app/pages/**/*.page.ts`, ...additionalPagesDirs.map((dir) => `${dir}/**/*.page.ts`)], {
52
+ routeFilesCache ??= globSync([
53
+ `${root}/src/app/pages/**/*.page.ts`,
54
+ `${root}/src/app/pages/**/*.page.tsrx`,
55
+ ...additionalPagesDirs.flatMap((dir) => [`${dir}/**/*.page.ts`, `${dir}/**/*.page.tsrx`])
56
+ ], {
53
57
  dot: true,
54
58
  absolute: true
55
59
  });
@@ -74,7 +78,7 @@ function routerPlugin(options) {
74
78
  return endpointFilesCache;
75
79
  };
76
80
  const discoverPageRouteFiles = () => {
77
- pageRouteFilesCache ??= discoverRouteFiles().filter((file) => file.endsWith(".page.ts"));
81
+ pageRouteFilesCache ??= discoverRouteFiles().filter((file) => file.endsWith(".page.ts") || file.endsWith(".page.tsrx"));
78
82
  return pageRouteFilesCache;
79
83
  };
80
84
  const invalidateDiscoveryCaches = () => {
@@ -192,7 +196,7 @@ function routerPlugin(options) {
192
196
  `);
193
197
  result = result.replace("ANALOG_CONTENT_ROUTE_FILES = {};", `
194
198
  ANALOG_CONTENT_ROUTE_FILES = {${contentRouteFiles.map((module) => {
195
- return `"${getModuleKey(module)}": () => import('${module}?analog-content-file=true').then(m => m.default)`;
199
+ return `"${getModuleKey(module)}": () => import('${module}?analog-content-file=true')`;
196
200
  })}};
197
201
  `);
198
202
  result = result.replace("ANALOG_CONTENT_FILE_COUNT = 0", `ANALOG_CONTENT_FILE_COUNT = ${contentRouteFiles.length}`);
@@ -1 +1 @@
1
- {"version":3,"file":"router-plugin.js","names":[],"sources":["../../../src/lib/router-plugin.ts"],"sourcesContent":["import { normalizePath, Plugin, UserConfig, ViteDevServer } from 'vite';\nimport { globSync } from 'tinyglobby';\nimport { readFileSync } from 'node:fs';\nimport { isAbsolute, relative, resolve } from 'node:path';\n\nimport { Options } from './options.js';\nimport {\n analyzeAnalogRouteFile,\n formatAnalogRouteIdiomDiagnostic,\n} from './route-idiom-diagnostics.js';\n\n/**\n * Router plugin that handles route file discovery and hot module replacement.\n *\n * This plugin provides three main functionalities:\n * 1. Route invalidation when files are added/deleted (HMR workaround)\n * 2. Dynamic route file discovery and import generation\n * 3. Content route file discovery for markdown and Analog content\n *\n * @param options Configuration options for the router plugin\n * @returns Array of Vite plugins for route handling\n *\n * IMPORTANT: This plugin uses tinyglobby for file discovery.\n * Key behavior with { dot: true, absolute: true }:\n * - Returns absolute paths for ALL discovered files\n * - Path normalization is required to match expected output format\n * - Files within project root must use relative paths in object keys\n * - Files outside project root keep absolute paths in object keys\n */\nexport function routerPlugin(options?: Options): Plugin[] {\n const workspaceRoot = normalizePath(\n options?.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd(),\n );\n let config: UserConfig;\n let root: string;\n // Option dirs are workspace-relative, often written with a leading `/`.\n // Normalize them once into absolute workspace paths so watcher events,\n // glob patterns, and key generation all compare against the same shape.\n const normalizeWatchedDir = (dir: string) => {\n const normalizedDir = normalizePath(\n dir.startsWith(`${workspaceRoot}/`) || dir === workspaceRoot\n ? dir\n : dir.startsWith('/')\n ? `${workspaceRoot}${dir}`\n : resolve(workspaceRoot, dir),\n );\n return normalizedDir.endsWith('/')\n ? normalizedDir.slice(0, -1)\n : normalizedDir;\n };\n // Computed eagerly — these depend only on `options` and `workspaceRoot`,\n // both of which are fixed at construction time.\n const additionalPagesDirs = (options?.additionalPagesDirs || []).map((dir) =>\n normalizeWatchedDir(dir),\n );\n const additionalContentDirs = (options?.additionalContentDirs || []).map(\n (dir) => normalizeWatchedDir(dir),\n );\n // Returns every directory that can contain route-like files. The root-\n // relative entries are only available after the Vite `config` hook sets\n // `root`. The short-form fallbacks (`/src/app/pages`, etc.) let watcher\n // events match before `config` runs — they cover the common convention\n // where paths start with these prefixes.\n const getRouteLikeDirs = () => [\n ...(root\n ? [\n normalizeWatchedDir(`${root}/src/app/pages`),\n normalizeWatchedDir(`${root}/src/content`),\n ]\n : []),\n '/src/app/pages',\n '/src/content',\n ...additionalPagesDirs,\n ...additionalContentDirs,\n ];\n // These lists are used repeatedly by transform hooks during serve. Keeping\n // them warm avoids a full glob on every route/content invalidation.\n let routeFilesCache: string[] | undefined;\n let pageRouteFilesCache: string[] | undefined;\n let contentRouteFilesCache: string[] | undefined;\n let endpointFilesCache: string[] | undefined;\n const routeDiagnosticCache = new Map<string, string>();\n const isRouteLikeFile = (path: string) => {\n // Watcher paths from chokidar are already absolute — `normalizePath`\n // (forward-slash only) is sufficient; `resolve()` would be a no-op.\n const normalizedPath = normalizePath(path);\n\n return getRouteLikeDirs().some(\n (dir) => normalizedPath === dir || normalizedPath.startsWith(`${dir}/`),\n );\n };\n const discoverRouteFiles = () => {\n routeFilesCache ??= globSync(\n [\n `${root}/src/app/pages/**/*.page.ts`,\n ...additionalPagesDirs.map((dir) => `${dir}/**/*.page.ts`),\n ],\n { dot: true, absolute: true },\n );\n\n return routeFilesCache;\n };\n const discoverContentRouteFiles = () => {\n contentRouteFilesCache ??= globSync(\n [\n `${root}/src/app/pages/**/*.md`,\n `${root}/src/content/**/*.md`,\n ...additionalContentDirs.map((dir) => `${dir}/**/*.md`),\n ],\n { dot: true, absolute: true },\n );\n\n return contentRouteFilesCache;\n };\n const discoverEndpointFiles = () => {\n endpointFilesCache ??= globSync(\n [\n `${root}/src/app/pages/**/*.server.ts`,\n ...additionalPagesDirs.map((dir) => `${dir}/**/*.server.ts`),\n ],\n { dot: true, absolute: true },\n );\n\n return endpointFilesCache;\n };\n const discoverPageRouteFiles = () => {\n pageRouteFilesCache ??= discoverRouteFiles().filter((file) =>\n file.endsWith('.page.ts'),\n );\n\n return pageRouteFilesCache;\n };\n const invalidateDiscoveryCaches = () => {\n routeFilesCache = undefined;\n pageRouteFilesCache = undefined;\n contentRouteFilesCache = undefined;\n endpointFilesCache = undefined;\n };\n const reportRouteDiagnostics = (path: string) => {\n if (!path.endsWith('.page.ts')) {\n return;\n }\n\n try {\n const code = readFileSync(path, 'utf-8');\n const routeFiles = discoverPageRouteFiles();\n const diagnostics = analyzeAnalogRouteFile({\n filename: path,\n code,\n routeFiles,\n });\n\n const rendered = diagnostics.map((diagnostic) =>\n formatAnalogRouteIdiomDiagnostic(diagnostic, path, workspaceRoot),\n );\n const fingerprint = rendered.join('\\n\\n');\n\n if (!fingerprint) {\n routeDiagnosticCache.delete(path);\n return;\n }\n\n if (routeDiagnosticCache.get(path) === fingerprint) {\n return;\n }\n\n routeDiagnosticCache.set(path, fingerprint);\n rendered.forEach((message) => console.warn(message));\n } catch {\n routeDiagnosticCache.delete(path);\n }\n };\n const getModuleKey = (module: string) => {\n // Before config sets `root`, fall back to workspace-relative keys.\n if (!root) {\n return `/${normalizePath(relative(workspaceRoot, module))}`;\n }\n\n const relToRoot = normalizePath(relative(root, module));\n // Use true path containment instead of a raw prefix check so siblings like\n // `/apps/my-app-tools/...` are not mistaken for files inside `/apps/my-app`.\n const isInRoot = !relToRoot.startsWith('..') && !isAbsolute(relToRoot);\n\n if (isInRoot) {\n return `/${relToRoot}`;\n }\n\n return `/${normalizePath(relative(workspaceRoot, module))}`;\n };\n const invalidateFileModules = (server: ViteDevServer, path: string) => {\n const normalizedPath = normalizePath(path);\n // A newly added page can be discovered before its final contents settle.\n // Invalidate the page module itself so later edits don't keep serving the\n // first incomplete transform from Vite's module graph.\n const fileModules =\n server.moduleGraph.getModulesByFile?.(normalizedPath) ??\n server.moduleGraph.fileToModulesMap.get(normalizedPath);\n\n fileModules?.forEach((mod) => {\n server.moduleGraph.invalidateModule(mod);\n\n mod.importers.forEach((imp) => {\n server.moduleGraph.invalidateModule(imp);\n });\n });\n };\n\n return [\n {\n name: 'analogjs-router-invalidate-routes',\n configureServer(server) {\n /**\n * Invalidates route modules when files are added or deleted.\n * This is a workaround for Vite's HMR limitations with dynamic imports.\n *\n * @param path The file path that was added or deleted\n */\n function invalidateRoutes(\n path: string,\n event: 'add' | 'change' | 'unlink',\n ) {\n if (!isRouteLikeFile(path)) {\n return;\n }\n\n // Add/remove changes the route graph shape, so the discovery caches\n // must be rebuilt. Plain edits can keep using the current file set.\n if (event !== 'change') {\n invalidateDiscoveryCaches();\n }\n\n if (event === 'change') {\n reportRouteDiagnostics(path);\n } else if (event === 'unlink') {\n routeDiagnosticCache.delete(path);\n discoverPageRouteFiles().forEach((file) =>\n reportRouteDiagnostics(file),\n );\n } else {\n discoverPageRouteFiles().forEach((file) =>\n reportRouteDiagnostics(file),\n );\n }\n\n invalidateFileModules(server, path);\n\n // For an in-place edit we only need module invalidation. Keeping the\n // app alive here lets Angular/Vite attempt the narrower HMR path.\n if (event === 'change') {\n return;\n }\n\n server.moduleGraph.fileToModulesMap.forEach((mods) => {\n mods.forEach((mod) => {\n if (mod.id?.includes('analogjs') && mod.id?.includes('fesm')) {\n server.moduleGraph.invalidateModule(mod);\n\n mod.importers.forEach((imp) => {\n server.moduleGraph.invalidateModule(imp);\n });\n }\n });\n });\n\n server.ws.send('analog:debug-full-reload', {\n plugin: 'platform:router-plugin',\n reason: 'route-graph-shape-changed',\n event,\n path,\n });\n server.ws.send({\n type: 'full-reload',\n });\n }\n\n server.watcher.on('add', (path) => invalidateRoutes(path, 'add'));\n server.watcher.on('change', (path) => invalidateRoutes(path, 'change'));\n server.watcher.on('unlink', (path) => invalidateRoutes(path, 'unlink'));\n\n // Vite's watcher only covers the app root by default.\n // additionalPagesDirs / additionalContentDirs live outside the\n // root (e.g. libs/shared/feature in a monorepo), so file\n // add/rename/delete events are never fired for them. Explicitly\n // add these directories to chokidar so route invalidation works.\n for (const dir of [...additionalPagesDirs, ...additionalContentDirs]) {\n server.watcher.add(dir);\n }\n\n discoverPageRouteFiles().forEach((file) =>\n reportRouteDiagnostics(file),\n );\n },\n },\n {\n name: 'analog-glob-routes',\n // enforce: 'post' ensures this transform runs AFTER the Angular compiler\n // plugin, which replaces module content with its own compiled output.\n // Without this, the Angular plugin would overwrite the route replacements.\n enforce: 'post',\n config(_config) {\n config = _config;\n root = normalizePath(resolve(workspaceRoot, config.root || '.') || '.');\n },\n /**\n * Transforms code to replace ANALOG_ROUTE_FILES and ANALOG_CONTENT_ROUTE_FILES\n * placeholders with actual dynamic imports of discovered route and content files.\n *\n * @param code The source code to transform\n * @returns Transformed code with dynamic imports or undefined if no transformation needed\n */\n // Vite 8 / Rolldown filtered transform: the `filter.code` substring\n // pre-filter lets the bundler skip modules that don't contain the\n // marker. '_ROUTE_FILES' is a common substring of both\n // 'ANALOG_ROUTE_FILES' and 'ANALOG_CONTENT_ROUTE_FILES'.\n //\n // IMPORTANT: Do NOT change this to 'ANALOG_ROUTE_FILES' — that is NOT\n // a substring of 'ANALOG_CONTENT_ROUTE_FILES' (they diverge at\n // position 7: 'ANALOG_C...' vs 'ANALOG_R...'). When tsconfig path\n // aliases resolve @analogjs/router and @analogjs/router/content to\n // separate source files, each variable lives in its own module and\n // the filter must match both independently.\n transform: {\n filter: {\n code: '_ROUTE_FILES',\n },\n handler(code) {\n if (\n code.includes('ANALOG_ROUTE_FILES') ||\n code.includes('ANALOG_CONTENT_ROUTE_FILES')\n ) {\n // Discover route files using tinyglobby\n // NOTE: { absolute: true } returns absolute paths for ALL files\n const routeFiles = discoverRouteFiles();\n\n // Discover content files using tinyglobby\n const contentRouteFiles = discoverContentRouteFiles();\n\n let result = code.replace(\n 'ANALOG_ROUTE_FILES = {};',\n `\n ANALOG_ROUTE_FILES = {${routeFiles.map((module) => {\n // Keys are app-root-relative for in-app files,\n // workspace-relative for library files (additionalPagesDirs).\n // import() keeps absolute paths for Vite's module resolution.\n const key = getModuleKey(module);\n return `\"${key}\": () => import('${module}')`;\n })}};\n `,\n );\n\n result = result.replace(\n 'ANALOG_CONTENT_ROUTE_FILES = {};',\n `\n ANALOG_CONTENT_ROUTE_FILES = {${contentRouteFiles.map((module) => {\n const key = getModuleKey(module);\n return `\"${key}\": () => import('${module}?analog-content-file=true').then(m => m.default)`;\n })}};\n `,\n );\n\n result = result.replace(\n 'ANALOG_CONTENT_FILE_COUNT = 0',\n `ANALOG_CONTENT_FILE_COUNT = ${contentRouteFiles.length}`,\n );\n\n return {\n code: result,\n map: { mappings: '' },\n };\n }\n\n return;\n },\n },\n },\n {\n name: 'analog-glob-endpoints',\n // enforce: 'post' ensures this transform runs AFTER the Angular compiler\n // plugin, which replaces module content with its own compiled output.\n // Without this, the Angular plugin would overwrite the endpoint replacements.\n enforce: 'post',\n /**\n * Transforms code to replace ANALOG_PAGE_ENDPOINTS placeholder\n * with actual dynamic imports of discovered server endpoint files.\n *\n * @param code The source code to transform\n * @returns Transformed code with dynamic imports or undefined if no transformation needed\n */\n transform: {\n filter: {\n code: 'ANALOG_PAGE_ENDPOINTS',\n },\n handler(code) {\n if (code.includes('ANALOG_PAGE_ENDPOINTS')) {\n // Discover server endpoint files using tinyglobby\n const endpointFiles = discoverEndpointFiles();\n\n const result = code.replace(\n 'ANALOG_PAGE_ENDPOINTS = {};',\n `\n ANALOG_PAGE_ENDPOINTS = {${endpointFiles.map((module) => {\n const key = getModuleKey(module);\n return `\"${key}\": () => import('${module}')`;\n })}};\n `,\n );\n\n return {\n code: result,\n map: { mappings: '' },\n };\n }\n\n return;\n },\n },\n },\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,aAAa,SAA6B;CACxD,MAAM,gBAAgB,cACpB,SAAS,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI,CAC5E;CACA,IAAI;CACJ,IAAI;CAIJ,MAAM,uBAAuB,QAAgB;EAC3C,MAAM,gBAAgB,cACpB,IAAI,WAAW,GAAG,cAAc,EAAE,KAAK,QAAQ,gBAC3C,MACA,IAAI,WAAW,GAAG,IAChB,GAAG,gBAAgB,QACnB,QAAQ,eAAe,GAAG,CAClC;EACA,OAAO,cAAc,SAAS,GAAG,IAC7B,cAAc,MAAM,GAAG,EAAE,IACzB;CACN;CAGA,MAAM,uBAAuB,SAAS,uBAAuB,CAAC,EAAA,CAAG,KAAK,QACpE,oBAAoB,GAAG,CACzB;CACA,MAAM,yBAAyB,SAAS,yBAAyB,CAAC,EAAA,CAAG,KAClE,QAAQ,oBAAoB,GAAG,CAClC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AA4B,GAC1C;MAGA,MAAM,aAAa,mBAAmB;MAGtC,MAAM,oBAAoB,0BAA0B;MAEpD,IAAI,SAAS,KAAK,QAChB,4BACA;sCACwB,WAAW,KAAK,WAAW;OAKjD,OAAO,IADK,aAAa,MACd,EAAI,mBAAmB,OAAO;MAC3C,CAAC,EAAE;aAEL;MAEA,SAAS,OAAO,QACd,oCACA;4CAC8B,kBAAkB,KAAK,WAAW;OAEhE,OAAO,IADK,aAAa,MACd,EAAI,mBAAmB,OAAO;MAC3C,CAAC,EAAE;aAEH;MAEA,SAAS,OAAO,QACd,iCACA,+BAA+B,kBAAkB,QACnD;MAEA,OAAO;OACL,MAAM;OACN,KAAK,EAAE,UAAU,GAAG;MACtB;KACF;IAGF;GACF;EACF;EACA;GACE,MAAM;GAIN,SAAS;;;;;;;;GAQT,WAAW;IACT,QAAQ,EACN,MAAM,wBACR;IACA,QAAQ,MAAM;KACZ,IAAI,KAAK,SAAS,uBAAuB,GAAG;MAE1C,MAAM,gBAAgB,sBAAsB;MAY5C,OAAO;OACL,MAXa,KAAK,QAClB,+BACA;yCAC2B,cAAc,KAAK,WAAW;QAEvD,OAAO,IADK,aAAa,MACd,EAAI,mBAAmB,OAAO;OAC3C,CAAC,EAAE;aAKG;OACN,KAAK,EAAE,UAAU,GAAG;MACtB;KACF;IAGF;GACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"router-plugin.js","names":[],"sources":["../../../src/lib/router-plugin.ts"],"sourcesContent":["import { normalizePath, Plugin, UserConfig, ViteDevServer } from 'vite';\nimport { globSync } from 'tinyglobby';\nimport { readFileSync } from 'node:fs';\nimport { isAbsolute, relative, resolve } from 'node:path';\n\nimport { Options } from './options.js';\nimport {\n analyzeAnalogRouteFile,\n formatAnalogRouteIdiomDiagnostic,\n} from './route-idiom-diagnostics.js';\n\n/**\n * Router plugin that handles route file discovery and hot module replacement.\n *\n * This plugin provides three main functionalities:\n * 1. Route invalidation when files are added/deleted (HMR workaround)\n * 2. Dynamic route file discovery and import generation\n * 3. Content route file discovery for markdown and Analog content\n *\n * @param options Configuration options for the router plugin\n * @returns Array of Vite plugins for route handling\n *\n * IMPORTANT: This plugin uses tinyglobby for file discovery.\n * Key behavior with { dot: true, absolute: true }:\n * - Returns absolute paths for ALL discovered files\n * - Path normalization is required to match expected output format\n * - Files within project root must use relative paths in object keys\n * - Files outside project root keep absolute paths in object keys\n */\nexport function routerPlugin(options?: Options): Plugin[] {\n const workspaceRoot = normalizePath(\n options?.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd(),\n );\n let config: UserConfig;\n let root: string;\n // Option dirs are workspace-relative, often written with a leading `/`.\n // Normalize them once into absolute workspace paths so watcher events,\n // glob patterns, and key generation all compare against the same shape.\n const normalizeWatchedDir = (dir: string) => {\n const normalizedDir = normalizePath(\n dir.startsWith(`${workspaceRoot}/`) || dir === workspaceRoot\n ? dir\n : dir.startsWith('/')\n ? `${workspaceRoot}${dir}`\n : resolve(workspaceRoot, dir),\n );\n return normalizedDir.endsWith('/')\n ? normalizedDir.slice(0, -1)\n : normalizedDir;\n };\n // Computed eagerly — these depend only on `options` and `workspaceRoot`,\n // both of which are fixed at construction time.\n const additionalPagesDirs = (options?.additionalPagesDirs || []).map((dir) =>\n normalizeWatchedDir(dir),\n );\n const additionalContentDirs = (options?.additionalContentDirs || []).map(\n (dir) => normalizeWatchedDir(dir),\n );\n // Returns every directory that can contain route-like files. The root-\n // relative entries are only available after the Vite `config` hook sets\n // `root`. The short-form fallbacks (`/src/app/pages`, etc.) let watcher\n // events match before `config` runs — they cover the common convention\n // where paths start with these prefixes.\n const getRouteLikeDirs = () => [\n ...(root\n ? [\n normalizeWatchedDir(`${root}/src/app/pages`),\n normalizeWatchedDir(`${root}/src/content`),\n ]\n : []),\n '/src/app/pages',\n '/src/content',\n ...additionalPagesDirs,\n ...additionalContentDirs,\n ];\n // These lists are used repeatedly by transform hooks during serve. Keeping\n // them warm avoids a full glob on every route/content invalidation.\n let routeFilesCache: string[] | undefined;\n let pageRouteFilesCache: string[] | undefined;\n let contentRouteFilesCache: string[] | undefined;\n let endpointFilesCache: string[] | undefined;\n const routeDiagnosticCache = new Map<string, string>();\n const isRouteLikeFile = (path: string) => {\n // Watcher paths from chokidar are already absolute — `normalizePath`\n // (forward-slash only) is sufficient; `resolve()` would be a no-op.\n const normalizedPath = normalizePath(path);\n\n return getRouteLikeDirs().some(\n (dir) => normalizedPath === dir || normalizedPath.startsWith(`${dir}/`),\n );\n };\n const discoverRouteFiles = () => {\n routeFilesCache ??= globSync(\n [\n `${root}/src/app/pages/**/*.page.ts`,\n `${root}/src/app/pages/**/*.page.tsrx`,\n ...additionalPagesDirs.flatMap((dir) => [\n `${dir}/**/*.page.ts`,\n `${dir}/**/*.page.tsrx`,\n ]),\n ],\n { dot: true, absolute: true },\n );\n\n return routeFilesCache;\n };\n const discoverContentRouteFiles = () => {\n contentRouteFilesCache ??= globSync(\n [\n `${root}/src/app/pages/**/*.md`,\n `${root}/src/content/**/*.md`,\n ...additionalContentDirs.map((dir) => `${dir}/**/*.md`),\n ],\n { dot: true, absolute: true },\n );\n\n return contentRouteFilesCache;\n };\n const discoverEndpointFiles = () => {\n endpointFilesCache ??= globSync(\n [\n `${root}/src/app/pages/**/*.server.ts`,\n ...additionalPagesDirs.map((dir) => `${dir}/**/*.server.ts`),\n ],\n { dot: true, absolute: true },\n );\n\n return endpointFilesCache;\n };\n const discoverPageRouteFiles = () => {\n pageRouteFilesCache ??= discoverRouteFiles().filter(\n (file) => file.endsWith('.page.ts') || file.endsWith('.page.tsrx'),\n );\n\n return pageRouteFilesCache;\n };\n const invalidateDiscoveryCaches = () => {\n routeFilesCache = undefined;\n pageRouteFilesCache = undefined;\n contentRouteFilesCache = undefined;\n endpointFilesCache = undefined;\n };\n const reportRouteDiagnostics = (path: string) => {\n // The route idiom checks parse TypeScript; `.page.tsrx` files are skipped.\n if (!path.endsWith('.page.ts')) {\n return;\n }\n\n try {\n const code = readFileSync(path, 'utf-8');\n const routeFiles = discoverPageRouteFiles();\n const diagnostics = analyzeAnalogRouteFile({\n filename: path,\n code,\n routeFiles,\n });\n\n const rendered = diagnostics.map((diagnostic) =>\n formatAnalogRouteIdiomDiagnostic(diagnostic, path, workspaceRoot),\n );\n const fingerprint = rendered.join('\\n\\n');\n\n if (!fingerprint) {\n routeDiagnosticCache.delete(path);\n return;\n }\n\n if (routeDiagnosticCache.get(path) === fingerprint) {\n return;\n }\n\n routeDiagnosticCache.set(path, fingerprint);\n rendered.forEach((message) => console.warn(message));\n } catch {\n routeDiagnosticCache.delete(path);\n }\n };\n const getModuleKey = (module: string) => {\n // Before config sets `root`, fall back to workspace-relative keys.\n if (!root) {\n return `/${normalizePath(relative(workspaceRoot, module))}`;\n }\n\n const relToRoot = normalizePath(relative(root, module));\n // Use true path containment instead of a raw prefix check so siblings like\n // `/apps/my-app-tools/...` are not mistaken for files inside `/apps/my-app`.\n const isInRoot = !relToRoot.startsWith('..') && !isAbsolute(relToRoot);\n\n if (isInRoot) {\n return `/${relToRoot}`;\n }\n\n return `/${normalizePath(relative(workspaceRoot, module))}`;\n };\n const invalidateFileModules = (server: ViteDevServer, path: string) => {\n const normalizedPath = normalizePath(path);\n // A newly added page can be discovered before its final contents settle.\n // Invalidate the page module itself so later edits don't keep serving the\n // first incomplete transform from Vite's module graph.\n const fileModules =\n server.moduleGraph.getModulesByFile?.(normalizedPath) ??\n server.moduleGraph.fileToModulesMap.get(normalizedPath);\n\n fileModules?.forEach((mod) => {\n server.moduleGraph.invalidateModule(mod);\n\n mod.importers.forEach((imp) => {\n server.moduleGraph.invalidateModule(imp);\n });\n });\n };\n\n return [\n {\n name: 'analogjs-router-invalidate-routes',\n configureServer(server) {\n /**\n * Invalidates route modules when files are added or deleted.\n * This is a workaround for Vite's HMR limitations with dynamic imports.\n *\n * @param path The file path that was added or deleted\n */\n function invalidateRoutes(\n path: string,\n event: 'add' | 'change' | 'unlink',\n ) {\n if (!isRouteLikeFile(path)) {\n return;\n }\n\n // Add/remove changes the route graph shape, so the discovery caches\n // must be rebuilt. Plain edits can keep using the current file set.\n if (event !== 'change') {\n invalidateDiscoveryCaches();\n }\n\n if (event === 'change') {\n reportRouteDiagnostics(path);\n } else if (event === 'unlink') {\n routeDiagnosticCache.delete(path);\n discoverPageRouteFiles().forEach((file) =>\n reportRouteDiagnostics(file),\n );\n } else {\n discoverPageRouteFiles().forEach((file) =>\n reportRouteDiagnostics(file),\n );\n }\n\n invalidateFileModules(server, path);\n\n // For an in-place edit we only need module invalidation. Keeping the\n // app alive here lets Angular/Vite attempt the narrower HMR path.\n if (event === 'change') {\n return;\n }\n\n server.moduleGraph.fileToModulesMap.forEach((mods) => {\n mods.forEach((mod) => {\n if (mod.id?.includes('analogjs') && mod.id?.includes('fesm')) {\n server.moduleGraph.invalidateModule(mod);\n\n mod.importers.forEach((imp) => {\n server.moduleGraph.invalidateModule(imp);\n });\n }\n });\n });\n\n server.ws.send('analog:debug-full-reload', {\n plugin: 'platform:router-plugin',\n reason: 'route-graph-shape-changed',\n event,\n path,\n });\n server.ws.send({\n type: 'full-reload',\n });\n }\n\n server.watcher.on('add', (path) => invalidateRoutes(path, 'add'));\n server.watcher.on('change', (path) => invalidateRoutes(path, 'change'));\n server.watcher.on('unlink', (path) => invalidateRoutes(path, 'unlink'));\n\n // Vite's watcher only covers the app root by default.\n // additionalPagesDirs / additionalContentDirs live outside the\n // root (e.g. libs/shared/feature in a monorepo), so file\n // add/rename/delete events are never fired for them. Explicitly\n // add these directories to chokidar so route invalidation works.\n for (const dir of [...additionalPagesDirs, ...additionalContentDirs]) {\n server.watcher.add(dir);\n }\n\n discoverPageRouteFiles().forEach((file) =>\n reportRouteDiagnostics(file),\n );\n },\n },\n {\n name: 'analog-glob-routes',\n // enforce: 'post' ensures this transform runs AFTER the Angular compiler\n // plugin, which replaces module content with its own compiled output.\n // Without this, the Angular plugin would overwrite the route replacements.\n enforce: 'post',\n config(_config) {\n config = _config;\n root = normalizePath(resolve(workspaceRoot, config.root || '.') || '.');\n },\n /**\n * Transforms code to replace ANALOG_ROUTE_FILES and ANALOG_CONTENT_ROUTE_FILES\n * placeholders with actual dynamic imports of discovered route and content files.\n *\n * @param code The source code to transform\n * @returns Transformed code with dynamic imports or undefined if no transformation needed\n */\n // Vite 8 / Rolldown filtered transform: the `filter.code` substring\n // pre-filter lets the bundler skip modules that don't contain the\n // marker. '_ROUTE_FILES' is a common substring of both\n // 'ANALOG_ROUTE_FILES' and 'ANALOG_CONTENT_ROUTE_FILES'.\n //\n // IMPORTANT: Do NOT change this to 'ANALOG_ROUTE_FILES' — that is NOT\n // a substring of 'ANALOG_CONTENT_ROUTE_FILES' (they diverge at\n // position 7: 'ANALOG_C...' vs 'ANALOG_R...'). When tsconfig path\n // aliases resolve @analogjs/router and @analogjs/router/content to\n // separate source files, each variable lives in its own module and\n // the filter must match both independently.\n transform: {\n filter: {\n code: '_ROUTE_FILES',\n },\n handler(code) {\n if (\n code.includes('ANALOG_ROUTE_FILES') ||\n code.includes('ANALOG_CONTENT_ROUTE_FILES')\n ) {\n // Discover route files using tinyglobby\n // NOTE: { absolute: true } returns absolute paths for ALL files\n const routeFiles = discoverRouteFiles();\n\n // Discover content files using tinyglobby\n const contentRouteFiles = discoverContentRouteFiles();\n\n let result = code.replace(\n 'ANALOG_ROUTE_FILES = {};',\n `\n ANALOG_ROUTE_FILES = {${routeFiles.map((module) => {\n // Keys are app-root-relative for in-app files,\n // workspace-relative for library files (additionalPagesDirs).\n // import() keeps absolute paths for Vite's module resolution.\n const key = getModuleKey(module);\n return `\"${key}\": () => import('${module}')`;\n })}};\n `,\n );\n\n result = result.replace(\n 'ANALOG_CONTENT_ROUTE_FILES = {};',\n `\n ANALOG_CONTENT_ROUTE_FILES = {${contentRouteFiles.map((module) => {\n const key = getModuleKey(module);\n return `\"${key}\": () => import('${module}?analog-content-file=true')`;\n })}};\n `,\n );\n\n result = result.replace(\n 'ANALOG_CONTENT_FILE_COUNT = 0',\n `ANALOG_CONTENT_FILE_COUNT = ${contentRouteFiles.length}`,\n );\n\n return {\n code: result,\n map: { mappings: '' },\n };\n }\n\n return;\n },\n },\n },\n {\n name: 'analog-glob-endpoints',\n // enforce: 'post' ensures this transform runs AFTER the Angular compiler\n // plugin, which replaces module content with its own compiled output.\n // Without this, the Angular plugin would overwrite the endpoint replacements.\n enforce: 'post',\n /**\n * Transforms code to replace ANALOG_PAGE_ENDPOINTS placeholder\n * with actual dynamic imports of discovered server endpoint files.\n *\n * @param code The source code to transform\n * @returns Transformed code with dynamic imports or undefined if no transformation needed\n */\n transform: {\n filter: {\n code: 'ANALOG_PAGE_ENDPOINTS',\n },\n handler(code) {\n if (code.includes('ANALOG_PAGE_ENDPOINTS')) {\n // Discover server endpoint files using tinyglobby\n const endpointFiles = discoverEndpointFiles();\n\n const result = code.replace(\n 'ANALOG_PAGE_ENDPOINTS = {};',\n `\n ANALOG_PAGE_ENDPOINTS = {${endpointFiles.map((module) => {\n const key = getModuleKey(module);\n return `\"${key}\": () => import('${module}')`;\n })}};\n `,\n );\n\n return {\n code: result,\n map: { mappings: '' },\n };\n }\n\n return;\n },\n },\n },\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,aAAa,SAA6B;CACxD,MAAM,gBAAgB,cACpB,SAAS,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI,CAC5E;CACA,IAAI;CACJ,IAAI;CAIJ,MAAM,uBAAuB,QAAgB;EAC3C,MAAM,gBAAgB,cACpB,IAAI,WAAW,GAAG,cAAc,EAAE,KAAK,QAAQ,gBAC3C,MACA,IAAI,WAAW,GAAG,IAChB,GAAG,gBAAgB,QACnB,QAAQ,eAAe,GAAG,CAClC;EACA,OAAO,cAAc,SAAS,GAAG,IAC7B,cAAc,MAAM,GAAG,EAAE,IACzB;CACN;CAGA,MAAM,uBAAuB,SAAS,uBAAuB,CAAC,EAAA,CAAG,KAAK,QACpE,oBAAoB,GAAG,CACzB;CACA,MAAM,yBAA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AK,GAAG;GACxE;;;;;;;;GAmBA,WAAW;IACT,QAAQ,EACN,MAAM,eACR;IACA,QAAQ,MAAM;KACZ,IACE,KAAK,SAAS,oBAAoB,KAClC,KAAK,SAAS,4BAA4B,GAC1C;MAGA,MAAM,aAAa,mBAAmB;MAGtC,MAAM,oBAAoB,0BAA0B;MAEpD,IAAI,SAAS,KAAK,QAChB,4BACA;sCACwB,WAAW,KAAK,WAAW;OAKjD,OAAO,IADK,aAAa,MACd,EAAI,mBAAmB,OAAO;MAC3C,CAAC,EAAE;aAEL;MAEA,SAAS,OAAO,QACd,oCACA;4CAC8B,kBAAkB,KAAK,WAAW;OAEhE,OAAO,IADK,aAAa,MACd,EAAI,mBAAmB,OAAO;MAC3C,CAAC,EAAE;aAEH;MAEA,SAAS,OAAO,QACd,iCACA,+BAA+B,kBAAkB,QACnD;MAEA,OAAO;OACL,MAAM;OACN,KAAK,EAAE,UAAU,GAAG;MACtB;KACF;IAGF;GACF;EACF;EACA;GACE,MAAM;GAIN,SAAS;;;;;;;;GAQT,WAAW;IACT,QAAQ,EACN,MAAM,wBACR;IACA,QAAQ,MAAM;KACZ,IAAI,KAAK,SAAS,uBAAuB,GAAG;MAE1C,MAAM,gBAAgB,sBAAsB;MAY5C,OAAO;OACL,MAXa,KAAK,QAClB,+BACA;yCAC2B,cAAc,KAAK,WAAW;QAEvD,OAAO,IADK,aAAa,MACd,EAAI,mBAAmB,OAAO;OAC3C,CAAC,EAAE;aAKG;OACN,KAAK,EAAE,UAAU,GAAG;MACtB;KACF;IAGF;GACF;EACF;CACF;AACF"}
@@ -0,0 +1,9 @@
1
+ import { type Plugin } from "vite";
2
+ import type { Options, ServerOptions } from "./options.js";
3
+ /**
4
+ * Builds and serves the app from `server.entry` instead of Nitro: the client
5
+ * and one server bundle in `vite build`, and the entry's app behind Vite's
6
+ * own middleware in dev. Fills in the `ANALOG_SERVER_MANIFEST` placeholder
7
+ * that `createAnalogRequestHandler()` in `@analogjs/router/server` reads.
8
+ */
9
+ export declare function serverPlugin(server: ServerOptions, options?: Options): Plugin;
@@ -0,0 +1,170 @@
1
+ import { getPageEndpoints } from "./get-page-endpoints.js";
2
+ import { getServerFnHandlers } from "./nitro/get-server-fn-handlers.js";
3
+ import { relative, resolve } from "node:path";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { normalizePath } from "vite";
6
+ import { toNodeHandler } from "srvx/node";
7
+ //#region packages/platform/src/lib/server-plugin.ts
8
+ var MANIFEST_PLACEHOLDER = /ANALOG_SERVER_MANIFEST = \{\}/;
9
+ var DEV_TEMPLATE = Symbol.for("@analogjs/platform/dev-template");
10
+ var HTML_MIDDLEWARES = [
11
+ "viteIndexHtmlMiddleware",
12
+ "vite404Middleware",
13
+ "viteSpaFallbackMiddleware",
14
+ "viteHtmlFallbackMiddleware"
15
+ ];
16
+ var NITRO_PLUGINS = ["nitro:main", "@analogjs/vite-plugin-nitro"];
17
+ /**
18
+ * Builds and serves the app from `server.entry` instead of Nitro: the client
19
+ * and one server bundle in `vite build`, and the entry's app behind Vite's
20
+ * own middleware in dev. Fills in the `ANALOG_SERVER_MANIFEST` placeholder
21
+ * that `createAnalogRequestHandler()` in `@analogjs/router/server` reads.
22
+ */
23
+ function serverPlugin(server, options = {}) {
24
+ const workspaceRoot = options.workspaceRoot ?? process.env["NX_WORKSPACE_ROOT"] ?? process.cwd();
25
+ const apiPrefix = options.apiPrefix ?? "api";
26
+ let root = process.cwd();
27
+ let isBuild = false;
28
+ let builtTemplate;
29
+ let manifestId;
30
+ const rootDir = () => relative(workspaceRoot, root) || ".";
31
+ const indexHtml = () => resolve(root, options.index ?? "index.html");
32
+ return {
33
+ name: "@analogjs/platform-server",
34
+ config(config, { command }) {
35
+ if ((config.plugins ?? []).flat(Infinity).some((p) => NITRO_PLUGINS.includes(p?.name ?? ""))) throw new Error("[@analogjs/platform] `analog({ server })` replaces Nitro; remove `nitro()` from the Vite plugins.");
36
+ if (options.i18n?.workers === true) throw new Error("[@analogjs/platform] `i18n.workers` needs Nitro; remove it to use `analog({ server })`, which renders without locale workers.");
37
+ root = normalizePath(resolve(config.root ?? process.cwd()));
38
+ isBuild = command === "build";
39
+ const outDir = (name) => resolve(workspaceRoot, "dist", rootDir(), name);
40
+ return {
41
+ define: {
42
+ ANALOG_API_PREFIX: JSON.stringify(apiPrefix),
43
+ ...options.i18n && {
44
+ ANALOG_I18N_DEFAULT_LOCALE: JSON.stringify(options.i18n.defaultLocale),
45
+ ANALOG_I18N_LOCALES: JSON.stringify(options.i18n.locales)
46
+ }
47
+ },
48
+ environments: {
49
+ client: { build: {
50
+ outDir: outDir("client"),
51
+ rollupOptions: { input: indexHtml() }
52
+ } },
53
+ ssr: { build: {
54
+ outDir: outDir("server"),
55
+ copyPublicDir: false,
56
+ rollupOptions: { input: { main: resolve(root, server.entry) } }
57
+ } }
58
+ },
59
+ builder: {
60
+ sharedPlugins: true,
61
+ async buildApp(builder) {
62
+ await builder.build(builder.environments["client"]);
63
+ await builder.build(builder.environments["ssr"]);
64
+ }
65
+ }
66
+ };
67
+ },
68
+ writeBundle(_options, bundle) {
69
+ if (this.environment.name === "client") {
70
+ const document = bundle[normalizePath(relative(root, indexHtml()))];
71
+ if (document?.type === "asset") builtTemplate = String(document.source);
72
+ }
73
+ },
74
+ transform: {
75
+ filter: { code: "ANALOG_SERVER_MANIFEST" },
76
+ handler(code, id) {
77
+ if (!MANIFEST_PLACEHOLDER.test(code)) return;
78
+ manifestId = id;
79
+ return code.replace(MANIFEST_PLACEHOLDER, `ANALOG_SERVER_MANIFEST = ${serverManifest()}`);
80
+ }
81
+ },
82
+ configureServer(viteServer) {
83
+ globalThis[DEV_TEMPLATE] = (url) => viteServer.transformIndexHtml(url, readFileSync(indexHtml(), "utf-8"));
84
+ const invalidateManifest = (file) => {
85
+ const graph = viteServer.environments["ssr"].moduleGraph;
86
+ const mod = manifestId && graph.getModuleById(manifestId);
87
+ if (file.endsWith(".server.ts") && mod) graph.invalidateModule(mod);
88
+ };
89
+ viteServer.watcher.on("add", invalidateManifest);
90
+ viteServer.watcher.on("unlink", invalidateManifest);
91
+ return () => {
92
+ removeHtmlMiddlewares(viteServer.middlewares);
93
+ viteServer.middlewares.use(devMiddleware(viteServer, resolve(root, server.entry)));
94
+ };
95
+ }
96
+ };
97
+ function requireBuiltTemplate() {
98
+ if (builtTemplate === void 0) throw new Error(`[@analogjs/platform] The client build didn't emit ${relative(root, indexHtml())}, which the server renders around.`);
99
+ return builtTemplate;
100
+ }
101
+ /**
102
+ * The manifest object literal: the template, and lazy imports of the SSR
103
+ * renderer, the server config, every server function module, and page
104
+ * endpoints keyed by route.
105
+ */
106
+ function serverManifest() {
107
+ const src = `${root}/src`;
108
+ const lazy = (file) => `() => import(${JSON.stringify(file)})`;
109
+ const appConfig = [`${src}/app/app.config.server.ts`, `${src}/app.config.server.ts`].find((file) => existsSync(file));
110
+ const discovery = {
111
+ workspaceRoot,
112
+ sourceRoot: "src",
113
+ rootDir: rootDir()
114
+ };
115
+ const pageEndpoints = getPageEndpoints({
116
+ ...discovery,
117
+ additionalPagesDirs: options.additionalPagesDirs
118
+ }).map(({ file, route }) => `${JSON.stringify(`/${apiPrefix}/_analog${route}`)}: ${lazy(normalizePath(file))}`);
119
+ const serverFnModules = getServerFnHandlers(discovery).map(({ file }) => lazy(file));
120
+ const template = isBuild ? `async () => ${JSON.stringify(requireBuiltTemplate())}` : `(url) => globalThis[Symbol.for('@analogjs/platform/dev-template')](url)`;
121
+ return `{
122
+ apiPrefix: ${JSON.stringify(apiPrefix)},
123
+ template: ${template},
124
+ render: () => import(${JSON.stringify(normalizePath(resolve(root, options.entryServer ?? "src/main.server.ts")))}).then((m) => m.default),
125
+ config: ${appConfig ? `() => import(${JSON.stringify(appConfig)}).then((m) => m.config)` : `async () => ({ providers: [] })`},
126
+ serverFnModules: [${serverFnModules.join(", ")}],
127
+ pageEndpoints: {${pageEndpoints.join(", ")}},
128
+ }`;
129
+ }
130
+ }
131
+ /**
132
+ * Hands every request Vite doesn't serve to the entry's `fetch`. The handler is
133
+ * recreated when the server module graph changes (ssrLoadModule returns a new
134
+ * module), and the previous entry's `close()` is called.
135
+ */
136
+ function devMiddleware(viteServer, entry) {
137
+ let current;
138
+ async function getHandler() {
139
+ const loaded = await viteServer.ssrLoadModule(entry);
140
+ if (current?.entry !== loaded) {
141
+ const previous = current?.entry.default;
142
+ current = {
143
+ entry: loaded,
144
+ handle: toHandler(loaded)
145
+ };
146
+ Promise.resolve().then(() => previous?.close?.()).catch(() => void 0);
147
+ }
148
+ return current.handle;
149
+ }
150
+ return (req, res, next) => {
151
+ getHandler().then((handle) => handle(req, res)).catch((error) => {
152
+ viteServer.ssrFixStacktrace(error);
153
+ next(error);
154
+ });
155
+ };
156
+ }
157
+ /** A Node handler around the `fetch` of a Fetchable entry (https://fetchable.org). */
158
+ function toHandler(entry) {
159
+ const fetchable = entry.default;
160
+ const handleRequest = fetchable?.fetch;
161
+ if (typeof handleRequest !== "function") throw new Error("[@analogjs/platform] The server entry must be a Fetchable module: a default export with `fetch(request)`. `createApp()` entries are no longer supported; see https://analogjs.org/docs/features/server/custom-server.");
162
+ return toNodeHandler((request) => handleRequest.call(fetchable, request));
163
+ }
164
+ function removeHtmlMiddlewares(middlewares) {
165
+ middlewares.stack = middlewares.stack.filter((layer) => !HTML_MIDDLEWARES.includes(layer.handle.name ?? ""));
166
+ }
167
+ //#endregion
168
+ export { serverPlugin };
169
+
170
+ //# sourceMappingURL=server-plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-plugin.js","names":[],"sources":["../../../src/lib/server-plugin.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { relative, resolve } from 'node:path';\nimport type { NodeHttp1Handler } from 'srvx';\nimport { toNodeHandler } from 'srvx/node';\nimport {\n normalizePath,\n type Connect,\n type Plugin,\n type ViteDevServer,\n} from 'vite';\n\nimport { getPageEndpoints } from './get-page-endpoints.js';\nimport { getServerFnHandlers } from './nitro/get-server-fn-handlers.js';\nimport type { Options, ServerOptions } from './options.js';\n\nconst MANIFEST_PLACEHOLDER = /ANALOG_SERVER_MANIFEST = \\{\\}/;\nconst DEV_TEMPLATE = Symbol.for('@analogjs/platform/dev-template');\nconst HTML_MIDDLEWARES = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n 'viteHtmlFallbackMiddleware',\n];\nconst NITRO_PLUGINS = ['nitro:main', '@analogjs/vite-plugin-nitro'];\n\ntype ServerEntry = {\n default?: {\n fetch?: (request: Request) => Response | Promise<Response>;\n close?: () => unknown;\n };\n};\n\n/**\n * Builds and serves the app from `server.entry` instead of Nitro: the client\n * and one server bundle in `vite build`, and the entry's app behind Vite's\n * own middleware in dev. Fills in the `ANALOG_SERVER_MANIFEST` placeholder\n * that `createAnalogRequestHandler()` in `@analogjs/router/server` reads.\n */\nexport function serverPlugin(\n server: ServerOptions,\n options: Options = {},\n): Plugin {\n const workspaceRoot =\n options.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd();\n const apiPrefix = options.apiPrefix ?? 'api';\n let root = process.cwd();\n let isBuild = false;\n let builtTemplate: string | undefined;\n let manifestId: string | undefined;\n\n const rootDir = () => relative(workspaceRoot, root) || '.';\n const indexHtml = () => resolve(root, options.index ?? 'index.html');\n\n return {\n name: '@analogjs/platform-server',\n config(config, { command }) {\n const plugins = ((config.plugins ?? []) as unknown[]).flat(Infinity) as (\n | { name?: string }\n | null\n | undefined\n )[];\n if (plugins.some((p) => NITRO_PLUGINS.includes(p?.name ?? ''))) {\n throw new Error(\n '[@analogjs/platform] `analog({ server })` replaces Nitro; remove `nitro()` from the Vite plugins.',\n );\n }\n if (options.i18n?.workers === true) {\n throw new Error(\n '[@analogjs/platform] `i18n.workers` needs Nitro; remove it to use `analog({ server })`, which renders without locale workers.',\n );\n }\n root = normalizePath(resolve(config.root ?? process.cwd()));\n isBuild = command === 'build';\n const outDir = (name: string) =>\n resolve(workspaceRoot, 'dist', rootDir(), name);\n return {\n // Build-time values the router reads, as `nitro()` defines them.\n define: {\n ANALOG_API_PREFIX: JSON.stringify(apiPrefix),\n ...(options.i18n && {\n ANALOG_I18N_DEFAULT_LOCALE: JSON.stringify(\n options.i18n.defaultLocale,\n ),\n ANALOG_I18N_LOCALES: JSON.stringify(options.i18n.locales),\n }),\n },\n environments: {\n client: {\n build: {\n outDir: outDir('client'),\n rollupOptions: { input: indexHtml() },\n },\n },\n ssr: {\n build: {\n outDir: outDir('server'),\n copyPublicDir: false,\n rollupOptions: { input: { main: resolve(root, server.entry) } },\n },\n },\n },\n builder: {\n // One plugin instance for both builds, so the server build sees\n // the document captured from the client build.\n sharedPlugins: true,\n async buildApp(builder) {\n await builder.build(builder.environments['client']);\n await builder.build(builder.environments['ssr']);\n },\n },\n };\n },\n // The server bundle renders around the built document, so take it from\n // the client build's own output.\n writeBundle(_options, bundle) {\n if (this.environment.name === 'client') {\n const document = bundle[normalizePath(relative(root, indexHtml()))];\n if (document?.type === 'asset') {\n builtTemplate = String(document.source);\n }\n }\n },\n transform: {\n filter: { code: 'ANALOG_SERVER_MANIFEST' },\n handler(code, id) {\n if (!MANIFEST_PLACEHOLDER.test(code)) {\n return undefined;\n }\n manifestId = id;\n return code.replace(\n MANIFEST_PLACEHOLDER,\n `ANALOG_SERVER_MANIFEST = ${serverManifest()}`,\n );\n },\n },\n configureServer(viteServer) {\n (globalThis as Record<symbol, unknown>)[DEV_TEMPLATE] = (url: string) =>\n viteServer.transformIndexHtml(url, readFileSync(indexHtml(), 'utf-8'));\n\n // New or removed page endpoints and server functions change the manifest.\n const invalidateManifest = (file: string) => {\n const graph = viteServer.environments['ssr'].moduleGraph;\n const mod = manifestId && graph.getModuleById(manifestId);\n if (file.endsWith('.server.ts') && mod) {\n graph.invalidateModule(mod);\n }\n };\n viteServer.watcher.on('add', invalidateManifest);\n viteServer.watcher.on('unlink', invalidateManifest);\n\n return () => {\n removeHtmlMiddlewares(viteServer.middlewares);\n viteServer.middlewares.use(\n devMiddleware(viteServer, resolve(root, server.entry)),\n );\n };\n },\n };\n\n function requireBuiltTemplate(): string {\n if (builtTemplate === undefined) {\n throw new Error(\n `[@analogjs/platform] The client build didn't emit ${relative(root, indexHtml())}, which the server renders around.`,\n );\n }\n return builtTemplate;\n }\n\n /**\n * The manifest object literal: the template, and lazy imports of the SSR\n * renderer, the server config, every server function module, and page\n * endpoints keyed by route.\n */\n function serverManifest(): string {\n const src = `${root}/src`;\n const lazy = (file: string) => `() => import(${JSON.stringify(file)})`;\n const appConfig = [\n `${src}/app/app.config.server.ts`,\n `${src}/app.config.server.ts`,\n ].find((file) => existsSync(file));\n const discovery = {\n workspaceRoot,\n sourceRoot: 'src',\n rootDir: rootDir(),\n };\n const pageEndpoints = getPageEndpoints({\n ...discovery,\n additionalPagesDirs: options.additionalPagesDirs,\n }).map(\n ({ file, route }) =>\n `${JSON.stringify(`/${apiPrefix}/_analog${route}`)}: ${lazy(normalizePath(file))}`,\n );\n const serverFnModules = getServerFnHandlers(discovery).map(({ file }) =>\n lazy(file),\n );\n const template = isBuild\n ? `async () => ${JSON.stringify(requireBuiltTemplate())}`\n : `(url) => globalThis[Symbol.for('@analogjs/platform/dev-template')](url)`;\n\n return `{\n apiPrefix: ${JSON.stringify(apiPrefix)},\n template: ${template},\n render: () => import(${JSON.stringify(normalizePath(resolve(root, options.entryServer ?? 'src/main.server.ts')))}).then((m) => m.default),\n config: ${\n appConfig\n ? `() => import(${JSON.stringify(appConfig)}).then((m) => m.config)`\n : `async () => ({ providers: [] })`\n },\n serverFnModules: [${serverFnModules.join(', ')}],\n pageEndpoints: {${pageEndpoints.join(', ')}},\n}`;\n }\n}\n\n/**\n * Hands every request Vite doesn't serve to the entry's `fetch`. The handler is\n * recreated when the server module graph changes (ssrLoadModule returns a new\n * module), and the previous entry's `close()` is called.\n */\nfunction devMiddleware(\n viteServer: ViteDevServer,\n entry: string,\n): Connect.NextHandleFunction {\n let current: { entry: ServerEntry; handle: NodeHttp1Handler } | undefined;\n\n async function getHandler(): Promise<NodeHttp1Handler> {\n const loaded = (await viteServer.ssrLoadModule(entry)) as ServerEntry;\n if (current?.entry !== loaded) {\n const previous = current?.entry.default;\n current = { entry: loaded, handle: toHandler(loaded) };\n void Promise.resolve()\n .then(() => previous?.close?.())\n .catch(() => undefined);\n }\n return current.handle;\n }\n\n return (req, res, next) => {\n getHandler()\n .then((handle) => handle(req, res))\n .catch((error: Error) => {\n viteServer.ssrFixStacktrace(error);\n next(error);\n });\n };\n}\n\n/** A Node handler around the `fetch` of a Fetchable entry (https://fetchable.org). */\nfunction toHandler(entry: ServerEntry): NodeHttp1Handler {\n const fetchable = entry.default;\n const handleRequest = fetchable?.fetch;\n if (typeof handleRequest !== 'function') {\n throw new Error(\n '[@analogjs/platform] The server entry must be a Fetchable module: a default export with `fetch(request)`. `createApp()` entries are no longer supported; see https://analogjs.org/docs/features/server/custom-server.',\n );\n }\n // Connect middleware is typed with the HTTP/1 request and response.\n return toNodeHandler((request) =>\n handleRequest.call(fetchable, request),\n ) as NodeHttp1Handler;\n}\n\nfunction removeHtmlMiddlewares(middlewares: Connect.Server): void {\n middlewares.stack = middlewares.stack.filter(\n (layer) =>\n !HTML_MIDDLEWARES.includes(\n (layer.handle as { name?: string }).name ?? '',\n ),\n );\n}\n"],"mappings":";;;;;;;AAeA,IAAM,uBAAuB;AAC7B,IAAM,eAAe,OAAO,IAAI,iCAAiC;AACjE,IAAM,mBAAmB;CACvB;CACA;CACA;CACA;AACF;AACA,IAAM,gBAAgB,CAAC,cAAc,6BAA6B;;;;;;;AAelE,SAAgB,aACd,QACA,UAAmB,CAAC,GACZ;CACR,MAAM,gBACJ,QAAQ,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI;CAC3E,MAAM,YAAY,QAAQ,aAAa;CACvC,IAAI,OAAO,QAAQ,IAAI;CACvB,IAAI,UAAU;CACd,IAAI;CACJ,IAAI;CAEJ,MAAM,gBAAgB,SAAS,eAAe,IAAI,KAAK;CACvD,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