@analogjs/platform 3.0.0-beta.3 → 3.0.0-beta.30

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 (62) hide show
  1. package/package.json +12 -8
  2. package/src/lib/content-plugin.js +12 -3
  3. package/src/lib/content-plugin.js.map +1 -1
  4. package/src/lib/deps-plugin.d.ts +1 -1
  5. package/src/lib/deps-plugin.js +10 -6
  6. package/src/lib/deps-plugin.js.map +1 -1
  7. package/src/lib/get-page-endpoints.d.ts +25 -0
  8. package/src/lib/get-page-endpoints.js +29 -0
  9. package/src/lib/get-page-endpoints.js.map +1 -0
  10. package/src/lib/nitro/analog-nitro-plugin.js +10 -12
  11. package/src/lib/nitro/analog-nitro-plugin.js.map +1 -1
  12. package/src/lib/nitro/get-page-handlers.d.ts +4 -19
  13. package/src/lib/nitro/get-page-handlers.js +9 -26
  14. package/src/lib/nitro/get-page-handlers.js.map +1 -1
  15. package/src/lib/nx-plugin/executors.json +0 -7
  16. package/src/lib/nx-plugin/src/generators/app/compat.d.ts +2 -1
  17. package/src/lib/nx-plugin/src/generators/app/compat.js +4 -1
  18. package/src/lib/nx-plugin/src/generators/app/compat.js.map +1 -1
  19. package/src/lib/nx-plugin/src/generators/app/generator.js +7 -2
  20. package/src/lib/nx-plugin/src/generators/app/generator.js.map +1 -1
  21. package/src/lib/nx-plugin/src/generators/app/lib/add-tailwind-helpers.js +2 -2
  22. package/src/lib/nx-plugin/src/generators/app/lib/add-tailwind-helpers.js.map +1 -1
  23. package/src/lib/nx-plugin/src/generators/app/versions/minimum-supported-versions.d.ts +3 -1
  24. package/src/lib/nx-plugin/src/generators/app/versions/minimum-supported-versions.js +5 -1
  25. package/src/lib/nx-plugin/src/generators/app/versions/minimum-supported-versions.js.map +1 -1
  26. package/src/lib/nx-plugin/src/generators/init/compat.d.ts +2 -1
  27. package/src/lib/nx-plugin/src/generators/init/compat.js +4 -1
  28. package/src/lib/nx-plugin/src/generators/init/compat.js.map +1 -1
  29. package/src/lib/nx-plugin/src/generators/init/lib/add-analog-dependencies.js +2 -2
  30. package/src/lib/nx-plugin/src/generators/init/lib/add-analog-dependencies.js.map +1 -1
  31. package/src/lib/nx-plugin/src/generators/page/compat.d.ts +2 -1
  32. package/src/lib/nx-plugin/src/generators/page/compat.js +4 -1
  33. package/src/lib/nx-plugin/src/generators/page/compat.js.map +1 -1
  34. package/src/lib/nx-plugin/src/generators/preset/__snapshots__/generator.spec.ts.snap +4 -0
  35. package/src/lib/nx-plugin/src/generators/preset/generator.js +5 -2
  36. package/src/lib/nx-plugin/src/generators/preset/generator.js.map +1 -1
  37. package/src/lib/nx-plugin/src/utils/versions/dev-dependencies.d.ts +2 -2
  38. package/src/lib/nx-plugin/src/utils/versions/dev-dependencies.js +7 -3
  39. package/src/lib/nx-plugin/src/utils/versions/dev-dependencies.js.map +1 -1
  40. package/src/lib/nx-plugin/src/utils/versions/versions.d.ts +9 -6
  41. package/src/lib/nx-plugin/src/utils/versions/versions.js +13 -7
  42. package/src/lib/nx-plugin/src/utils/versions/versions.js.map +1 -1
  43. package/src/lib/options.d.ts +16 -0
  44. package/src/lib/platform-plugin.js +2 -0
  45. package/src/lib/platform-plugin.js.map +1 -1
  46. package/src/lib/route-idiom-diagnostics.js +23 -8
  47. package/src/lib/route-idiom-diagnostics.js.map +1 -1
  48. package/src/lib/router-plugin.js +1 -1
  49. package/src/lib/router-plugin.js.map +1 -1
  50. package/src/lib/server-plugin.d.ts +9 -0
  51. package/src/lib/server-plugin.js +170 -0
  52. package/src/lib/server-plugin.js.map +1 -0
  53. package/src/lib/typed-routes-plugin.js +1 -1
  54. package/src/lib/typed-routes-plugin.js.map +1 -1
  55. package/src/lib/nx-plugin/src/executors/vite-dev-server/compat.d.ts +0 -3
  56. package/src/lib/nx-plugin/src/executors/vite-dev-server/compat.js +0 -7
  57. package/src/lib/nx-plugin/src/executors/vite-dev-server/compat.js.map +0 -1
  58. package/src/lib/nx-plugin/src/executors/vite-dev-server/schema.d.ts +0 -1
  59. package/src/lib/nx-plugin/src/executors/vite-dev-server/schema.json +0 -101
  60. package/src/lib/nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.d.ts +0 -2
  61. package/src/lib/nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.js +0 -6
  62. package/src/lib/nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.js.map +0 -1
@@ -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 ];\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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 ...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')`;\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,aA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AK,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,uB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AAQ,KAAK,KAAK,SAAS;EACzB,WAAW,CAAC,CACT,MAAM,WAAW,OAAO,KAAK,GAAG,CAAC,CAAC,CAClC,OAAO,UAAiB;GACvB,WAAW,iBAAiB,KAAK;GACjC,KAAK,KAAK;EACZ,CAAC;CACL;AACF;;AAGA,SAAS,UAAU,OAAsC;CACvD,MAAM,YAAY,MAAM;CACxB,MAAM,gBAAgB,WAAW;CACjC,IAAI,OAAO,kBAAkB,YAC3B,MAAM,IAAI,MACR,uNACF;CAGF,OAAO,eAAe,YACpB,cAAc,KAAK,WAAW,OAAO,CACvC;AACF;AAEA,SAAS,sBAAsB,aAAmC;CAChE,YAAY,QAAQ,YAAY,MAAM,QACnC,UACC,CAAC,iBAAiB,SACf,MAAM,OAA6B,QAAQ,EAC9C,CACJ;AACF"}
@@ -65,7 +65,7 @@ function typedRoutes(options = {}) {
65
65
  generate();
66
66
  },
67
67
  configResolved(config) {
68
- const compiler = config.plugins.find((plugin) => plugin.name === "@analogjs/vite-plugin-angular" || plugin.name === "@analogjs/vite-plugin-angular-fast-compile" || plugin.name === "@analogjs/vite-plugin-angular-compilation-api");
68
+ const compiler = config.plugins.find((plugin) => plugin.name === "@analogjs/vite-plugin-angular" || plugin.name === "@analogjs/vite-plugin-angular-fast-compile" || plugin.name === "@analogjs/vite-plugin-angular-compilation-api" || plugin.name === "@analogjs/vite-plugin-angular-ngp");
69
69
  getTsConfigPath = compiler?.api?.getTsConfigPath;
70
70
  if (compiler && !getTsConfigPath) throw new Error("[analog] Typed routing requires a matching @analogjs/vite-plugin-angular version to verify the application tsconfig.");
71
71
  verifyTypeInclusion();
@@ -1 +1 @@
1
- {"version":3,"file":"typed-routes-plugin.js","names":[],"sources":["../../../src/lib/typed-routes-plugin.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport { readConfiguration } from '@angular/compiler-cli';\nimport { parseSync } from 'oxc-parser';\nimport { normalizePath, type Plugin } from 'vite';\n\nimport {\n createRouteFileDiscovery,\n type RouteFileDiscovery,\n} from './route-file-discovery.js';\nimport {\n generateRouteManifest,\n generateRouteTableDeclaration,\n} from './route-manifest.js';\n\nexport interface TypedRoutingOptions {\n /** Generated declaration path (.d.ts), relative to the app root. */\n outFile?: string;\n /** Fail builds when a checked-in route table is stale. Defaults to true. */\n verifyOnBuild?: boolean;\n}\n\nexport interface TypedRoutesPluginOptions extends TypedRoutingOptions {\n workspaceRoot?: string;\n additionalPagesDirs?: string[];\n additionalContentDirs?: string[];\n}\n\nexport function typedRoutes(options: TypedRoutesPluginOptions = {}): Plugin {\n const workspaceRoot = normalizePath(options.workspaceRoot ?? process.cwd());\n const outFile = options.outFile ?? 'src/routeTree.gen.d.ts';\n if (!outFile.endsWith('.d.ts')) {\n throw new Error(\n '[analog] Typed routing outFile must end in .d.ts. Include this declaration in your application tsconfig.',\n );\n }\n let root: string;\n let command: 'build' | 'serve';\n let discovery: RouteFileDiscovery;\n\n let getTsConfigPath: (() => string) | undefined;\n\n function verifyTypeInclusion(): void {\n if (!getTsConfigPath) return;\n const tsconfig = getTsConfigPath();\n const { rootNames, errors } = readConfiguration(tsconfig);\n if (errors.length) {\n throw new Error(\n `[analog] Cannot verify typed routing: unable to read ${tsconfig}.`,\n );\n }\n const outputPath = normalizePath(resolve(root, outFile));\n if (\n !rootNames.some((file) => normalizePath(resolve(file)) === outputPath)\n ) {\n const declaration = normalizePath(\n relative(dirname(tsconfig), outputPath),\n );\n throw new Error(\n `[analog] Typed route declaration is not included in ${tsconfig}. Add \"${declaration}\" to its \"files\" or \"include\" list so typed routing is available to the compiler and editor.`,\n );\n }\n }\n\n function generate(): void {\n const manifest = generateRouteManifest(\n [...discovery.getRouteFiles(), ...discovery.getContentFiles()],\n (filename) => (discovery.isAppLocal(filename) ? 0 : 1),\n );\n const collisions = manifest.collisions.filter(\n (collision) => collision.samePriority,\n );\n if (command === 'build' && collisions.length) {\n throw new Error(\n `[analog] Route collisions detected: ${collisions.map((c) => `${c.fullPath}: ${c.keptFile}, ${c.droppedFile}`).join('; ')}`,\n );\n }\n const outputPath = join(root, outFile);\n const output = generateRouteTableDeclaration(manifest, (filename) => {\n const pageFile = [\n join(root, filename),\n join(workspaceRoot, filename),\n filename,\n ].find((file) => existsSync(file));\n if (!pageFile) return undefined;\n const serverFile = pageFile.replace(/\\.page\\.ts$/, '.server.ts');\n return {\n routeMeta: hasNamedExport(pageFile, 'routeMeta')\n ? toImportSpecifier(dirname(outputPath), pageFile)\n : undefined,\n load:\n serverFile !== pageFile &&\n existsSync(serverFile) &&\n hasNamedExport(serverFile, 'load')\n ? toImportSpecifier(dirname(outputPath), serverFile)\n : undefined,\n };\n });\n const exists = existsSync(outputPath);\n const current = exists ? readFileSync(outputPath, 'utf8') : '';\n if (current !== output && !sameDeclarations(current, output)) {\n if (exists && command === 'build' && (options.verifyOnBuild ?? true)) {\n throw new Error(\n `[analog] Stale route file: ${outFile}. Run the dev server to regenerate it before building.`,\n );\n }\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, output);\n }\n }\n\n return {\n name: 'analog-typed-routes',\n config(config, env) {\n command = env.command;\n root = normalizePath(resolve(workspaceRoot, config.root ?? '.'));\n discovery = createRouteFileDiscovery({\n root,\n workspaceRoot,\n additionalPagesDirs: options.additionalPagesDirs ?? [],\n additionalContentDirs: options.additionalContentDirs ?? [],\n });\n // Generate before Angular reads the application tsconfig.\n generate();\n },\n configResolved(config) {\n const compiler = config.plugins.find(\n (plugin) =>\n plugin.name === '@analogjs/vite-plugin-angular' ||\n plugin.name === '@analogjs/vite-plugin-angular-fast-compile' ||\n plugin.name === '@analogjs/vite-plugin-angular-compilation-api',\n );\n getTsConfigPath = compiler?.api?.getTsConfigPath;\n if (compiler && !getTsConfigPath) {\n throw new Error(\n '[analog] Typed routing requires a matching @analogjs/vite-plugin-angular version to verify the application tsconfig.',\n );\n }\n verifyTypeInclusion();\n },\n buildStart() {\n discovery.reset();\n generate();\n verifyTypeInclusion();\n },\n configureServer(server) {\n server.watcher.add(join(root, outFile));\n for (const event of ['add', 'change', 'unlink'] as const) {\n server.watcher.on(event, (path) => {\n if (!discovery.getDiscoveredFileKind(path)) return;\n discovery.updateDiscoveredFile(path, event);\n generate();\n });\n }\n },\n };\n}\n\nfunction toImportSpecifier(fromDir: string, file: string): string {\n const specifier = normalizePath(relative(fromDir, file)).replace(/\\.ts$/, '');\n return specifier.startsWith('.') ? specifier : `./${specifier}`;\n}\n\nfunction hasNamedExport(file: string, name: string): boolean {\n const source = readFileSync(file, 'utf8');\n if (!source.includes(name)) return false;\n const { program, errors } = parseSync(file, source);\n if (errors.length) return false;\n return program.body.some((statement) => {\n if (\n statement.type !== 'ExportNamedDeclaration' ||\n statement.exportKind === 'type'\n ) {\n return false;\n }\n const declaration = statement.declaration;\n if (declaration?.type === 'VariableDeclaration') {\n return declaration.declarations.some(\n (item) => item.id.type === 'Identifier' && item.id.name === name,\n );\n }\n if (declaration?.type === 'FunctionDeclaration') {\n return declaration.id?.name === name;\n }\n return statement.specifiers.some(\n (specifier) =>\n specifier.exportKind !== 'type' &&\n (specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value) === name,\n );\n });\n}\n\nfunction sameDeclarations(current: string, output: string): boolean {\n const left = parseSync('routeTree.gen.d.ts', current);\n const right = parseSync('routeTree.gen.d.ts', output);\n if (left.errors.length || right.errors.length) return false;\n const withoutFormatting = (key: string, value: unknown) =>\n key === 'start' || key === 'end' || key === 'raw' ? undefined : value;\n return (\n JSON.stringify(left.program, withoutFormatting) ===\n JSON.stringify(right.program, withoutFormatting)\n );\n}\n"],"mappings":";;;;;;;;AA4BA,SAAgB,YAAY,UAAoC,CAAC,GAAW;CAC1E,MAAM,gBAAgB,cAAc,QAAQ,iBAAiB,QAAQ,IAAI,CAAC;CAC1E,MAAM,UAAU,QAAQ,WAAW;CACnC,IAAI,CAAC,QAAQ,SAAS,OAAO,GAC3B,MAAM,IAAI,MAC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":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport { readConfiguration } from '@angular/compiler-cli';\nimport { parseSync } from 'oxc-parser';\nimport { normalizePath, type Plugin } from 'vite';\n\nimport {\n createRouteFileDiscovery,\n type RouteFileDiscovery,\n} from './route-file-discovery.js';\nimport {\n generateRouteManifest,\n generateRouteTableDeclaration,\n} from './route-manifest.js';\n\nexport interface TypedRoutingOptions {\n /** Generated declaration path (.d.ts), relative to the app root. */\n outFile?: string;\n /** Fail builds when a checked-in route table is stale. Defaults to true. */\n verifyOnBuild?: boolean;\n}\n\nexport interface TypedRoutesPluginOptions extends TypedRoutingOptions {\n workspaceRoot?: string;\n additionalPagesDirs?: string[];\n additionalContentDirs?: string[];\n}\n\nexport function typedRoutes(options: TypedRoutesPluginOptions = {}): Plugin {\n const workspaceRoot = normalizePath(options.workspaceRoot ?? process.cwd());\n const outFile = options.outFile ?? 'src/routeTree.gen.d.ts';\n if (!outFile.endsWith('.d.ts')) {\n throw new Error(\n '[analog] Typed routing outFile must end in .d.ts. Include this declaration in your application tsconfig.',\n );\n }\n let root: string;\n let command: 'build' | 'serve';\n let discovery: RouteFileDiscovery;\n\n let getTsConfigPath: (() => string) | undefined;\n\n function verifyTypeInclusion(): void {\n if (!getTsConfigPath) return;\n const tsconfig = getTsConfigPath();\n const { rootNames, errors } = readConfiguration(tsconfig);\n if (errors.length) {\n throw new Error(\n `[analog] Cannot verify typed routing: unable to read ${tsconfig}.`,\n );\n }\n const outputPath = normalizePath(resolve(root, outFile));\n if (\n !rootNames.some((file) => normalizePath(resolve(file)) === outputPath)\n ) {\n const declaration = normalizePath(\n relative(dirname(tsconfig), outputPath),\n );\n throw new Error(\n `[analog] Typed route declaration is not included in ${tsconfig}. Add \"${declaration}\" to its \"files\" or \"include\" list so typed routing is available to the compiler and editor.`,\n );\n }\n }\n\n function generate(): void {\n const manifest = generateRouteManifest(\n [...discovery.getRouteFiles(), ...discovery.getContentFiles()],\n (filename) => (discovery.isAppLocal(filename) ? 0 : 1),\n );\n const collisions = manifest.collisions.filter(\n (collision) => collision.samePriority,\n );\n if (command === 'build' && collisions.length) {\n throw new Error(\n `[analog] Route collisions detected: ${collisions.map((c) => `${c.fullPath}: ${c.keptFile}, ${c.droppedFile}`).join('; ')}`,\n );\n }\n const outputPath = join(root, outFile);\n const output = generateRouteTableDeclaration(manifest, (filename) => {\n const pageFile = [\n join(root, filename),\n join(workspaceRoot, filename),\n filename,\n ].find((file) => existsSync(file));\n if (!pageFile) return undefined;\n const serverFile = pageFile.replace(/\\.page\\.ts$/, '.server.ts');\n return {\n routeMeta: hasNamedExport(pageFile, 'routeMeta')\n ? toImportSpecifier(dirname(outputPath), pageFile)\n : undefined,\n load:\n serverFile !== pageFile &&\n existsSync(serverFile) &&\n hasNamedExport(serverFile, 'load')\n ? toImportSpecifier(dirname(outputPath), serverFile)\n : undefined,\n };\n });\n const exists = existsSync(outputPath);\n const current = exists ? readFileSync(outputPath, 'utf8') : '';\n if (current !== output && !sameDeclarations(current, output)) {\n if (exists && command === 'build' && (options.verifyOnBuild ?? true)) {\n throw new Error(\n `[analog] Stale route file: ${outFile}. Run the dev server to regenerate it before building.`,\n );\n }\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, output);\n }\n }\n\n return {\n name: 'analog-typed-routes',\n config(config, env) {\n command = env.command;\n root = normalizePath(resolve(workspaceRoot, config.root ?? '.'));\n discovery = createRouteFileDiscovery({\n root,\n workspaceRoot,\n additionalPagesDirs: options.additionalPagesDirs ?? [],\n additionalContentDirs: options.additionalContentDirs ?? [],\n });\n // Generate before Angular reads the application tsconfig.\n generate();\n },\n configResolved(config) {\n const compiler = config.plugins.find(\n (plugin) =>\n plugin.name === '@analogjs/vite-plugin-angular' ||\n plugin.name === '@analogjs/vite-plugin-angular-fast-compile' ||\n plugin.name === '@analogjs/vite-plugin-angular-compilation-api' ||\n plugin.name === '@analogjs/vite-plugin-angular-ngp',\n );\n getTsConfigPath = compiler?.api?.getTsConfigPath;\n if (compiler && !getTsConfigPath) {\n throw new Error(\n '[analog] Typed routing requires a matching @analogjs/vite-plugin-angular version to verify the application tsconfig.',\n );\n }\n verifyTypeInclusion();\n },\n buildStart() {\n discovery.reset();\n generate();\n verifyTypeInclusion();\n },\n configureServer(server) {\n server.watcher.add(join(root, outFile));\n for (const event of ['add', 'change', 'unlink'] as const) {\n server.watcher.on(event, (path) => {\n if (!discovery.getDiscoveredFileKind(path)) return;\n discovery.updateDiscoveredFile(path, event);\n generate();\n });\n }\n },\n };\n}\n\nfunction toImportSpecifier(fromDir: string, file: string): string {\n const specifier = normalizePath(relative(fromDir, file)).replace(/\\.ts$/, '');\n return specifier.startsWith('.') ? specifier : `./${specifier}`;\n}\n\nfunction hasNamedExport(file: string, name: string): boolean {\n const source = readFileSync(file, 'utf8');\n if (!source.includes(name)) return false;\n const { program, errors } = parseSync(file, source);\n if (errors.length) return false;\n return program.body.some((statement) => {\n if (\n statement.type !== 'ExportNamedDeclaration' ||\n statement.exportKind === 'type'\n ) {\n return false;\n }\n const declaration = statement.declaration;\n if (declaration?.type === 'VariableDeclaration') {\n return declaration.declarations.some(\n (item) => item.id.type === 'Identifier' && item.id.name === name,\n );\n }\n if (declaration?.type === 'FunctionDeclaration') {\n return declaration.id?.name === name;\n }\n return statement.specifiers.some(\n (specifier) =>\n specifier.exportKind !== 'type' &&\n (specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value) === name,\n );\n });\n}\n\nfunction sameDeclarations(current: string, output: string): boolean {\n const left = parseSync('routeTree.gen.d.ts', current);\n const right = parseSync('routeTree.gen.d.ts', output);\n if (left.errors.length || right.errors.length) return false;\n const withoutFormatting = (key: string, value: unknown) =>\n key === 'start' || key === 'end' || key === 'raw' ? undefined : value;\n return (\n JSON.stringify(left.program, withoutFormatting) ===\n JSON.stringify(right.program, withoutFormatting)\n );\n}\n"],"mappings":";;;;;;;;AA4BA,SAAgB,Y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,QAAQ,QAAQ,KAAA,IAAY;CAClE,OACE,KAAK,UAAU,KAAK,SAAS,iBAAiB,MAC9C,KAAK,UAAU,MAAM,SAAS,iBAAiB;AAEnD"}
@@ -1,3 +0,0 @@
1
- import { convertNxExecutor } from "@nx/devkit";
2
- declare const compat: ReturnType<typeof convertNxExecutor>;
3
- export default compat;
@@ -1,7 +0,0 @@
1
- const require_src_executors_vite_dev_server_vite_dev_server_impl = require("./vite-dev-server.impl.js");
2
- //#region packages/nx-plugin/src/executors/vite-dev-server/compat.ts
3
- var compat = (0, require("@nx/devkit").convertNxExecutor)(require_src_executors_vite_dev_server_vite_dev_server_impl);
4
- //#endregion
5
- module.exports = compat;
6
-
7
- //# sourceMappingURL=compat.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"compat.js","names":[],"sources":["../../../../../../../../nx-plugin/src/executors/vite-dev-server/compat.ts"],"sourcesContent":["import { convertNxExecutor } from '@nx/devkit';\n\nimport viteDevServerExecutor from './vite-dev-server.impl';\n\nconst compat: ReturnType<typeof convertNxExecutor> = convertNxExecutor(\n viteDevServerExecutor,\n);\nexport default compat;\n"],"mappings":";;AAIA,IAAM,UAAA,uBAA+C,CAAA,CAAA,kBAAA,CACnD,0DACF"}
@@ -1 +0,0 @@
1
- export type { ViteDevServerExecutorOptions } from '@nx/vite/executors';
@@ -1,101 +0,0 @@
1
- {
2
- "version": 2,
3
- "outputCapture": "direct-nodejs",
4
- "title": "Vite Dev Server",
5
- "cli": "nx",
6
- "description": "Starts a dev server using Vite.",
7
- "type": "object",
8
- "presets": [
9
- {
10
- "name": "Default minimum setup",
11
- "keys": ["buildTarget"]
12
- },
13
- {
14
- "name": "Using a Different Port",
15
- "keys": ["buildTarget", "port"]
16
- }
17
- ],
18
- "properties": {
19
- "buildTarget": {
20
- "type": "string",
21
- "description": "Target which builds the application. Only used to retrieve the configuration as the dev-server does not build the code.",
22
- "x-priority": "important"
23
- },
24
- "buildLibsFromSource": {
25
- "type": "boolean",
26
- "description": "Read buildable libraries from source instead of building them separately.",
27
- "default": true
28
- },
29
- "proxyConfig": {
30
- "type": "string",
31
- "description": "Path to the proxy configuration file.",
32
- "x-completion-type": "file"
33
- },
34
- "port": {
35
- "type": "number",
36
- "description": "Port to listen on.",
37
- "x-priority": "important"
38
- },
39
- "host": {
40
- "description": "Specify which IP addresses the server should listen on.",
41
- "oneOf": [
42
- {
43
- "type": "boolean"
44
- },
45
- {
46
- "type": "string"
47
- }
48
- ]
49
- },
50
- "https": {
51
- "oneOf": [
52
- {
53
- "type": "boolean"
54
- },
55
- {
56
- "type": "object"
57
- }
58
- ],
59
- "description": "Serve using HTTPS. https://vitejs.dev/config/server-options.html#server-https"
60
- },
61
- "hmr": {
62
- "description": "Enable hot module replacement. For more options, use the 'hmr' option in the Vite configuration file.",
63
- "type": "boolean"
64
- },
65
- "open": {
66
- "description": "Automatically open the app in the browser on server start. When the value is a string, it will be used as the URL's pathname.",
67
- "oneOf": [
68
- {
69
- "type": "boolean"
70
- },
71
- {
72
- "type": "string"
73
- }
74
- ]
75
- },
76
- "cors": {
77
- "description": "Configure CORS for the dev server.",
78
- "type": "boolean"
79
- },
80
- "logLevel": {
81
- "type": "string",
82
- "description": "Adjust console output verbosity.",
83
- "enum": ["info", "warn", "error", "silent"]
84
- },
85
- "mode": {
86
- "type": "string",
87
- "description": "Mode to run the server in."
88
- },
89
- "clearScreen": {
90
- "description": "Set to false to prevent Vite from clearing the terminal screen when logging certain messages.",
91
- "type": "boolean"
92
- },
93
- "force": {
94
- "description": "Force the optimizer to ignore the cache and re-bundle",
95
- "type": "boolean"
96
- }
97
- },
98
- "definitions": {},
99
- "required": ["buildTarget"],
100
- "examplesFile": "../../../docs/dev-server-examples.md"
101
- }
@@ -1,2 +0,0 @@
1
- import { viteDevServerExecutor } from "@nx/vite/executors";
2
- export default viteDevServerExecutor;
@@ -1,6 +0,0 @@
1
- //#region packages/nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.ts
2
- var vite_dev_server_impl_default = require("@nx/vite/executors").viteDevServerExecutor;
3
- //#endregion
4
- module.exports = vite_dev_server_impl_default;
5
-
6
- //# sourceMappingURL=vite-dev-server.impl.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"vite-dev-server.impl.js","names":[],"sources":["../../../../../../../../nx-plugin/src/executors/vite-dev-server/vite-dev-server.impl.ts"],"sourcesContent":["import { viteDevServerExecutor } from '@nx/vite/executors';\n\nexport default viteDevServerExecutor;\n"],"mappings":";AAEA,IAAA,2DAAe,CAAA,CAAA"}