@analogjs/platform 3.0.0-alpha.91 → 3.0.0-alpha.93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/migrations/migrate-to-separated-plugins/migrate-to-separated-plugins.d.ts +2 -0
- package/migrations/migrate-to-separated-plugins/migrate-to-separated-plugins.js +203 -0
- package/migrations/migrate-to-separated-plugins/migrate-to-separated-plugins.js.map +1 -0
- package/package.json +11 -7
- package/src/lib/clear-client-page-endpoint.js +1 -0
- package/src/lib/clear-client-page-endpoint.js.map +1 -1
- package/src/lib/deps-plugin.js +17 -6
- package/src/lib/deps-plugin.js.map +1 -1
- package/src/lib/nitro/analog-nitro-plugin.js +102 -45
- package/src/lib/nitro/analog-nitro-plugin.js.map +1 -1
- package/src/lib/nitro/get-server-fn-handlers.d.ts +29 -0
- package/src/lib/nitro/get-server-fn-handlers.js +66 -0
- package/src/lib/nitro/get-server-fn-handlers.js.map +1 -0
- package/src/lib/nitro/server-fn-endpoints.d.ts +41 -0
- package/src/lib/nitro/server-fn-endpoints.js +57 -0
- package/src/lib/nitro/server-fn-endpoints.js.map +1 -0
- package/src/lib/nx-plugin/src/generators/app/files/template-angular/src/server/routes/api/v1/hello.ts__template__ +2 -2
- package/src/lib/nx-plugin/src/generators/app/files/template-angular/vite.config.ts__template__ +4 -0
- package/src/lib/nx-plugin/src/generators/app/generator.js +5 -0
- package/src/lib/nx-plugin/src/generators/app/generator.js.map +1 -1
- package/src/lib/nx-plugin/src/generators/app/versions/nx_18_X/versions.d.ts +8 -6
- package/src/lib/nx-plugin/src/generators/app/versions/nx_18_X/versions.js.map +1 -1
- package/src/lib/nx-plugin/src/generators/init/lib/update-git-ignore.js +4 -7
- package/src/lib/nx-plugin/src/generators/init/lib/update-git-ignore.js.map +1 -1
- package/src/lib/nx-plugin/src/generators/preset/__snapshots__/generator.spec.ts.snap +3 -1
- package/src/lib/nx-plugin/src/utils/versions/ng_19_X/versions.d.ts +6 -6
- package/src/lib/nx-plugin/src/utils/versions/ng_19_X/versions.js +6 -6
- package/src/lib/nx-plugin/src/utils/versions/ng_19_X/versions.js.map +1 -1
- package/src/lib/options.d.ts +17 -1
- package/src/lib/platform-plugin.js +34 -3
- package/src/lib/platform-plugin.js.map +1 -1
- package/src/lib/ssr/defer-streaming-plugin.d.ts +3 -35
- package/src/lib/ssr/defer-streaming-plugin.js +103 -0
- package/src/lib/ssr/defer-streaming-plugin.js.map +1 -0
- package/src/lib/ssr/ssr-build-plugin.d.ts +1 -1
- package/src/lib/ssr/ssr-build-plugin.js.map +1 -1
- package/src/lib/utils/rolldown.js +1 -1
- package/src/server-mode-plugin.d.ts +1 -1
- package/src/server-mode-plugin.js +13 -1
- package/src/server-mode-plugin.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analog-nitro-plugin.js","names":[],"sources":["../../../../src/lib/nitro/analog-nitro-plugin.ts"],"sourcesContent":["import { existsSync, readFileSync, readdirSync, unlinkSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { basename, dirname, relative, resolve } from 'node:path';\nimport type { Nitro, NitroEventHandler, PrerenderRoute } from 'nitro/types';\nimport type { DevEnvironment, Plugin, UserConfig } from 'vite';\n\nimport type { Options } from '../options.js';\nimport { SERVER_MODE_ID } from '../../server-mode-plugin.js';\nimport type {\n PrerenderContentDir,\n PrerenderContentFile,\n PrerenderRouteConfig,\n PrerenderSitemapConfig,\n} from './types.js';\nimport { getPageHandlers } from './get-page-handlers.js';\nimport { pageEndpointsPlugin } from './page-endpoints-plugin.js';\nimport { getMatchingContentFilesWithFrontMatter } from './get-content-files.js';\nimport { buildSitemap } from './build-sitemap.js';\nimport { addPostRenderingHooks } from './post-rendering-hook.js';\nimport {\n expandRoutesWithLocales,\n createI18nPostRenderingHook,\n} from './i18n-prerender.js';\nimport { angularLinkerPlugin } from './angular-linker-plugin.js';\n\nconst SSR_ENTRY_VIRTUAL_ID = '\\0virtual:@analogjs/nitro/ssr-entry';\n\n/**\n * Angular packages that ship in partial-compilation form and must pass\n * through the linker before the SSR / nitro bundle can execute without\n * JIT. Wired into `ssr.optimizeDeps.rolldownOptions.plugins`.\n */\nconst ANGULAR_SSR_DEPS = [\n '@angular/compiler',\n '@angular/core',\n '@angular/common',\n '@angular/platform-browser',\n '@angular/platform-server',\n];\n\ninterface NitroPluginContext {\n workspaceRoot: string;\n rootDir: string;\n sourceRoot: string;\n}\n\ntype RouteSitemap =\n | PrerenderSitemapConfig\n | (() => PrerenderSitemapConfig)\n | undefined;\n\n/**\n * Analog's NitroModule. Plug it into the Vite plugin chain alongside\n * `nitro()` from `nitro/vite`; nitro/vite picks up the `.nitro` property\n * and runs `setup(nitro)` once the Nitro instance is ready.\n */\nexport function analogNitroPlugin(options: Options = {}): Plugin {\n const workspaceRoot =\n options.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd();\n const sourceRoot = 'src';\n const ssr = options.ssr ?? true;\n const apiPrefix = options.apiPrefix ?? 'api';\n\n let context: NitroPluginContext = {\n workspaceRoot,\n rootDir: '.',\n sourceRoot,\n };\n let ssrEntryMarkerPath = '';\n let userPublicDir: string | undefined;\n let isBuild = false;\n const ssrDepsReady = new WeakMap<DevEnvironment, Promise<void>>();\n // The document the client environment emitted for this build, captured in\n // `writeBundle` below. A build must render around this rather than the\n // source document: the source points at the unbundled entry, which only\n // resolves while Vite is serving.\n let builtIndexHtml: string | undefined;\n\n function waitForSsrDeps(environment: DevEnvironment): Promise<void> {\n let ready = ssrDepsReady.get(environment);\n if (!ready) {\n // Vite's subsequent init() calls return before the first run finishes.\n ready = Promise.resolve(environment.depsOptimizer?.init());\n ssrDepsReady.set(environment, ready);\n }\n return ready;\n }\n\n function refreshContext(viteRoot: string | undefined) {\n const root = viteRoot ?? process.cwd();\n context = {\n workspaceRoot,\n rootDir: relative(workspaceRoot, root) || '.',\n sourceRoot,\n };\n ssrEntryMarkerPath = resolve(\n context.workspaceRoot,\n context.rootDir,\n '.analog/__ssr-entry.mjs',\n );\n }\n\n function indexHtmlPath(): string {\n return resolve(\n context.workspaceRoot,\n context.rootDir,\n options.index ?? 'index.html',\n );\n }\n\n function readIndexHtml(): string {\n // Dev reads the source document so Vite can transform it and serve the\n // entry it points at.\n if (!isBuild) {\n const source = indexHtmlPath();\n return existsSync(source)\n ? readFileSync(source, 'utf-8')\n : '<!doctype html><html><body><div id=\"app\"></div></body></html>';\n }\n if (builtIndexHtml === undefined) {\n throw new Error(\n `[analog] The client build produced no ${basename(indexHtmlPath())}, ` +\n `so there is no document to server-render around. Rendering around ` +\n `the source document instead would ship markup pointing at the ` +\n `unbundled entry, which does not exist in a build.`,\n );\n }\n return builtIndexHtml;\n }\n\n function resolveEntryServer(): string {\n return (\n options.entryServer ??\n resolve(\n context.workspaceRoot,\n context.rootDir,\n `${sourceRoot}/main.server.ts`,\n )\n );\n }\n\n const plugin: Plugin & {\n nitro: { setup: (nitro: Nitro) => void | Promise<void> };\n } = {\n name: '@analogjs/nitro',\n enforce: 'pre',\n\n config(userConfig, configEnv) {\n refreshContext(userConfig.root);\n isBuild = configEnv?.command === 'build';\n\n // Capture the user's Vite `publicDir` so the nitro `setup()` hook can\n // register it as a Nitro `publicAssets` source. nitro/vite forces the\n // client environment's `build.copyPublicDir` to `false`\n // (vite.mjs:248), expecting Nitro to manage public assets — but\n // doesn't auto-add the user's `publicDir`. Without this, anything\n // under `src/public/` (e.g. `/assets/shipping.json`) 404s during SSR\n // and ofetch consumers parse the catch-all SSR HTML as JSON.\n if (userConfig.publicDir !== false) {\n userPublicDir = resolve(\n context.workspaceRoot,\n context.rootDir,\n (userConfig.publicDir as string | undefined) ?? 'public',\n );\n }\n\n // Bridge the legacy `BUILD_PRESET` env var that `@analogjs/vite-plugin-nitro`\n // accepted into Nitro v3's `NITRO_PRESET`, and auto-pick the matching\n // preset when the build runs inside a host's CI (each host sets its\n // own well-known env var). Mirrors the legacy plugin's behavior so\n // users upgrading don't need to change their CI configuration.\n if (!process.env['NITRO_PRESET']) {\n if (process.env['BUILD_PRESET']) {\n process.env['NITRO_PRESET'] = process.env['BUILD_PRESET'];\n } else if (process.env['VERCEL']) {\n process.env['NITRO_PRESET'] = 'vercel';\n } else if (process.env['NETLIFY']) {\n process.env['NITRO_PRESET'] = 'netlify';\n } else if (process.env['CF_PAGES']) {\n process.env['NITRO_PRESET'] = 'cloudflare-pages';\n }\n }\n\n const overrides: UserConfig = {\n // Vite 8 defaults `server.fs.allow` to `[searchForWorkspaceRoot(root)]`,\n // which should already cover the workspace root. In practice, nitro/vite's\n // env-runner loads its own `dev-entry.mjs` from a pnpm content-hash path\n // (`node_modules/.pnpm/nitro@.../...`) through Vite's ModuleRunner and\n // hits an `ERR_LOAD_URL`/\"Does the file exist?\" error unless an explicit\n // allow entry covers the same root. Whitelist the workspace root here so\n // users don't have to write the workaround in every vite.config.ts.\n server: {\n fs: {\n allow: [context.workspaceRoot],\n },\n },\n // nitro/vite defaults the client environment's input to\n // `renderer.template` (vite.mjs:240). We install our own renderer\n // handler and delete that template — Nitro's template-serving\n // renderer just returns the raw document — which leaves the client\n // environment with no input, and an environment without one is\n // skipped (vite.mjs:78). The build then emits no browser bundles at\n // all and the client never boots. Point it at the source document\n // ourselves.\n //\n // Declared ahead of `ssr` so it builds first: the SSR bundle inlines\n // the document it renders around, so the client output has to exist\n // by the time that bundle is built.\n environments: {\n client: {\n build: { rollupOptions: { input: indexHtmlPath() } },\n },\n } as UserConfig['environments'],\n };\n\n if (ssr) {\n // Two-pronged registration: `experimental.vite.services.ssr.entry`\n // is the documented hook, but nitro/vite's setupNitroContext also\n // accepts an `environments.ssr.build.rollupOptions.input` entry\n // (see node_modules/nitro/dist/vite.mjs:710-734). When `analog()`\n // and `nitro()` are invoked separately, the `services` slot on\n // `nitro()`'s pluginConfig is empty, so the rollupOptions.input\n // path is how we get our wrapper entry recognized.\n overrides.experimental = {\n vite: {\n services: {\n ssr: { entry: ssrEntryMarkerPath },\n },\n },\n };\n (overrides.environments as Record<string, unknown>)['ssr'] = {\n build: {\n outDir: resolve(\n context.workspaceRoot,\n 'dist',\n context.rootDir,\n 'ssr',\n ),\n rollupOptions: {\n input: { index: ssrEntryMarkerPath },\n },\n },\n optimizeDeps: {\n include: ANGULAR_SSR_DEPS,\n rolldownOptions: {\n plugins: [angularLinkerPlugin()],\n },\n },\n };\n }\n\n return overrides;\n },\n\n configureServer(server) {\n const environment = server.environments['ssr'];\n if (ssr && environment) {\n // Capture initialization before listen(); entry resolution propagates failures.\n void waitForSsrDeps(environment).catch(() => undefined);\n }\n },\n\n resolveId(id) {\n if (id === ssrEntryMarkerPath || id === SSR_ENTRY_VIRTUAL_ID) {\n if (ssr && !isBuild && this.environment.name === 'ssr') {\n return waitForSsrDeps(this.environment as DevEnvironment).then(\n () => SSR_ENTRY_VIRTUAL_ID,\n );\n }\n return SSR_ENTRY_VIRTUAL_ID;\n }\n return null;\n },\n\n load(id) {\n if (id !== SSR_ENTRY_VIRTUAL_ID) return null;\n return generateSsrEntryWrapper(resolveEntryServer(), readIndexHtml());\n },\n\n // Take the rendered-around document from the client environment's own\n // output rather than guessing where it landed. A guessed path can name a\n // leftover from an earlier build, which serves pages an application bundle\n // that no longer matches the markup around it.\n //\n // `writeBundle` rather than `generateBundle`: this plugin is\n // `enforce: 'pre'`, so its `generateBundle` runs before `vite:build-html`\n // emits the document. `writeBundle` runs once every `generateBundle` has.\n writeBundle(_outputOptions, bundle) {\n if (\n (this as { environment?: { name?: string } }).environment?.name !==\n 'client'\n ) {\n return;\n }\n const emitted = bundle[basename(indexHtmlPath())];\n if (emitted?.type === 'asset') {\n const { source } = emitted;\n builtIndexHtml =\n typeof source === 'string'\n ? source\n : new TextDecoder().decode(source);\n }\n },\n\n nitro: {\n async setup(nitro) {\n // refreshContext may not have run yet if nitro/vite resolved the\n // plugin before `config()`; fall back to nitro's own root.\n if (!context || context.rootDir === '.') {\n refreshContext(nitro.options.rootDir);\n }\n\n // Nitro's default dev runner answers from a worker, and the response\n // does not survive the trip back: the server adapter receives a value\n // it cannot read headers from, so every request Nitro handles hangs\n // without a status. Run the environment in process until that path is\n // fixed upstream. An explicit `devServer.runner` or `NITRO_DEV_RUNNER`\n // still wins.\n if (\n nitro.options.dev &&\n !process.env['NITRO_DEV_RUNNER'] &&\n !nitro.options.devServer?.runner\n ) {\n nitro.options.devServer = {\n ...nitro.options.devServer,\n runner: 'self',\n };\n }\n\n // Preserve the legacy `@analogjs/vite-plugin-nitro` final output\n // layout so downstream tooling (deploy scripts, docs, the\n // `dist/analog/server` start command) keeps working. nitro/vite's\n // default `<rootDir>/.output` would otherwise drop artifacts in an\n // unexpected location for users upgrading from v2.\n //\n // Build only. During dev, leaving the output paths at Nitro's\n // defaults keeps the dev server's `readAsset` happy — those\n // virtuals expect to read from the in-memory module graph, not\n // from a `dist/` directory that doesn't exist yet.\n //\n // `buildDir` (Nitro's intermediate scratch dir) stays at its default\n // inside the project root. Nitro's prerender phase re-bundles SSR\n // chunks out of `<buildDir>/vite/services/ssr/`, and Rolldown's\n // resolver walks up from those files looking for `node_modules/`.\n // Keeping `buildDir` adjacent to the project root means workspace\n // packages installed at `<rootDir>/node_modules/` (the usual install\n // shape for both standalone and Nx setups) remain reachable.\n if (!nitro.options.dev) {\n // Deployment presets (Vercel, Netlify, Cloudflare, Firebase, ...)\n // own their own output layout — Vercel writes the Build Output API\n // tree under `.vercel/output/`, Netlify expects functions under\n // `.netlify/functions-internal/` with static assets under `dist/`,\n // and so on. Clobbering `output.{dir,publicDir,serverDir}` for\n // those presets leaves functions and static files in different\n // trees and breaks the deploy. Only override when running the\n // default node-server preset (or no preset at all) so docs and\n // the legacy `dist/analog/server` start command keep working for\n // standalone Node deployments.\n const preset = (nitro.options.preset ?? '').toLowerCase();\n const isManagedPreset =\n preset !== '' &&\n preset !== 'node-server' &&\n preset !== 'node' &&\n preset !== 'nitro-dev';\n\n // Vercel's Build Output API expects `.vercel/output/` at the cwd\n // `vercel build` runs from (the repo root). Nitro's preset anchors\n // to `{{rootDir}}`, so in Nx monorepos artifacts land at\n // `apps/<name>/.vercel/output/` and the deploy can't find them.\n // Hoist to workspace root and apply Analog's runtime defaults.\n if (preset.includes('vercel')) {\n const vercel = (nitro.options as { vercel?: Record<string, any> })\n .vercel;\n (nitro.options as { vercel?: Record<string, any> }).vercel = {\n ...vercel,\n entryFormat: vercel?.entryFormat ?? 'node',\n functions: {\n runtime: vercel?.functions?.runtime ?? 'nodejs24.x',\n ...vercel?.functions,\n },\n };\n const vercelDir = resolve(context.workspaceRoot, '.vercel/output');\n nitro.options.output = {\n ...nitro.options.output,\n dir: vercelDir,\n serverDir: resolve(vercelDir, 'functions/__server.func'),\n publicDir: resolve(vercelDir, 'static'),\n };\n }\n\n // Netlify auto-discovers functions under\n // `<workspaceRoot>/.netlify/functions-internal/`. Nitro's netlify\n // preset anchors that to `{{rootDir}}`, which in Nx monorepos\n // becomes `apps/<name>/.netlify/...` and is invisible to the\n // Netlify deploy. Hoist the functions to the workspace root so\n // `nx build <app>` produces a deploy-ready tree at the repo root.\n // Keep `publicDir` under `dist/<rootDir>/analog/public/` (the\n // legacy Analog Netlify publish layout) — the user wires their\n // `netlify.toml` publish path to it.\n if (preset === 'netlify' || preset === 'netlify-edge') {\n const netlifyDir = resolve(\n context.workspaceRoot,\n '.netlify/functions-internal',\n );\n nitro.options.output = {\n ...nitro.options.output,\n dir: netlifyDir,\n serverDir: resolve(netlifyDir, 'server'),\n publicDir: resolve(\n context.workspaceRoot,\n 'dist',\n context.rootDir,\n 'analog/public',\n ),\n };\n }\n\n // Cloudflare Pages/Workers presets anchor their output at\n // `{{rootDir}}/dist` or `{{rootDir}}/.output`, which puts the\n // deploy tree at `apps/<name>/...` for Nx monorepos. Hoist to\n // `<workspaceRoot>/dist/<rootDir>/` so `wrangler pages deploy\n // dist/<rootDir>` from the workspace root finds `_worker.js/`\n // alongside the static assets.\n if (preset.includes('cloudflare')) {\n const cfDir = resolve(\n context.workspaceRoot,\n 'dist',\n context.rootDir,\n );\n nitro.options.output = {\n ...nitro.options.output,\n dir: cfDir,\n publicDir: cfDir,\n serverDir: resolve(cfDir, '_worker.js'),\n };\n }\n\n if (!isManagedPreset) {\n const distRoot = resolve(\n context.workspaceRoot,\n 'dist',\n context.rootDir,\n );\n nitro.options.output = {\n ...nitro.options.output,\n dir: resolve(distRoot, 'analog'),\n publicDir: resolve(distRoot, 'analog/public'),\n serverDir: resolve(distRoot, 'analog/server'),\n };\n }\n\n // Nitro v3's prerender writer compares `filePath.startsWith(publicDir)`\n // with `filePath` built via `node:path.join` (platform-native\n // separators on Windows) and `publicDir` set via `resolveNitroPath`\n // (always forward slashes via pathe). On Windows the two sides\n // disagree and every route is marked `(skipped)` — no HTML is\n // written. Hook `prerender:route` and write the file ourselves\n // when Nitro has skipped it but the route generated content.\n nitro.hooks.hook('prerender:route', async (route) => {\n if (!route.skip || route.error) return;\n const buffer = route.data;\n if (!buffer || !route.fileName) return;\n const filePath = resolve(\n nitro.options.output.publicDir,\n route.fileName.replace(/^[\\\\/]+/, ''),\n );\n try {\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, Buffer.from(buffer));\n route.skip = false;\n } catch {\n // leave Nitro's skip in place if the manual write also fails\n }\n });\n }\n\n // Register the user's Vite `publicDir` (e.g. `src/public/`) as a\n // Nitro public asset source. nitro/vite turns off Vite's own copy\n // of publicDir so Nitro can take over, but doesn't auto-bridge the\n // user's setting — without this entry, files like\n // `src/public/assets/shipping.json` aren't served and `HttpClient`\n // SSR fetches fall through to the catch-all SSR renderer, leaking\n // HTML where consumers expected JSON.\n if (userPublicDir && existsSync(userPublicDir)) {\n const already = nitro.options.publicAssets.some(\n (asset) => asset.dir === userPublicDir,\n );\n if (!already) {\n nitro.options.publicAssets.push({\n dir: userPublicDir,\n baseURL: '/',\n maxAge: 0,\n fallthrough: true,\n });\n }\n }\n\n // Bridge the outer Nitro's `output.publicDir` into the prerender's\n // own Nitro instance. Nitro spawns a nested `nitroRenderer` for the\n // prerender pass (`createNitro({ preset: 'nitro-prerender' })`) and\n // builds the public-assets manifest by glob-scanning that\n // instance's `output.publicDir`. The nested config resets\n // `output.publicDir` to undefined and resolves it against the\n // prerender preset defaults (`<rootDir>/.output/public`), so the\n // scan hits an empty directory and the manifest is empty — every\n // `HttpClient.get('/assets/...')` during SSR then falls through to\n // the catch-all SSR renderer and the consumer parses HTML as JSON.\n // Force the nested publicDir to match the outer publicDir (which\n // `copyPublicAssets` has already populated by this point).\n nitro.hooks.hook(\n 'prerender:config',\n (prerendererConfig: { output?: Record<string, unknown> }) => {\n prerendererConfig.output = {\n ...prerendererConfig.output,\n publicDir: nitro.options.output.publicDir,\n };\n },\n );\n\n const pageHandlers: NitroEventHandler[] = getPageHandlers({\n workspaceRoot: context.workspaceRoot,\n sourceRoot: context.sourceRoot,\n rootDir: context.rootDir,\n additionalPagesDirs: options.additionalPagesDirs,\n });\n nitro.options.handlers.push(...pageHandlers);\n\n const serverDir = resolve(\n context.workspaceRoot,\n context.rootDir,\n `${context.sourceRoot}/server`,\n );\n if (\n existsSync(serverDir) &&\n !nitro.options.scanDirs.includes(serverDir)\n ) {\n nitro.options.scanDirs.push(serverDir);\n }\n\n nitro.hooks.hook('rollup:before', (_n, rollupConfig: any) => {\n if (Array.isArray(rollupConfig.plugins)) {\n rollupConfig.plugins.push(pageEndpointsPlugin());\n }\n applyAnalogNitroExternals(rollupConfig);\n sanitizeNitroBundlerConfig(rollupConfig);\n });\n\n if (ssr) {\n // Override Nitro's auto-detected template-serving renderer with one\n // that routes HTML requests to our SSR service. Nitro's\n // `resolveRendererOptions` finds `index.html` at the project root\n // and installs `internal/routes/renderer-template[.dev]`, which\n // just serves the raw template. nitro/vite's own SSR-routing\n // renderer only auto-installs when both `renderer.handler` and\n // `renderer.template` are empty (vite.mjs:574), which never holds\n // for a typical app — so we install our own renderer virtual\n // explicitly here.\n //\n // `#analog/ssr` is a Nitro virtual (not a Vite virtual) so it\n // resolves under both Vite-built bundles (main) and Rolldown-built\n // bundles (Nitro's prerender, which forces builder: 'rolldown' —\n // see nitro/dist/_chunks/nitro.mjs:769). That sidesteps nitro/vite's\n // prodSetup polyfill, which is Vite-only and leaves\n // `__nitro_vite_envs__` unset in the prerender bundle.\n nitro.options.virtual['#analog/ssr'] = () =>\n generateSsrServiceVirtual(nitro);\n // Lazy: `setup()` runs before any environment builds, so reading\n // the template here would read it before the client has emitted\n // one. Nitro resolves this virtual when it bundles — the prerender\n // pass and the final server build, both after the client build.\n nitro.options.virtual['#analog/ssr-renderer'] = () =>\n generateSsrRendererVirtual(readIndexHtml());\n nitro.options.renderer ??= {};\n nitro.options.renderer.handler = '#analog/ssr-renderer';\n delete nitro.options.renderer.template;\n\n // Nitro resolves `renderer.handler` to a file on disk while it\n // creates the prerender instance, which rejects the virtual id.\n // Hide the renderer from that resolution and restore the virtual\n // handler before the prerenderer syncs its routes.\n nitro.hooks.hook('prerender:config', (prerendererConfig) => {\n prerendererConfig.renderer = false;\n });\n nitro.hooks.hook('prerender:init', (prerenderer) => {\n prerenderer.options.renderer = { handler: '#analog/ssr-renderer' };\n });\n }\n // When ssr === false, Nitro's auto-detected template-serving\n // renderer is exactly what we want (serve the raw index.html for\n // every HTML request) — leave it in place.\n\n injectAnalogRouteRuleHeaders(nitro);\n\n await wirePrerender(nitro, options, context, apiPrefix);\n\n if (options.i18n) {\n addPostRenderingHooks(nitro, [\n createI18nPostRenderingHook({\n defaultLocale: options.i18n.defaultLocale,\n locales: options.i18n.locales,\n }),\n ]);\n }\n },\n },\n };\n\n return plugin;\n}\n\n/**\n * Builds the h3 handler installed as Nitro's `renderer.handler`. Short-circuits\n * `ssr: false` routes to the raw client template; otherwise dispatches the\n * request to the SSR service env (`fetchViteEnv(\"ssr\", req)` works in dev via\n * the env-runner and in prod via the `__nitro_vite_envs__` global set up by\n * nitro/vite's `prodSetup`).\n */\nfunction generateSsrRendererVirtual(template: string): string {\n return `\nimport { defineHandler } from 'nitro/h3';\nimport ssr from '#analog/ssr';\n\nconst TEMPLATE = ${JSON.stringify(template)};\n\nexport default defineHandler(async (event) => {\n event.res.headers.set('content-type', 'text/html; charset=utf-8');\n // 'x-analog-no-ssr' is stamped on response headers by\n // injectAnalogRouteRuleHeaders for routeRules with \\`ssr: false\\`. Nitro\n // applies routeRule headers to the response before the renderer fires,\n // so we can short-circuit by reading them here.\n if (event.res.headers.get('x-analog-no-ssr') === 'true') {\n return TEMPLATE;\n }\n const service = ssr.default ?? ssr;\n return service.fetch(event.req);\n});\n`;\n}\n\n/**\n * Resolves \\`#analog/ssr\\` to the SSR fetch handler. The shape returned by\n * this function is bundler-agnostic: works in Vite-built main bundles and\n * Rolldown-built prerender bundles alike.\n *\n * - Dev: dispatch through nitro/vite's env runner (\\`fetchViteEnv\\`); the SSR\n * service module isn't on disk yet, so we delegate to the runner.\n * - Build / prerender: re-export the built SSR entry directly from the\n * filesystem. By the time Nitro's bundlers ask for \\`#analog/ssr\\`, Vite has\n * already produced \\`<buildDir>/vite/services/ssr/<entry>.mjs\\`.\n */\nfunction generateSsrServiceVirtual(nitro: Nitro): string {\n if (nitro.options.dev) {\n return `\nimport { fetchViteEnv } from 'nitro/vite/runtime';\nexport default {\n // The dev runner answers from a worker, and a rejection there comes back as\n // something Nitro cannot turn into a response, so the request hangs with no\n // status and no message. Answer with the failure instead.\n async fetch(req) {\n try {\n return await fetchViteEnv('ssr', req);\n } catch (err) {\n console.error('[analog ssr]', err);\n const message = err instanceof Error ? (err.stack ?? err.message) : String(err);\n return new Response(message, {\n status: 500,\n headers: { 'content-type': 'text/plain; charset=utf-8' },\n });\n }\n },\n};\n`;\n }\n\n const ssrDir = resolve(nitro.options.buildDir, 'vite/services/ssr');\n if (!existsSync(ssrDir)) {\n return `export default { async fetch() { throw new Error('Analog SSR service directory missing: ${ssrDir}'); } };`;\n }\n const entries = readdirSync(ssrDir).filter((f) => f.endsWith('.mjs'));\n if (entries.length === 0) {\n return `export default { async fetch() { throw new Error('No Analog SSR entry file built in: ${ssrDir}'); } };`;\n }\n // Prefer 'main.server.mjs' if present; otherwise take the only entry.\n const entry = entries.find((f) => f === 'main.server.mjs') ?? entries[0];\n const entryPath = resolve(ssrDir, entry);\n return `export { default } from ${JSON.stringify(entryPath)};`;\n}\n\n/**\n * Packages Analog forces external in the Nitro server bundle. Each entry is\n * here for a specific reason — see comments.\n */\nconst ANALOG_NITRO_EXTERNALS = [\n // rxjs ships per-entry CJS/ESM facades that confuse the Nitro/Rolldown\n // resolver during bundling.\n 'rxjs',\n // node-fetch-native's polyfill subpath rewrites global fetch and isn't\n // safe to inline into the Nitro bundle.\n 'node-fetch-native/dist/polyfill',\n // sharp ships platform-specific native binaries under @img/sharp-*. pnpm\n // creates symlinks for ALL optional platform deps but only installs the\n // matching one, leaving broken symlinks that crash Nitro's externals\n // plugin with ENOENT during realpath(). Externalizing sharp avoids\n // bundling it; the user's app resolves it from node_modules at runtime.\n 'sharp',\n];\n\nfunction applyAnalogNitroExternals(rollupConfig: { external?: unknown }): void {\n // Rolldown's `external` only accepts `Array<string | RegExp>`; promote\n // whatever shape Nitro gave us (regex, single string, undefined) to an\n // array and append Analog's entries as regex patterns that also match\n // sub-paths (e.g. `sharp` matches `sharp/lib/foo`).\n const prev = rollupConfig.external;\n const existing: Array<string | RegExp> =\n prev === undefined\n ? []\n : Array.isArray(prev)\n ? (prev as Array<string | RegExp>)\n : prev instanceof RegExp\n ? [prev]\n : typeof prev === 'string'\n ? [prev]\n : [];\n\n const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n for (const entry of ANALOG_NITRO_EXTERNALS) {\n const pattern = new RegExp(`^${escapeRegExp(entry)}(?:/|$)`);\n if (!existing.some((p) => String(p) === String(pattern))) {\n existing.push(pattern);\n }\n }\n\n rollupConfig.external = existing;\n}\n\n/**\n * Workarounds for Nitro v3 + Rolldown bundler interaction quirks. Each\n * is narrowly scoped and can be removed once the upstream bug is fixed:\n *\n * 1. `output.codeSplitting` — Nitro 3.0.x sets this; Rolldown rejects it\n * as an unknown key.\n * 2. `output.manualChunks` — Nitro's default manual chunking crashes\n * Nitro's prerender rebundle.\n * 3. `output.chunkFileNames` — Nitro's chunk-name function produces\n * route-derived `[token]` patterns which Rollup/Rolldown interprets as\n * placeholders; we rewrite non-standard tokens to `_token_`.\n */\nfunction sanitizeNitroBundlerConfig(rollupConfig: { output?: unknown }): void {\n const output = rollupConfig.output;\n if (!output || Array.isArray(output) || typeof output !== 'object') return;\n const out = output as Record<string, unknown>;\n\n if ('codeSplitting' in out) delete out['codeSplitting'];\n if ('manualChunks' in out) delete out['manualChunks'];\n\n const VALID_ROLLUP_PLACEHOLDER = /^\\[(?:name|hash|format|ext)\\]$/;\n const chunkFileNames = out['chunkFileNames'];\n if (typeof chunkFileNames === 'function') {\n const originalFn = chunkFileNames as (...args: unknown[]) => unknown;\n out['chunkFileNames'] = (...args: unknown[]) => {\n const result = originalFn(...args);\n if (typeof result !== 'string') return result;\n return result.replace(/\\[[^\\]]+\\]/g, (match: string) =>\n VALID_ROLLUP_PLACEHOLDER.test(match)\n ? match\n : `_${match.slice(1, -1)}_`,\n );\n };\n }\n}\n\n/**\n * Walks Nitro's resolved routeRules and stamps `x-analog-no-ssr: true` onto\n * any rule with `ssr: false`, and `x-analog-no-streaming: true` onto any rule\n * with `streaming: false`. Kept as response-header hints for downstream\n * consumers (CDN, edge logic); the actual SSR short-circuit happens inside\n * the SSR renderer virtual above, and the router falls back to a buffered\n * render when it sees the streaming hint.\n */\nexport function injectAnalogRouteRuleHeaders(nitro: Nitro): void {\n const routeRules = nitro.options.routeRules as\n | Record<\n string,\n {\n ssr?: boolean;\n streaming?: boolean;\n headers?: Record<string, string>;\n }\n >\n | undefined;\n if (!routeRules) return;\n\n for (const rule of Object.values(routeRules)) {\n if (rule?.ssr === false) {\n rule.headers = { ...rule.headers, 'x-analog-no-ssr': 'true' };\n }\n if (rule?.streaming === false) {\n rule.headers = { ...rule.headers, 'x-analog-no-streaming': 'true' };\n }\n }\n}\n\n/**\n * Builds the SSR service entry source. The wrapper imports the user's\n * `main.server.ts` Angular renderer and adapts it to the `{ fetch(req) }`\n * shape that nitro/vite's service mechanism expects.\n */\nfunction generateSsrEntryWrapper(\n entryServer: string,\n template: string,\n): string {\n return `\n// Import \\`serverFetch\\` from the root \\`nitro\\` entry rather than \\`nitro/app\\`.\n// The /app subpath creates a fresh \\`useNitroApp()\\` instance scoped to the\n// importing bundle, which in our setup is the standalone SSR vite bundle —\n// it has no route handlers, so every fetch 404s. The root entry instead\n// reads \\`globalThis.__nitro__.{default,prerender}\\`, which the surrounding\n// Nitro server (prerender pass or production runtime) has already\n// populated with the real app + handlers.\n// Set \\`ngServerMode\\` before the Angular renderer and its app config evaluate,\n// otherwise \\`provideClientHydration()\\` registers browser-only features such\n// as event replay on the server.\nimport ${JSON.stringify(SERVER_MODE_ID)};\nimport { serverFetch as nitroServerFetch } from 'nitro';\nimport { createFetch } from 'ofetch';\nimport renderer from ${JSON.stringify(entryServer)};\n\nconst TEMPLATE = ${JSON.stringify(template)};\n\nconst normalizeRequestPath = (url) =>\n url.replace(/\\\\/index\\\\.html(?=$|[?#])/, '/');\n\n// In-process fetch wired into Nitro's request pipeline. Angular's HttpClient\n// (via withFetch()) and Analog's injectLoad() call this during SSR/prerender\n// so they hit the running app's page-endpoint and API routes without going\n// through the network — the prerender pipeline doesn't have a listening\n// socket. Without this, every SSR data fetch ECONNREFUSEs and Angular's\n// router fails to resolve any data-bound route, producing an empty\n// <router-outlet/> in the prerendered HTML.\nconst ssrFetch = (resource, init) => {\n let url = typeof resource === 'string'\n ? resource\n : resource instanceof URL\n ? resource.href\n : resource.url;\n // Relative URLs from injectAPIPrefix() etc. need a host for Nitro's\n // Request constructor to accept them.\n if (typeof url === 'string' && url.startsWith('/')) {\n url = 'http://localhost' + url;\n }\n return nitroServerFetch(url, init);\n};\n\n// Wrap in ofetch so consumers that expect \\`$fetch.raw()\\` (the router's\n// request-context interceptor short-circuits SSR HttpClient calls through\n// \\`globalThis.$fetch.raw\\`) can call it. Set on globalThis so router code\n// running inside the Angular renderer can find it.\nconst ssrOFetch = createFetch({ fetch: ssrFetch });\nif (typeof globalThis.$fetch === 'undefined') {\n globalThis.$fetch = ssrOFetch;\n}\n\nexport default {\n async fetch(req) {\n const url = new URL(req.url);\n const requestPath = normalizeRequestPath(url.pathname);\n // Preserve the query string so Angular's router + injectQuery() and\n // server data loaders that read from req.url see the full path+query.\n const requestUrl = requestPath + url.search;\n\n if (req.headers.get('x-analog-no-ssr') === 'true') {\n return new Response(TEMPLATE, {\n status: 200,\n headers: { 'content-type': 'text/html; charset=utf-8' },\n });\n }\n\n const reqShim = {\n headers: Object.fromEntries(req.headers.entries()),\n url: requestUrl,\n originalUrl: requestUrl,\n connection: {},\n };\n\n try {\n const html = await renderer(requestUrl, TEMPLATE, {\n req: reqShim,\n // Pass the ofetch-wrapped fetch — INTERNAL_FETCH is consumed by the\n // router's request-context interceptor via \\`serverFetch.raw(...)\\`,\n // which is ofetch's response-shape API. Plain fetch lacks \\`.raw\\`\n // and throws TypeError during prerender/SSR.\n fetch: ssrOFetch,\n });\n return new Response(html, {\n status: 200,\n headers: { 'content-type': 'text/html; charset=utf-8' },\n });\n } catch (err) {\n console.error('[analog ssr]', err);\n return new Response(TEMPLATE, {\n status: 500,\n headers: { 'content-type': 'text/html; charset=utf-8' },\n });\n }\n },\n};\n`;\n}\n\nasync function wirePrerender(\n nitro: Nitro,\n options: Options,\n context: NitroPluginContext,\n apiPrefix: string,\n): Promise<void> {\n const prerender = options.prerender;\n if (!prerender && !options.i18n) return;\n\n const {\n routes: collected,\n sitemaps: routeSitemaps,\n routeSourceFiles,\n } = await collectRoutes(prerender?.routes, context, apiPrefix);\n\n const expanded = options.i18n\n ? expandRoutesWithLocales(collected, {\n defaultLocale: options.i18n.defaultLocale,\n locales: options.i18n.locales,\n })\n : collected;\n\n const nitroPrerender = (nitro.options.prerender ??= {}) as Record<\n string,\n any\n >;\n nitroPrerender.routes ??= [];\n nitroPrerender.routes.push(...expanded);\n if (prerender?.discover ?? false) {\n nitroPrerender.crawlLinks = true;\n }\n\n // The client build emits an `index.html` shell, and copying the public\n // assets puts it in the output directory before anything is prerendered.\n // Nitro answers from the public assets ahead of the renderer, so the\n // prerenderer's own request for `/` is served that shell and writes it\n // straight back out — the route never reaches the renderer at all. Drop it\n // once the assets are in place and before the first route is rendered, so\n // the prerendered document takes its place.\n const prerendersRoot = (nitroPrerender.routes as string[]).some(\n (route) => route === '/',\n );\n\n if ((options.ssr ?? true) && prerendersRoot) {\n nitro.hooks.hook('prerender:init', () => {\n const publicDir = resolve(nitro.options.output.publicDir);\n\n for (const extension of ['', '.br', '.gz']) {\n const indexFile = resolve(publicDir, `index.html${extension}`);\n\n if (existsSync(indexFile)) {\n unlinkSync(indexFile);\n }\n }\n });\n }\n\n if (prerender?.postRenderingHooks?.length) {\n addPostRenderingHooks(nitro, prerender.postRenderingHooks);\n }\n\n if (Object.keys(routeSourceFiles).length > 0) {\n // Mirror the legacy `@analogjs/vite-plugin-nitro` behavior: after\n // prerender completes, write the route's source content alongside the\n // prerendered HTML at `<publicDir>/<route>.md`. Drives the\n // `outputSourceFile` option on both `PrerenderRouteConfig` (string path\n // to source markdown) and `PrerenderContentDir` (per-file callback).\n nitro.hooks.hook('prerender:done', async () => {\n const publicDir = resolve(nitro.options.output.publicDir);\n const { mkdirSync, writeFileSync } = await import('node:fs');\n const { dirname, join } = await import('node:path');\n for (const [route, content] of Object.entries(routeSourceFiles)) {\n const outputPath = join(publicDir, `${route}.md`);\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, content, 'utf8');\n }\n });\n }\n\n const sitemapConfig = prerender?.sitemap;\n if (sitemapConfig) {\n nitro.hooks.hook('prerender:done', async (result) => {\n const prerenderedRoutes = (result?.prerenderedRoutes ?? []).map(\n (r: PrerenderRoute) => r.route,\n );\n const publicDir = resolve(nitro.options.output.publicDir);\n await buildSitemap(\n {} as any,\n sitemapConfig,\n prerenderedRoutes,\n publicDir,\n routeSitemaps,\n { apiPrefix },\n );\n });\n }\n}\n\nasync function collectRoutes(\n routesInput: Options['prerender'] extends infer P\n ? P extends { routes?: infer R }\n ? R\n : never\n : never,\n context: NitroPluginContext,\n apiPrefix: string,\n): Promise<{\n routes: string[];\n sitemaps: Record<string, RouteSitemap>;\n routeSourceFiles: Record<string, string>;\n}> {\n const out: string[] = [];\n const sitemaps: Record<string, RouteSitemap> = {};\n const routeSourceFiles: Record<string, string> = {};\n\n if (!routesInput) return { routes: out, sitemaps, routeSourceFiles };\n\n const inputs = Array.isArray(routesInput)\n ? routesInput\n : typeof routesInput === 'function'\n ? await routesInput()\n : [];\n\n for (const entry of inputs) {\n if (!entry) continue;\n\n if (typeof entry === 'string') {\n out.push(entry);\n continue;\n }\n\n if ('contentDir' in entry) {\n const dir = entry as PrerenderContentDir;\n const files = getMatchingContentFilesWithFrontMatter(\n context.workspaceRoot,\n context.rootDir,\n dir.contentDir,\n !!dir.recursive,\n );\n for (const file of files) {\n const route = dir.transform(file);\n if (route === false) continue;\n out.push(route);\n if (dir.sitemap) {\n sitemaps[route] =\n typeof dir.sitemap === 'function'\n ? (\n dir.sitemap as (\n f: PrerenderContentFile,\n ) => PrerenderSitemapConfig\n )(file)\n : dir.sitemap;\n }\n if (dir.outputSourceFile) {\n const sourceContent = dir.outputSourceFile(file);\n if (typeof sourceContent === 'string') {\n routeSourceFiles[route] = sourceContent;\n }\n }\n }\n continue;\n }\n\n if ('route' in entry) {\n const cfg = entry as PrerenderRouteConfig;\n out.push(cfg.route);\n if (cfg.sitemap) {\n sitemaps[cfg.route] = cfg.sitemap;\n }\n if (cfg.outputSourceFile) {\n const sourcePath = resolve(\n context.workspaceRoot,\n context.rootDir,\n cfg.outputSourceFile,\n );\n if (existsSync(sourcePath)) {\n routeSourceFiles[cfg.route] = readFileSync(sourcePath, 'utf8');\n }\n }\n if (cfg.staticData) {\n // Mirror the legacy plugin: when staticData is requested, also\n // prerender the page's data-fetching endpoint so the JSON payload\n // is available statically.\n const prefix = apiPrefix.startsWith('/') ? apiPrefix : `/${apiPrefix}`;\n const route = cfg.route.startsWith('/') ? cfg.route : `/${cfg.route}`;\n out.push(`${prefix}/_analog/pages${route}`);\n }\n }\n }\n\n return { routes: out, sitemaps, routeSourceFiles };\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,IAAM,uBAAuB;;;;;;AAO7B,IAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACD;;;;;;AAkBD,SAAgB,kBAAkB,UAAmB,EAAE,EAAU;CAC/D,MAAM,gBACJ,QAAQ,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,KAAK;CAC5E,MAAM,aAAa;CACnB,MAAM,MAAM,QAAQ,OAAO;CAC3B,MAAM,YAAY,QAAQ,aAAa;CAEvC,IAAI,UAA8B;EAChC;EACA,SAAS;EACT;EACD;CACD,IAAI,qBAAqB;CACzB,IAAI;CACJ,IAAI,UAAU;CACd,MAAM,+BAAe,IAAI,SAAwC;CAKjE,IAAI;CAEJ,SAAS,eAAe,aAA4C;EAClE,IAAI,QAAQ,aAAa,IAAI,YAAY;AACzC,MAAI,CAAC,OAAO;AAEV,WAAQ,QAAQ,QAAQ,YAAY,eAAe,MAAM,CAAC;AAC1D,gBAAa,IAAI,aAAa,MAAM;;AAEtC,SAAO;;CAGT,SAAS,eAAe,UAA8B;AAEpD,YAAU;GACR;GACA,SAAS,SAAS,eAHP,YAAY,QAAQ,KAAK,CAGE,IAAI;GAC1C;GACD;AACD,uBAAqB,QACnB,QAAQ,eACR,QAAQ,SACR,0BACD;;CAGH,SAAS,gBAAwB;AAC/B,SAAO,QACL,QAAQ,eACR,QAAQ,SACR,QAAQ,SAAS,aAClB;;CAGH,SAAS,gBAAwB;AAG/B,MAAI,CAAC,SAAS;GACZ,MAAM,SAAS,eAAe;AAC9B,UAAO,WAAW,OAAO,GACrB,aAAa,QAAQ,QAAQ,GAC7B;;AAEN,MAAI,mBAAmB,KAAA,EACrB,OAA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S,aAAa,YAAY,OAAO;;AAGlE,OAAI,IAAI,YAAY;IAIlB,MAAM,SAAS,UAAU,WAAW,IAAI,GAAG,YAAY,IAAI;IAC3D,MAAM,QAAQ,IAAI,MAAM,WAAW,IAAI,GAAG,IAAI,QAAQ,IAAI,IAAI;AAC9D,QAAI,KAAK,GAAG,OAAO,gBAAgB,QAAQ;;;;AAKjD,QAAO;EAAE,QAAQ;EAAK;EAAU;EAAkB"}
|
|
1
|
+
{"version":3,"file":"analog-nitro-plugin.js","names":[],"sources":["../../../../src/lib/nitro/analog-nitro-plugin.ts"],"sourcesContent":["import { existsSync, readFileSync, readdirSync, unlinkSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { basename, dirname, join, relative, resolve } from 'node:path';\nimport type { Nitro, NitroEventHandler, PrerenderRoute } from 'nitro/types';\nimport type { DevEnvironment, Plugin, UserConfig } from 'vite';\n\nimport type { Options } from '../options.js';\nimport { SERVER_MODE_ID } from '../../server-mode-plugin.js';\nimport { injectServerFnIds } from '../inject-server-fn-ids.js';\nimport { serverFnFileId } from '../server-fn-id.js';\nimport type {\n PrerenderContentDir,\n PrerenderContentFile,\n PrerenderRouteConfig,\n PrerenderSitemapConfig,\n} from './types.js';\nimport { getPageHandlers } from './get-page-handlers.js';\nimport { pageEndpointsPlugin } from './page-endpoints-plugin.js';\nimport { getMatchingContentFilesWithFrontMatter } from './get-content-files.js';\nimport { buildSitemap } from './build-sitemap.js';\nimport { addPostRenderingHooks } from './post-rendering-hook.js';\nimport {\n expandRoutesWithLocales,\n createI18nPostRenderingHook,\n} from './i18n-prerender.js';\nimport { getServerFnHandlers } from './get-server-fn-handlers.js';\nimport {\n buildServerFnDispatchModule,\n getServerFnDispatchHandler,\n SERVER_FN_DISPATCH_VIRTUAL,\n} from './server-fn-endpoints.js';\n\nconst SSR_ENTRY_VIRTUAL_ID = '\\0virtual:@analogjs/nitro/ssr-entry';\n\ninterface NitroPluginContext {\n workspaceRoot: string;\n rootDir: string;\n sourceRoot: string;\n}\n\ntype RouteSitemap =\n | PrerenderSitemapConfig\n | (() => PrerenderSitemapConfig)\n | undefined;\n\n/**\n * Analog's NitroModule. Plug it into the Vite plugin chain alongside\n * `nitro()` from `nitro/vite`; nitro/vite picks up the `.nitro` property\n * and runs `setup(nitro)` once the Nitro instance is ready.\n */\nexport function analogNitroPlugin(options: Options = {}): Plugin {\n const workspaceRoot =\n options.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd();\n const sourceRoot = 'src';\n const ssr = options.ssr ?? true;\n const apiPrefix = options.apiPrefix ?? 'api';\n\n let context: NitroPluginContext = {\n workspaceRoot,\n rootDir: '.',\n sourceRoot,\n };\n let ssrEntryMarkerPath = '';\n let userPublicDir: string | undefined;\n let isBuild = false;\n // Only active alongside `nitro()` from `nitro/vite`; apps on Nitro v2 use\n // `@analogjs/vite-plugin-nitro` instead.\n let enabled = false;\n let nitroH3Resolver: Plugin;\n const ssrDepsReady = new WeakMap<DevEnvironment, Promise<void>>();\n // The document the client environment emitted for this build, captured in\n // `writeBundle` below. A build must render around this rather than the\n // source document: the source points at the unbundled entry, which only\n // resolves while Vite is serving.\n let builtIndexHtml: string | undefined;\n\n function waitForSsrDeps(environment: DevEnvironment): Promise<void> {\n let ready = ssrDepsReady.get(environment);\n if (!ready) {\n // Vite's subsequent init() calls return before the first run finishes.\n ready = Promise.resolve(environment.depsOptimizer?.init());\n ssrDepsReady.set(environment, ready);\n }\n return ready;\n }\n\n function refreshContext(viteRoot: string | undefined) {\n const root = viteRoot ?? process.cwd();\n context = {\n workspaceRoot,\n rootDir: relative(workspaceRoot, root) || '.',\n sourceRoot,\n };\n ssrEntryMarkerPath = resolve(\n context.workspaceRoot,\n context.rootDir,\n '.analog/__ssr-entry.mjs',\n );\n }\n\n function indexHtmlPath(): string {\n return resolve(\n context.workspaceRoot,\n context.rootDir,\n options.index ?? 'index.html',\n );\n }\n\n function readIndexHtml(): string {\n // Dev reads the source document so Vite can transform it and serve the\n // entry it points at.\n if (!isBuild) {\n const source = indexHtmlPath();\n return existsSync(source)\n ? readFileSync(source, 'utf-8')\n : '<!doctype html><html><body><div id=\"app\"></div></body></html>';\n }\n if (builtIndexHtml === undefined) {\n throw new Error(\n `[analog] The client build produced no ${basename(indexHtmlPath())}, ` +\n `so there is no document to server-render around. Rendering around ` +\n `the source document instead would ship markup pointing at the ` +\n `unbundled entry, which does not exist in a build.`,\n );\n }\n return builtIndexHtml;\n }\n\n function resolveEntryServer(): string {\n return (\n options.entryServer ??\n resolve(\n context.workspaceRoot,\n context.rootDir,\n `${sourceRoot}/main.server.ts`,\n )\n );\n }\n\n const plugin: Plugin & {\n nitro: { setup: (nitro: Nitro) => void | Promise<void> };\n } = {\n name: '@analogjs/nitro',\n enforce: 'pre',\n\n config(userConfig, configEnv) {\n enabled = hasNitroVitePlugin(userConfig);\n if (!enabled) {\n return;\n }\n refreshContext(userConfig.root);\n isBuild = configEnv?.command === 'build';\n nitroH3Resolver = nitroH3Plugin(\n resolve(context.workspaceRoot, context.rootDir),\n );\n\n // Capture the user's Vite `publicDir` so the nitro `setup()` hook can\n // register it as a Nitro `publicAssets` source. nitro/vite forces the\n // client environment's `build.copyPublicDir` to `false`\n // (vite.mjs:248), expecting Nitro to manage public assets — but\n // doesn't auto-add the user's `publicDir`. Without this, anything\n // under `src/public/` (e.g. `/assets/shipping.json`) 404s during SSR\n // and ofetch consumers parse the catch-all SSR HTML as JSON.\n if (userConfig.publicDir !== false) {\n userPublicDir = resolve(\n context.workspaceRoot,\n context.rootDir,\n (userConfig.publicDir as string | undefined) ?? 'public',\n );\n }\n\n // Bridge the legacy `BUILD_PRESET` env var that `@analogjs/vite-plugin-nitro`\n // accepted into Nitro v3's `NITRO_PRESET`, and auto-pick the matching\n // preset when the build runs inside a host's CI (each host sets its\n // own well-known env var). Mirrors the legacy plugin's behavior so\n // users upgrading don't need to change their CI configuration.\n if (!process.env['NITRO_PRESET']) {\n if (process.env['BUILD_PRESET']) {\n process.env['NITRO_PRESET'] = process.env['BUILD_PRESET'];\n } else if (process.env['VERCEL']) {\n process.env['NITRO_PRESET'] = 'vercel';\n } else if (process.env['NETLIFY']) {\n process.env['NITRO_PRESET'] = 'netlify';\n } else if (process.env['CF_PAGES']) {\n process.env['NITRO_PRESET'] = 'cloudflare-pages';\n }\n }\n\n const overrides: UserConfig = {\n // Vite 8 defaults `server.fs.allow` to `[searchForWorkspaceRoot(root)]`,\n // which should already cover the workspace root. In practice, nitro/vite's\n // env-runner loads its own `dev-entry.mjs` from a pnpm content-hash path\n // (`node_modules/.pnpm/nitro@.../...`) through Vite's ModuleRunner and\n // hits an `ERR_LOAD_URL`/\"Does the file exist?\" error unless an explicit\n // allow entry covers the same root. Whitelist the workspace root here so\n // users don't have to write the workaround in every vite.config.ts.\n server: {\n fs: {\n allow: [context.workspaceRoot],\n },\n },\n // nitro/vite defaults the client environment's input to\n // `renderer.template` (vite.mjs:240). We install our own renderer\n // handler and delete that template — Nitro's template-serving\n // renderer just returns the raw document — which leaves the client\n // environment with no input, and an environment without one is\n // skipped (vite.mjs:78). The build then emits no browser bundles at\n // all and the client never boots. Point it at the source document\n // ourselves.\n //\n // Declared ahead of `ssr` so it builds first: the SSR bundle inlines\n // the document it renders around, so the client output has to exist\n // by the time that bundle is built.\n environments: {\n client: {\n build: { rollupOptions: { input: indexHtmlPath() } },\n },\n } as UserConfig['environments'],\n };\n\n if (ssr) {\n // Two-pronged registration: `experimental.vite.services.ssr.entry`\n // is the documented hook, but nitro/vite's setupNitroContext also\n // accepts an `environments.ssr.build.rollupOptions.input` entry\n // (see node_modules/nitro/dist/vite.mjs:710-734). When `analog()`\n // and `nitro()` are invoked separately, the `services` slot on\n // `nitro()`'s pluginConfig is empty, so the rollupOptions.input\n // path is how we get our wrapper entry recognized.\n overrides.experimental = {\n vite: {\n services: {\n ssr: { entry: ssrEntryMarkerPath },\n },\n },\n };\n (overrides.environments as Record<string, unknown>)['ssr'] = {\n build: {\n outDir: resolve(\n context.workspaceRoot,\n 'dist',\n context.rootDir,\n 'ssr',\n ),\n rollupOptions: {\n input: { index: ssrEntryMarkerPath },\n },\n },\n };\n }\n\n return overrides;\n },\n\n configureServer(server) {\n const environment = server.environments['ssr'];\n if (enabled && ssr && environment) {\n // Capture initialization before listen(); entry resolution propagates failures.\n void waitForSsrDeps(environment).catch(() => undefined);\n }\n },\n\n resolveId(id, importer, resolveOptions) {\n if (enabled && id === 'h3') {\n return (nitroH3Resolver.resolveId as ResolveIdHook).call(\n this,\n id,\n importer,\n resolveOptions,\n );\n }\n if (id === ssrEntryMarkerPath || id === SSR_ENTRY_VIRTUAL_ID) {\n if (ssr && !isBuild && this.environment.name === 'ssr') {\n return waitForSsrDeps(this.environment as DevEnvironment).then(\n () => SSR_ENTRY_VIRTUAL_ID,\n );\n }\n return SSR_ENTRY_VIRTUAL_ID;\n }\n return null;\n },\n\n load(id) {\n if (id !== SSR_ENTRY_VIRTUAL_ID) return null;\n return generateSsrEntryWrapper(resolveEntryServer(), readIndexHtml());\n },\n\n // Take the rendered-around document from the client environment's own\n // output rather than guessing where it landed. A guessed path can name a\n // leftover from an earlier build, which serves pages an application bundle\n // that no longer matches the markup around it.\n //\n // `writeBundle` rather than `generateBundle`: this plugin is\n // `enforce: 'pre'`, so its `generateBundle` runs before `vite:build-html`\n // emits the document. `writeBundle` runs once every `generateBundle` has.\n writeBundle(_outputOptions, bundle) {\n if (\n !enabled ||\n (this as { environment?: { name?: string } }).environment?.name !==\n 'client'\n ) {\n return;\n }\n const emitted = bundle[basename(indexHtmlPath())];\n if (emitted?.type === 'asset') {\n const { source } = emitted;\n builtIndexHtml =\n typeof source === 'string'\n ? source\n : new TextDecoder().decode(source);\n }\n },\n\n nitro: {\n async setup(nitro) {\n // refreshContext may not have run yet if nitro/vite resolved the\n // plugin before `config()`; fall back to nitro's own root.\n if (!context || context.rootDir === '.') {\n refreshContext(nitro.options.rootDir);\n }\n\n // Nitro's default dev runner answers from a worker, and the response\n // does not survive the trip back: the server adapter receives a value\n // it cannot read headers from, so every request Nitro handles hangs\n // without a status. Run the environment in process until that path is\n // fixed upstream. An explicit `devServer.runner` or `NITRO_DEV_RUNNER`\n // still wins.\n if (\n nitro.options.dev &&\n !process.env['NITRO_DEV_RUNNER'] &&\n !nitro.options.devServer?.runner\n ) {\n nitro.options.devServer = {\n ...nitro.options.devServer,\n runner: 'self',\n };\n }\n\n // Preserve the legacy `@analogjs/vite-plugin-nitro` final output\n // layout so downstream tooling (deploy scripts, docs, the\n // `dist/analog/server` start command) keeps working. nitro/vite's\n // default `<rootDir>/.output` would otherwise drop artifacts in an\n // unexpected location for users upgrading from v2.\n //\n // Build only. During dev, leaving the output paths at Nitro's\n // defaults keeps the dev server's `readAsset` happy — those\n // virtuals expect to read from the in-memory module graph, not\n // from a `dist/` directory that doesn't exist yet.\n //\n // `buildDir` (Nitro's intermediate scratch dir) stays at its default\n // inside the project root. Nitro's prerender phase re-bundles SSR\n // chunks out of `<buildDir>/vite/services/ssr/`, and Rolldown's\n // resolver walks up from those files looking for `node_modules/`.\n // Keeping `buildDir` adjacent to the project root means workspace\n // packages installed at `<rootDir>/node_modules/` (the usual install\n // shape for both standalone and Nx setups) remain reachable.\n if (!nitro.options.dev) {\n // Deployment presets (Vercel, Netlify, Cloudflare, Firebase, ...)\n // own their own output layout — Vercel writes the Build Output API\n // tree under `.vercel/output/`, Netlify expects functions under\n // `.netlify/functions-internal/` with static assets under `dist/`,\n // and so on. Clobbering `output.{dir,publicDir,serverDir}` for\n // those presets leaves functions and static files in different\n // trees and breaks the deploy. Only override when running the\n // default node-server preset (or no preset at all) so docs and\n // the legacy `dist/analog/server` start command keep working for\n // standalone Node deployments.\n const preset = (nitro.options.preset ?? '').toLowerCase();\n const isManagedPreset =\n preset !== '' &&\n preset !== 'node-server' &&\n preset !== 'node' &&\n preset !== 'nitro-dev';\n\n // Vercel's Build Output API expects `.vercel/output/` at the cwd\n // `vercel build` runs from (the repo root). Nitro's preset anchors\n // to `{{rootDir}}`, so in Nx monorepos artifacts land at\n // `apps/<name>/.vercel/output/` and the deploy can't find them.\n // Hoist to workspace root and apply Analog's runtime defaults.\n if (preset.includes('vercel')) {\n const vercel = (nitro.options as { vercel?: Record<string, any> })\n .vercel;\n (nitro.options as { vercel?: Record<string, any> }).vercel = {\n ...vercel,\n entryFormat: vercel?.entryFormat ?? 'node',\n functions: {\n runtime: vercel?.functions?.runtime ?? 'nodejs24.x',\n ...vercel?.functions,\n },\n };\n const vercelDir = resolve(context.workspaceRoot, '.vercel/output');\n nitro.options.output = {\n ...nitro.options.output,\n dir: vercelDir,\n serverDir: resolve(vercelDir, 'functions/__server.func'),\n publicDir: resolve(vercelDir, 'static'),\n };\n }\n\n // Netlify auto-discovers functions under\n // `<workspaceRoot>/.netlify/functions-internal/`. Nitro's netlify\n // preset anchors that to `{{rootDir}}`, which in Nx monorepos\n // becomes `apps/<name>/.netlify/...` and is invisible to the\n // Netlify deploy. Hoist the functions to the workspace root so\n // `nx build <app>` produces a deploy-ready tree at the repo root.\n // Keep `publicDir` under `dist/<rootDir>/analog/public/` (the\n // legacy Analog Netlify publish layout) — the user wires their\n // `netlify.toml` publish path to it.\n if (preset === 'netlify' || preset === 'netlify-edge') {\n const netlifyDir = resolve(\n context.workspaceRoot,\n '.netlify/functions-internal',\n );\n nitro.options.output = {\n ...nitro.options.output,\n dir: netlifyDir,\n serverDir: resolve(netlifyDir, 'server'),\n publicDir: resolve(\n context.workspaceRoot,\n 'dist',\n context.rootDir,\n 'analog/public',\n ),\n };\n }\n\n // Cloudflare Pages/Workers presets anchor their output at\n // `{{rootDir}}/dist` or `{{rootDir}}/.output`, which puts the\n // deploy tree at `apps/<name>/...` for Nx monorepos. Hoist to\n // `<workspaceRoot>/dist/<rootDir>/` so `wrangler pages deploy\n // dist/<rootDir>` from the workspace root finds `_worker.js/`\n // alongside the static assets.\n if (preset.includes('cloudflare')) {\n const cfDir = resolve(\n context.workspaceRoot,\n 'dist',\n context.rootDir,\n );\n nitro.options.output = {\n ...nitro.options.output,\n dir: cfDir,\n publicDir: cfDir,\n serverDir: resolve(cfDir, '_worker.js'),\n };\n }\n\n if (!isManagedPreset) {\n const distRoot = resolve(\n context.workspaceRoot,\n 'dist',\n context.rootDir,\n );\n nitro.options.output = {\n ...nitro.options.output,\n dir: resolve(distRoot, 'analog'),\n publicDir: resolve(distRoot, 'analog/public'),\n serverDir: resolve(distRoot, 'analog/server'),\n };\n }\n\n // Nitro v3's prerender writer compares `filePath.startsWith(publicDir)`\n // with `filePath` built via `node:path.join` (platform-native\n // separators on Windows) and `publicDir` set via `resolveNitroPath`\n // (always forward slashes via pathe). On Windows the two sides\n // disagree and every route is marked `(skipped)` — no HTML is\n // written. Hook `prerender:route` and write the file ourselves\n // when Nitro has skipped it but the route generated content.\n nitro.hooks.hook('prerender:route', async (route) => {\n if (!route.skip || route.error) return;\n const buffer = route.data;\n if (!buffer || !route.fileName) return;\n const filePath = resolve(\n nitro.options.output.publicDir,\n route.fileName.replace(/^[\\\\/]+/, ''),\n );\n try {\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, Buffer.from(buffer));\n route.skip = false;\n } catch {\n // leave Nitro's skip in place if the manual write also fails\n }\n });\n }\n\n // Register the user's Vite `publicDir` (e.g. `src/public/`) as a\n // Nitro public asset source. nitro/vite turns off Vite's own copy\n // of publicDir so Nitro can take over, but doesn't auto-bridge the\n // user's setting — without this entry, files like\n // `src/public/assets/shipping.json` aren't served and `HttpClient`\n // SSR fetches fall through to the catch-all SSR renderer, leaking\n // HTML where consumers expected JSON.\n if (userPublicDir && existsSync(userPublicDir)) {\n const already = nitro.options.publicAssets.some(\n (asset) => asset.dir === userPublicDir,\n );\n if (!already) {\n nitro.options.publicAssets.push({\n dir: userPublicDir,\n baseURL: '/',\n maxAge: 0,\n fallthrough: true,\n });\n }\n }\n\n // Bridge the outer Nitro's `output.publicDir` into the prerender's\n // own Nitro instance. Nitro spawns a nested `nitroRenderer` for the\n // prerender pass (`createNitro({ preset: 'nitro-prerender' })`) and\n // builds the public-assets manifest by glob-scanning that\n // instance's `output.publicDir`. The nested config resets\n // `output.publicDir` to undefined and resolves it against the\n // prerender preset defaults (`<rootDir>/.output/public`), so the\n // scan hits an empty directory and the manifest is empty — every\n // `HttpClient.get('/assets/...')` during SSR then falls through to\n // the catch-all SSR renderer and the consumer parses HTML as JSON.\n // Force the nested publicDir to match the outer publicDir (which\n // `copyPublicAssets` has already populated by this point).\n nitro.hooks.hook(\n 'prerender:config',\n (prerendererConfig: { output?: Record<string, unknown> }) => {\n prerendererConfig.output = {\n ...prerendererConfig.output,\n publicDir: nitro.options.output.publicDir,\n };\n },\n );\n\n const pageHandlers: NitroEventHandler[] = getPageHandlers({\n workspaceRoot: context.workspaceRoot,\n sourceRoot: context.sourceRoot,\n rootDir: context.rootDir,\n additionalPagesDirs: options.additionalPagesDirs,\n });\n nitro.options.handlers.push(...pageHandlers);\n registerServerFns(nitro, context);\n\n const serverDir = resolve(\n context.workspaceRoot,\n context.rootDir,\n `${context.sourceRoot}/server`,\n );\n const apiDirs = (options.additionalAPIDirs ?? []).map((dir) =>\n resolve(context.workspaceRoot, `.${dir}`),\n );\n for (const dir of [serverDir, ...apiDirs]) {\n if (existsSync(dir) && !nitro.options.scanDirs.includes(dir)) {\n nitro.options.scanDirs.push(dir);\n }\n }\n\n nitro.hooks.hook('rollup:before', (_n, rollupConfig: any) => {\n if (Array.isArray(rollupConfig.plugins)) {\n rollupConfig.plugins.push(\n nitroH3Resolver,\n pageEndpointsPlugin(),\n serverFnIdPlugin(resolve(context.workspaceRoot, context.rootDir)),\n );\n }\n applyAnalogNitroExternals(rollupConfig);\n sanitizeNitroBundlerConfig(rollupConfig);\n });\n\n if (ssr) {\n // Override Nitro's auto-detected template-serving renderer with one\n // that routes HTML requests to our SSR service. Nitro's\n // `resolveRendererOptions` finds `index.html` at the project root\n // and installs `internal/routes/renderer-template[.dev]`, which\n // just serves the raw template. nitro/vite's own SSR-routing\n // renderer only auto-installs when both `renderer.handler` and\n // `renderer.template` are empty (vite.mjs:574), which never holds\n // for a typical app — so we install our own renderer virtual\n // explicitly here.\n //\n // `#analog/ssr` is a Nitro virtual (not a Vite virtual) so it\n // resolves under both Vite-built bundles (main) and Rolldown-built\n // bundles (Nitro's prerender, which forces builder: 'rolldown' —\n // see nitro/dist/_chunks/nitro.mjs:769). That sidesteps nitro/vite's\n // prodSetup polyfill, which is Vite-only and leaves\n // `__nitro_vite_envs__` unset in the prerender bundle.\n nitro.options.virtual['#analog/ssr'] = () =>\n generateSsrServiceVirtual(nitro);\n // Lazy: `setup()` runs before any environment builds, so reading\n // the template here would read it before the client has emitted\n // one. Nitro resolves this virtual when it bundles — the prerender\n // pass and the final server build, both after the client build.\n nitro.options.virtual['#analog/ssr-renderer'] = () =>\n generateSsrRendererVirtual(readIndexHtml());\n nitro.options.renderer ??= {};\n nitro.options.renderer.handler = '#analog/ssr-renderer';\n delete nitro.options.renderer.template;\n\n // Nitro resolves `renderer.handler` to a file on disk while it\n // creates the prerender instance, which rejects the virtual id.\n // Hide the renderer from that resolution and restore the virtual\n // handler before the prerenderer syncs its routes.\n nitro.hooks.hook('prerender:config', (prerendererConfig) => {\n prerendererConfig.renderer = false;\n // The prerender instance is created from the raw user config, so\n // pass along the rules carrying the `ssr: false` headers.\n prerendererConfig.routeRules = nitro.options.routeRules;\n });\n nitro.hooks.hook('prerender:init', (prerenderer) => {\n prerenderer.options.renderer = { handler: '#analog/ssr-renderer' };\n });\n\n // The client build emits an `index.html` shell, and copying the\n // public assets puts it in the output directory. Nitro answers from\n // the public assets ahead of the renderer, so `/` would be served\n // that shell instead of being rendered. Nitro calls this hook once\n // the assets are in place, before prerendering and the server build.\n nitro.hooks.hook('prerender:routes', () => {\n const publicDir = resolve(nitro.options.output.publicDir);\n for (const extension of ['', '.br', '.gz']) {\n const indexFile = resolve(publicDir, `index.html${extension}`);\n if (existsSync(indexFile)) {\n unlinkSync(indexFile);\n }\n }\n });\n }\n // When ssr === false, Nitro's auto-detected template-serving\n // renderer is exactly what we want (serve the raw index.html for\n // every HTML request) — leave it in place.\n\n injectAnalogRouteRuleHeaders(nitro);\n\n await wirePrerender(nitro, options, context, apiPrefix);\n\n if (options.i18n) {\n addPostRenderingHooks(nitro, [\n createI18nPostRenderingHook({\n defaultLocale: options.i18n.defaultLocale,\n locales: options.i18n.locales,\n }),\n ]);\n }\n },\n },\n };\n\n return plugin;\n}\n\nfunction hasNitroVitePlugin(userConfig: UserConfig): boolean {\n const plugins = ((userConfig.plugins ?? []) as unknown[]).flat(Infinity) as (\n | { name?: string }\n | null\n | undefined\n )[];\n return plugins.some((plugin) => plugin?.name === 'nitro:main');\n}\n\ntype ResolveIdHook = Extract<NonNullable<Plugin['resolveId']>, Function>;\n\n/**\n * Resolves `h3` from Nitro's own package, so server code always uses the h3\n * version the server runs on.\n */\nfunction nitroH3Plugin(root: string): Plugin {\n let nitroPackageJson: string | undefined;\n return {\n name: 'analogjs-nitro-h3',\n resolveId(id, _importer, resolveOptions) {\n if (id !== 'h3') {\n return null;\n }\n nitroPackageJson ??= createRequire(join(root, 'noop.js')).resolve(\n 'nitro/package.json',\n );\n return this.resolve(id, nitroPackageJson, {\n ...resolveOptions,\n skipSelf: true,\n });\n },\n };\n}\n\n/**\n * Registers the `/_analog/fn/:id` dispatch handler when the app defines server\n * functions in `*.server.ts` files.\n */\nfunction registerServerFns(nitro: Nitro, context: NitroPluginContext): void {\n const modules = getServerFnHandlers(context);\n if (!modules.length) {\n return;\n }\n\n const root = resolve(context.workspaceRoot, context.rootDir);\n const appConfigModule = [\n `${root}/${context.sourceRoot}/app/app.config.server.ts`,\n `${root}/${context.sourceRoot}/app.config.server.ts`,\n ].find((candidate) => existsSync(candidate));\n\n nitro.options.handlers.push(getServerFnDispatchHandler());\n nitro.options.virtual[SERVER_FN_DISPATCH_VIRTUAL] =\n buildServerFnDispatchModule({ modules, appConfigModule });\n}\n\n/**\n * Stamps the derived id into each `serverFn` in the Nitro server bundle, so it\n * registers under the route the client calls.\n */\nfunction serverFnIdPlugin(projectRoot: string): {\n name: string;\n transform(code: string, id: string): { code: string; map: null } | undefined;\n} {\n return {\n name: 'analogjs-server-fn-id',\n transform(code, id) {\n if (!id.endsWith('.server.ts')) {\n return;\n }\n const injected = injectServerFnIds(code, serverFnFileId(id, projectRoot));\n return injected ? { code: injected.code, map: null } : undefined;\n },\n };\n}\n\n/**\n * Builds the h3 handler installed as Nitro's `renderer.handler`. Short-circuits\n * `ssr: false` routes to the raw client template; otherwise dispatches the\n * request to the SSR service env (`fetchViteEnv(\"ssr\", req)` works in dev via\n * the env-runner and in prod via the `__nitro_vite_envs__` global set up by\n * nitro/vite's `prodSetup`).\n */\nfunction generateSsrRendererVirtual(template: string): string {\n return `\nimport { defineHandler } from 'nitro/h3';\nimport { getRouteRules } from 'nitro/app';\nimport ssr from '#analog/ssr';\n\nconst TEMPLATE = ${JSON.stringify(template)};\n\nexport default defineHandler(async (event) => {\n event.res.headers.set('content-type', 'text/html; charset=utf-8');\n // 'x-analog-no-ssr' is stamped on the route rule headers by\n // injectAnalogRouteRuleHeaders for routeRules with \\`ssr: false\\`. Nitro\n // writes those headers after the handler runs, so read the matched rules.\n const { routeRules } = getRouteRules(event.req.method, event.url.pathname);\n if (routeRules?.headers?.['x-analog-no-ssr'] === 'true') {\n return TEMPLATE;\n }\n const service = ssr.default ?? ssr;\n // The SSR service renders without a Node response, so forward the\n // \\`streaming: false\\` rule on the request for the renderer to read.\n if (routeRules?.headers?.['x-analog-no-streaming'] === 'true') {\n const headers = new Headers(event.req.headers);\n headers.set('x-analog-no-streaming', 'true');\n return service.fetch(\n new Request(event.req.url, { method: event.req.method, headers }),\n );\n }\n return service.fetch(event.req);\n});\n`;\n}\n\n/**\n * Resolves \\`#analog/ssr\\` to the SSR fetch handler. The shape returned by\n * this function is bundler-agnostic: works in Vite-built main bundles and\n * Rolldown-built prerender bundles alike.\n *\n * - Dev: dispatch through nitro/vite's env runner (\\`fetchViteEnv\\`); the SSR\n * service module isn't on disk yet, so we delegate to the runner.\n * - Build / prerender: re-export the built SSR entry directly from the\n * filesystem. By the time Nitro's bundlers ask for \\`#analog/ssr\\`, Vite has\n * already produced \\`<buildDir>/vite/services/ssr/<entry>.mjs\\`.\n */\nfunction generateSsrServiceVirtual(nitro: Nitro): string {\n if (nitro.options.dev) {\n return `\nimport { fetchViteEnv } from 'nitro/vite/runtime';\nexport default {\n // The dev runner answers from a worker, and a rejection there comes back as\n // something Nitro cannot turn into a response, so the request hangs with no\n // status and no message. Answer with the failure instead.\n async fetch(req) {\n try {\n return await fetchViteEnv('ssr', req);\n } catch (err) {\n console.error('[analog ssr]', err);\n const message = err instanceof Error ? (err.stack ?? err.message) : String(err);\n return new Response(message, {\n status: 500,\n headers: { 'content-type': 'text/plain; charset=utf-8' },\n });\n }\n },\n};\n`;\n }\n\n const ssrDir = resolve(nitro.options.buildDir, 'vite/services/ssr');\n if (!existsSync(ssrDir)) {\n return `export default { async fetch() { throw new Error('Analog SSR service directory missing: ${ssrDir}'); } };`;\n }\n const entries = readdirSync(ssrDir).filter((f) => f.endsWith('.mjs'));\n if (entries.length === 0) {\n return `export default { async fetch() { throw new Error('No Analog SSR entry file built in: ${ssrDir}'); } };`;\n }\n // Prefer 'main.server.mjs' if present; otherwise take the only entry.\n const entry = entries.find((f) => f === 'main.server.mjs') ?? entries[0];\n const entryPath = resolve(ssrDir, entry);\n return `export { default } from ${JSON.stringify(entryPath)};`;\n}\n\n/**\n * Packages Analog forces external in the Nitro server bundle. Each entry is\n * here for a specific reason — see comments.\n */\nconst ANALOG_NITRO_EXTERNALS = [\n // rxjs ships per-entry CJS/ESM facades that confuse the Nitro/Rolldown\n // resolver during bundling.\n 'rxjs',\n // node-fetch-native's polyfill subpath rewrites global fetch and isn't\n // safe to inline into the Nitro bundle.\n 'node-fetch-native/dist/polyfill',\n // sharp ships platform-specific native binaries under @img/sharp-*. pnpm\n // creates symlinks for ALL optional platform deps but only installs the\n // matching one, leaving broken symlinks that crash Nitro's externals\n // plugin with ENOENT during realpath(). Externalizing sharp avoids\n // bundling it; the user's app resolves it from node_modules at runtime.\n 'sharp',\n];\n\nfunction applyAnalogNitroExternals(rollupConfig: { external?: unknown }): void {\n // Rolldown's `external` only accepts `Array<string | RegExp>`; promote\n // whatever shape Nitro gave us (regex, single string, undefined) to an\n // array and append Analog's entries as regex patterns that also match\n // sub-paths (e.g. `sharp` matches `sharp/lib/foo`).\n const prev = rollupConfig.external;\n const existing: Array<string | RegExp> =\n prev === undefined\n ? []\n : Array.isArray(prev)\n ? (prev as Array<string | RegExp>)\n : prev instanceof RegExp\n ? [prev]\n : typeof prev === 'string'\n ? [prev]\n : [];\n\n const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n for (const entry of ANALOG_NITRO_EXTERNALS) {\n const pattern = new RegExp(`^${escapeRegExp(entry)}(?:/|$)`);\n if (!existing.some((p) => String(p) === String(pattern))) {\n existing.push(pattern);\n }\n }\n\n rollupConfig.external = existing;\n}\n\n/**\n * Workarounds for Nitro v3 + Rolldown bundler interaction quirks. Each\n * is narrowly scoped and can be removed once the upstream bug is fixed:\n *\n * 1. `output.codeSplitting` — Nitro 3.0.x sets this; Rolldown rejects it\n * as an unknown key.\n * 2. `output.manualChunks` — Nitro's default manual chunking crashes\n * Nitro's prerender rebundle.\n * 3. `output.chunkFileNames` — Nitro's chunk-name function produces\n * route-derived `[token]` patterns which Rollup/Rolldown interprets as\n * placeholders; we rewrite non-standard tokens to `_token_`.\n */\nfunction sanitizeNitroBundlerConfig(rollupConfig: { output?: unknown }): void {\n const output = rollupConfig.output;\n if (!output || Array.isArray(output) || typeof output !== 'object') return;\n const out = output as Record<string, unknown>;\n\n if ('codeSplitting' in out) delete out['codeSplitting'];\n if ('manualChunks' in out) delete out['manualChunks'];\n\n const VALID_ROLLUP_PLACEHOLDER = /^\\[(?:name|hash|format|ext)\\]$/;\n const chunkFileNames = out['chunkFileNames'];\n if (typeof chunkFileNames === 'function') {\n const originalFn = chunkFileNames as (...args: unknown[]) => unknown;\n out['chunkFileNames'] = (...args: unknown[]) => {\n const result = originalFn(...args);\n if (typeof result !== 'string') return result;\n return result.replace(/\\[[^\\]]+\\]/g, (match: string) =>\n VALID_ROLLUP_PLACEHOLDER.test(match)\n ? match\n : `_${match.slice(1, -1)}_`,\n );\n };\n }\n}\n\n/**\n * Walks Nitro's resolved routeRules and stamps `x-analog-no-ssr: true` onto\n * any rule with `ssr: false`, and `x-analog-no-streaming: true` onto any rule\n * with `streaming: false`. Kept as response-header hints for downstream\n * consumers (CDN, edge logic); the actual SSR short-circuit happens inside\n * the SSR renderer virtual above, and the router falls back to a buffered\n * render when it sees the streaming hint.\n */\nexport function injectAnalogRouteRuleHeaders(nitro: Nitro): void {\n const routeRules = nitro.options.routeRules as\n | Record<\n string,\n {\n ssr?: boolean;\n streaming?: boolean;\n headers?: Record<string, string>;\n }\n >\n | undefined;\n if (!routeRules) return;\n\n for (const rule of Object.values(routeRules)) {\n if (rule?.ssr === false) {\n rule.headers = { ...rule.headers, 'x-analog-no-ssr': 'true' };\n }\n if (rule?.streaming === false) {\n rule.headers = { ...rule.headers, 'x-analog-no-streaming': 'true' };\n }\n }\n}\n\n/**\n * Builds the SSR service entry source. The wrapper imports the user's\n * `main.server.ts` Angular renderer and adapts it to the `{ fetch(req) }`\n * shape that nitro/vite's service mechanism expects.\n */\nfunction generateSsrEntryWrapper(\n entryServer: string,\n template: string,\n): string {\n return `\n// Import \\`serverFetch\\` from the root \\`nitro\\` entry rather than \\`nitro/app\\`.\n// The /app subpath creates a fresh \\`useNitroApp()\\` instance scoped to the\n// importing bundle, which in our setup is the standalone SSR vite bundle —\n// it has no route handlers, so every fetch 404s. The root entry instead\n// reads \\`globalThis.__nitro__.{default,prerender}\\`, which the surrounding\n// Nitro server (prerender pass or production runtime) has already\n// populated with the real app + handlers.\n// Set \\`ngServerMode\\` before the Angular renderer and its app config evaluate,\n// otherwise \\`provideClientHydration()\\` registers browser-only features such\n// as event replay on the server.\nimport ${JSON.stringify(SERVER_MODE_ID)};\nimport { serverFetch as nitroServerFetch } from 'nitro';\nimport { createFetch } from 'ofetch';\nimport renderer from ${JSON.stringify(entryServer)};\n\nconst TEMPLATE = ${JSON.stringify(template)};\n\nconst normalizeRequestPath = (url) =>\n url.replace(/\\\\/index\\\\.html(?=$|[?#])/, '/');\n\n// In-process fetch wired into Nitro's request pipeline. Angular's HttpClient\n// (via withFetch()) and Analog's injectLoad() call this during SSR/prerender\n// so they hit the running app's page-endpoint and API routes without going\n// through the network — the prerender pipeline doesn't have a listening\n// socket. Without this, every SSR data fetch ECONNREFUSEs and Angular's\n// router fails to resolve any data-bound route, producing an empty\n// <router-outlet/> in the prerendered HTML.\nconst ssrFetch = (resource, init) => {\n let url = typeof resource === 'string'\n ? resource\n : resource instanceof URL\n ? resource.href\n : resource.url;\n // Relative URLs from injectAPIPrefix() etc. need a host for Nitro's\n // Request constructor to accept them.\n if (typeof url === 'string' && url.startsWith('/')) {\n url = 'http://localhost' + url;\n }\n return nitroServerFetch(url, init);\n};\n\n// Wrap in ofetch so consumers that expect \\`$fetch.raw()\\` (the router's\n// request-context interceptor short-circuits SSR HttpClient calls through\n// \\`globalThis.$fetch.raw\\`) can call it. Set on globalThis so router code\n// running inside the Angular renderer can find it.\nconst ssrOFetch = createFetch({ fetch: ssrFetch });\nif (typeof globalThis.$fetch === 'undefined') {\n globalThis.$fetch = ssrOFetch;\n}\n\nexport default {\n async fetch(req) {\n const url = new URL(req.url);\n const requestPath = normalizeRequestPath(url.pathname);\n // Preserve the query string so Angular's router + injectQuery() and\n // server data loaders that read from req.url see the full path+query.\n const requestUrl = requestPath + url.search;\n\n if (req.headers.get('x-analog-no-ssr') === 'true') {\n return new Response(TEMPLATE, {\n status: 200,\n headers: { 'content-type': 'text/html; charset=utf-8' },\n });\n }\n\n const reqShim = {\n headers: Object.fromEntries(req.headers.entries()),\n url: requestUrl,\n originalUrl: requestUrl,\n connection: {},\n };\n\n try {\n const html = await renderer(requestUrl, TEMPLATE, {\n req: reqShim,\n // Pass the ofetch-wrapped fetch — INTERNAL_FETCH is consumed by the\n // router's request-context interceptor via \\`serverFetch.raw(...)\\`,\n // which is ofetch's response-shape API. Plain fetch lacks \\`.raw\\`\n // and throws TypeError during prerender/SSR.\n fetch: ssrOFetch,\n });\n return new Response(html, {\n status: 200,\n headers: { 'content-type': 'text/html; charset=utf-8' },\n });\n } catch (err) {\n console.error('[analog ssr]', err);\n return new Response(TEMPLATE, {\n status: 500,\n headers: { 'content-type': 'text/html; charset=utf-8' },\n });\n }\n },\n};\n`;\n}\n\nasync function wirePrerender(\n nitro: Nitro,\n options: Options,\n context: NitroPluginContext,\n apiPrefix: string,\n): Promise<void> {\n const prerender = options.prerender;\n if (!prerender && !options.i18n) return;\n\n const {\n routes: collected,\n sitemaps: routeSitemaps,\n routeSourceFiles,\n } = await collectRoutes(prerender?.routes, context, apiPrefix);\n\n const expanded = options.i18n\n ? expandRoutesWithLocales(collected, {\n defaultLocale: options.i18n.defaultLocale,\n locales: options.i18n.locales,\n })\n : collected;\n\n const nitroPrerender = (nitro.options.prerender ??= {}) as Record<\n string,\n any\n >;\n nitroPrerender.routes ??= [];\n nitroPrerender.routes.push(...expanded);\n if (prerender?.discover ?? false) {\n nitroPrerender.crawlLinks = true;\n }\n\n if (prerender?.postRenderingHooks?.length) {\n addPostRenderingHooks(nitro, prerender.postRenderingHooks);\n }\n\n if (Object.keys(routeSourceFiles).length > 0) {\n // Mirror the legacy `@analogjs/vite-plugin-nitro` behavior: after\n // prerender completes, write the route's source content alongside the\n // prerendered HTML at `<publicDir>/<route>.md`. Drives the\n // `outputSourceFile` option on both `PrerenderRouteConfig` (string path\n // to source markdown) and `PrerenderContentDir` (per-file callback).\n nitro.hooks.hook('prerender:done', async () => {\n const publicDir = resolve(nitro.options.output.publicDir);\n const { mkdirSync, writeFileSync } = await import('node:fs');\n const { dirname, join } = await import('node:path');\n for (const [route, content] of Object.entries(routeSourceFiles)) {\n const outputPath = join(publicDir, `${route}.md`);\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, content, 'utf8');\n }\n });\n }\n\n const sitemapConfig = prerender?.sitemap;\n if (sitemapConfig) {\n nitro.hooks.hook('prerender:done', async (result) => {\n const prerenderedRoutes = (result?.prerenderedRoutes ?? []).map(\n (r: PrerenderRoute) => r.route,\n );\n const publicDir = resolve(nitro.options.output.publicDir);\n await buildSitemap(\n {} as any,\n sitemapConfig,\n prerenderedRoutes,\n publicDir,\n routeSitemaps,\n { apiPrefix },\n );\n });\n }\n}\n\nasync function collectRoutes(\n routesInput: Options['prerender'] extends infer P\n ? P extends { routes?: infer R }\n ? R\n : never\n : never,\n context: NitroPluginContext,\n apiPrefix: string,\n): Promise<{\n routes: string[];\n sitemaps: Record<string, RouteSitemap>;\n routeSourceFiles: Record<string, string>;\n}> {\n const out: string[] = [];\n const sitemaps: Record<string, RouteSitemap> = {};\n const routeSourceFiles: Record<string, string> = {};\n\n if (!routesInput) return { routes: out, sitemaps, routeSourceFiles };\n\n const inputs = Array.isArray(routesInput)\n ? routesInput\n : typeof routesInput === 'function'\n ? await routesInput()\n : [];\n\n for (const entry of inputs) {\n if (!entry) continue;\n\n if (typeof entry === 'string') {\n out.push(entry);\n continue;\n }\n\n if ('contentDir' in entry) {\n const dir = entry as PrerenderContentDir;\n const files = getMatchingContentFilesWithFrontMatter(\n context.workspaceRoot,\n context.rootDir,\n dir.contentDir,\n !!dir.recursive,\n );\n for (const file of files) {\n const route = dir.transform(file);\n if (route === false) continue;\n out.push(route);\n if (dir.sitemap) {\n sitemaps[route] =\n typeof dir.sitemap === 'function'\n ? (\n dir.sitemap as (\n f: PrerenderContentFile,\n ) => PrerenderSitemapConfig\n )(file)\n : dir.sitemap;\n }\n if (dir.outputSourceFile) {\n const sourceContent = dir.outputSourceFile(file);\n if (typeof sourceContent === 'string') {\n routeSourceFiles[route] = sourceContent;\n }\n }\n }\n continue;\n }\n\n if ('route' in entry) {\n const cfg = entry as PrerenderRouteConfig;\n out.push(cfg.route);\n if (cfg.sitemap) {\n sitemaps[cfg.route] = cfg.sitemap;\n }\n if (cfg.outputSourceFile) {\n const sourcePath = resolve(\n context.workspaceRoot,\n context.rootDir,\n cfg.outputSourceFile,\n );\n if (existsSync(sourcePath)) {\n routeSourceFiles[cfg.route] = readFileSync(sourcePath, 'utf8');\n }\n }\n if (cfg.staticData) {\n // Mirror the legacy plugin: when staticData is requested, also\n // prerender the page's data-fetching endpoint so the JSON payload\n // is available statically.\n const prefix = apiPrefix.startsWith('/') ? apiPrefix : `/${apiPrefix}`;\n const route = cfg.route.startsWith('/') ? cfg.route : `/${cfg.route}`;\n out.push(`${prefix}/_analog/pages${route}`);\n }\n }\n }\n\n return { routes: out, sitemaps, routeSourceFiles };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiCA,IAAM,uBAAuB;;;;;;AAkB7B,SAAgB,kBAAkB,UAAmB,EAAE,EAAU;CAC/D,MAAM,gBACJ,QAAQ,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,KAAK;CAC5E,MAAM,aAAa;CACnB,MAAM,MAAM,QAAQ,OAAO;CAC3B,MAAM,YAAY,QAAQ,aAAa;CAEvC,IAAI,UAA8B;EAChC;EACA,SAAS;EACT;EACD;CACD,IAAI,qBAAqB;CACzB,IAAI;CACJ,IAAI,UAAU;CAGd,IAAI,UAAU;CACd,IAAI;CACJ,MAAM,+BAAe,IAAI,SAAwC;CAKjE,IAAI;CAEJ,SAAS,eAAe,aAA4C;EAClE,IAAI,QAAQ,aAAa,IAAI,YAAY;AACzC,MAAI,CAAC,OAAO;AAEV,WAAQ,QAAQ,QAAQ,YAAY,eAAe,MAAM,CAAC;AAC1D,gBAAa,IAAI,aAAa,MAAM;;AAEtC,SAAO;;CAGT,SAAS,eAAe,UAA8B;AAEpD,YAAU;GACR;GACA,SAAS,SAAS,eAHP,YAAY,QAAQ,KAAK,CAGE,IAAI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ACf,QAAI,IAAI,QACN,UAAS,SACP,OAAO,IAAI,YAAY,aAEjB,IAAI,QAGJ,KAAK,GACP,IAAI;AAEZ,QAAI,IAAI,kBAAkB;KACxB,MAAM,gBAAgB,IAAI,iBAAiB,KAAK;AAChD,SAAI,OAAO,kBAAkB,SAC3B,kBAAiB,SAAS;;;AAIhC;;AAGF,MAAI,WAAW,OAAO;GACpB,MAAM,MAAM;AACZ,OAAI,KAAK,IAAI,MAAM;AACnB,OAAI,IAAI,QACN,UAAS,IAAI,SAAS,IAAI;AAE5B,OAAI,IAAI,kBAAkB;IACxB,MAAM,aAAa,QACjB,QAAQ,eACR,QAAQ,SACR,IAAI,iBACL;AACD,QAAI,WAAW,WAAW,CACxB,kBAAiB,IAAI,SAAS,aAAa,YAAY,OAAO;;AAGlE,OAAI,IAAI,YAAY;IAIlB,MAAM,SAAS,UAAU,WAAW,IAAI,GAAG,YAAY,IAAI;IAC3D,MAAM,QAAQ,IAAI,MAAM,WAAW,IAAI,GAAG,IAAI,QAAQ,IAAI,IAAI;AAC9D,QAAI,KAAK,GAAG,OAAO,gBAAgB,QAAQ;;;;AAKjD,QAAO;EAAE,QAAQ;EAAK;EAAU;EAAkB"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export type GetServerFnHandlersArgs = {
|
|
2
|
+
workspaceRoot: string;
|
|
3
|
+
sourceRoot: string;
|
|
4
|
+
rootDir: string;
|
|
5
|
+
additionalServerFnDirs?: string[];
|
|
6
|
+
};
|
|
7
|
+
export type ServerFnHandlerModule = {
|
|
8
|
+
/** Absolute, normalized path to a discovered `*.server.ts` module. */
|
|
9
|
+
file: string;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Discovers the `*.server.ts` modules that may define server functions.
|
|
13
|
+
*
|
|
14
|
+
* Unlike page endpoints (one Nitro handler per file), server functions all
|
|
15
|
+
* share a single `/_analog/fn/:id` dispatch route. The discovered modules are
|
|
16
|
+
* imported for their registration side-effects — each `serverFn(...)` call
|
|
17
|
+
* registers itself into the server-side registry at import time — after which
|
|
18
|
+
* dispatch looks up the requested function by id.
|
|
19
|
+
*
|
|
20
|
+
* Scope is `<projectRoot>/<sourceRoot>/**\/*.server.ts` because the RFC allows a
|
|
21
|
+
* server function to live in any `.server.ts` module, including existing page
|
|
22
|
+
* server files. Only modules defining a server function that the client
|
|
23
|
+
* transform can rewrite participate.
|
|
24
|
+
* Angular SSR config (`app.config.server.ts`) is excluded — it is not a route or
|
|
25
|
+
* function module and must not be pulled into the dispatch bundle.
|
|
26
|
+
*
|
|
27
|
+
* @returns discovered modules, de-duplicated and sorted for deterministic output
|
|
28
|
+
*/
|
|
29
|
+
export declare function getServerFnHandlers({ workspaceRoot, sourceRoot, rootDir, additionalServerFnDirs }: GetServerFnHandlersArgs): ServerFnHandlerModule[];
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { normalizePath } from "vite";
|
|
4
|
+
import { globSync } from "tinyglobby";
|
|
5
|
+
import { parseSync } from "oxc-parser";
|
|
6
|
+
//#region packages/platform/src/lib/nitro/get-server-fn-handlers.ts
|
|
7
|
+
/**
|
|
8
|
+
* `*.server.ts` files that are matched by the glob but are never server-function
|
|
9
|
+
* hosts, so importing them for registration side-effects would be wrong.
|
|
10
|
+
*
|
|
11
|
+
* The SSR entries (`main.server.ts`, `main-cf.server.ts`, …) sit at the top of
|
|
12
|
+
* the source root and bootstrap the whole Angular application; importing one
|
|
13
|
+
* would pull the entire app into the dispatch bundle. They are matched by
|
|
14
|
+
* directory rather than by name so a page named `main.server.ts` still counts.
|
|
15
|
+
*/
|
|
16
|
+
var EXCLUDED_SERVER_FILES = [/\/app\.config\.server\.ts$/];
|
|
17
|
+
/**
|
|
18
|
+
* Discovers the `*.server.ts` modules that may define server functions.
|
|
19
|
+
*
|
|
20
|
+
* Unlike page endpoints (one Nitro handler per file), server functions all
|
|
21
|
+
* share a single `/_analog/fn/:id` dispatch route. The discovered modules are
|
|
22
|
+
* imported for their registration side-effects — each `serverFn(...)` call
|
|
23
|
+
* registers itself into the server-side registry at import time — after which
|
|
24
|
+
* dispatch looks up the requested function by id.
|
|
25
|
+
*
|
|
26
|
+
* Scope is `<projectRoot>/<sourceRoot>/**\/*.server.ts` because the RFC allows a
|
|
27
|
+
* server function to live in any `.server.ts` module, including existing page
|
|
28
|
+
* server files. Only modules defining a server function that the client
|
|
29
|
+
* transform can rewrite participate.
|
|
30
|
+
* Angular SSR config (`app.config.server.ts`) is excluded — it is not a route or
|
|
31
|
+
* function module and must not be pulled into the dispatch bundle.
|
|
32
|
+
*
|
|
33
|
+
* @returns discovered modules, de-duplicated and sorted for deterministic output
|
|
34
|
+
*/
|
|
35
|
+
function getServerFnHandlers({ workspaceRoot, sourceRoot, rootDir, additionalServerFnDirs }) {
|
|
36
|
+
const root = normalizePath(resolve(workspaceRoot, rootDir));
|
|
37
|
+
const files = globSync([`${root}/${sourceRoot}/**/*.server.ts`, ...(additionalServerFnDirs || []).map((dir) => `${workspaceRoot}${dir}/**/*.server.ts`)], {
|
|
38
|
+
dot: true,
|
|
39
|
+
absolute: true
|
|
40
|
+
}).map((file) => normalizePath(file));
|
|
41
|
+
const sourceRootDir = `${root}/${sourceRoot}/`;
|
|
42
|
+
const seen = /* @__PURE__ */ new Set();
|
|
43
|
+
return files.filter((file) => !EXCLUDED_SERVER_FILES.some((re) => re.test(file))).filter((file) => !file.startsWith(sourceRootDir) || file.slice(sourceRootDir.length).includes("/")).filter((file) => seen.has(file) ? false : (seen.add(file), true)).sort().filter(definesServerFn).map((file) => ({ file }));
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Match the client scrub's supported server-function declaration shape. The
|
|
47
|
+
* scrub deliberately falls back to the conventional `serverFn` name when the
|
|
48
|
+
* function is re-exported through a local barrel, so discovery must make the
|
|
49
|
+
* same choice or the browser receives a proxy without a dispatch route.
|
|
50
|
+
*/
|
|
51
|
+
function definesServerFn(file) {
|
|
52
|
+
const code = readFileSync(file, "utf8");
|
|
53
|
+
if (!code.includes("serverFn")) return false;
|
|
54
|
+
const { program } = parseSync(file, code);
|
|
55
|
+
const localNames = /* @__PURE__ */ new Set();
|
|
56
|
+
for (const node of program.body) {
|
|
57
|
+
if (node.type !== "ImportDeclaration" || node.source.value !== "@analogjs/router/server") continue;
|
|
58
|
+
for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier" && (specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value) === "serverFn") localNames.add(specifier.local.name);
|
|
59
|
+
}
|
|
60
|
+
if (localNames.size === 0) localNames.add("serverFn");
|
|
61
|
+
return program.body.some((node) => node.type === "ExportNamedDeclaration" && node.declaration?.type === "VariableDeclaration" && node.declaration.declarations.some((declarator) => declarator.id?.type === "Identifier" && declarator.init?.type === "CallExpression" && declarator.init.callee?.type === "Identifier" && localNames.has(declarator.init.callee.name)));
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { getServerFnHandlers };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=get-server-fn-handlers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-server-fn-handlers.js","names":[],"sources":["../../../../src/lib/nitro/get-server-fn-handlers.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { parseSync } from 'oxc-parser';\nimport { resolve } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport { normalizePath } from 'vite';\n\nexport type GetServerFnHandlersArgs = {\n workspaceRoot: string;\n sourceRoot: string;\n rootDir: string;\n additionalServerFnDirs?: string[];\n};\n\nexport type ServerFnHandlerModule = {\n /** Absolute, normalized path to a discovered `*.server.ts` module. */\n file: string;\n};\n\n/**\n * `*.server.ts` files that are matched by the glob but are never server-function\n * hosts, so importing them for registration side-effects would be wrong.\n *\n * The SSR entries (`main.server.ts`, `main-cf.server.ts`, …) sit at the top of\n * the source root and bootstrap the whole Angular application; importing one\n * would pull the entire app into the dispatch bundle. They are matched by\n * directory rather than by name so a page named `main.server.ts` still counts.\n */\nconst EXCLUDED_SERVER_FILES: RegExp[] = [/\\/app\\.config\\.server\\.ts$/];\n\n/**\n * Discovers the `*.server.ts` modules that may define server functions.\n *\n * Unlike page endpoints (one Nitro handler per file), server functions all\n * share a single `/_analog/fn/:id` dispatch route. The discovered modules are\n * imported for their registration side-effects — each `serverFn(...)` call\n * registers itself into the server-side registry at import time — after which\n * dispatch looks up the requested function by id.\n *\n * Scope is `<projectRoot>/<sourceRoot>/**\\/*.server.ts` because the RFC allows a\n * server function to live in any `.server.ts` module, including existing page\n * server files. Only modules defining a server function that the client\n * transform can rewrite participate.\n * Angular SSR config (`app.config.server.ts`) is excluded — it is not a route or\n * function module and must not be pulled into the dispatch bundle.\n *\n * @returns discovered modules, de-duplicated and sorted for deterministic output\n */\nexport function getServerFnHandlers({\n workspaceRoot,\n sourceRoot,\n rootDir,\n additionalServerFnDirs,\n}: GetServerFnHandlersArgs): ServerFnHandlerModule[] {\n const root = normalizePath(resolve(workspaceRoot, rootDir));\n\n const files = globSync(\n [\n `${root}/${sourceRoot}/**/*.server.ts`,\n ...(additionalServerFnDirs || []).map(\n (dir) => `${workspaceRoot}${dir}/**/*.server.ts`,\n ),\n ],\n { dot: true, absolute: true },\n ).map((file) => normalizePath(file));\n\n const sourceRootDir = `${root}/${sourceRoot}/`;\n const seen = new Set<string>();\n return files\n .filter((file) => !EXCLUDED_SERVER_FILES.some((re) => re.test(file)))\n .filter(\n (file) =>\n !file.startsWith(sourceRootDir) ||\n file.slice(sourceRootDir.length).includes('/'),\n )\n .filter((file) => (seen.has(file) ? false : (seen.add(file), true)))\n .sort()\n .filter(definesServerFn)\n .map((file) => ({ file }));\n}\n\n/**\n * Match the client scrub's supported server-function declaration shape. The\n * scrub deliberately falls back to the conventional `serverFn` name when the\n * function is re-exported through a local barrel, so discovery must make the\n * same choice or the browser receives a proxy without a dispatch route.\n */\nfunction definesServerFn(file: string): boolean {\n const code = readFileSync(file, 'utf8');\n if (!code.includes('serverFn')) return false;\n\n const { program } = parseSync(file, code);\n const localNames = new Set<string>();\n for (const node of program.body) {\n if (\n node.type !== 'ImportDeclaration' ||\n node.source.value !== '@analogjs/router/server'\n ) {\n continue;\n }\n for (const specifier of node.specifiers) {\n if (\n specifier.type === 'ImportSpecifier' &&\n (specifier.imported.type === 'Identifier'\n ? specifier.imported.name\n : specifier.imported.value) === 'serverFn'\n ) {\n localNames.add(specifier.local.name);\n }\n }\n }\n if (localNames.size === 0) localNames.add('serverFn');\n\n return program.body.some(\n (node) =>\n node.type === 'ExportNamedDeclaration' &&\n node.declaration?.type === 'VariableDeclaration' &&\n node.declaration.declarations.some(\n (declarator) =>\n declarator.id?.type === 'Identifier' &&\n declarator.init?.type === 'CallExpression' &&\n declarator.init.callee?.type === 'Identifier' &&\n localNames.has(declarator.init.callee.name),\n ),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,IAAM,wBAAkC,CAAC,6BAA6B;;;;;;;;;;;;;;;;;;;AAoBtE,SAAgB,oBAAoB,EAClC,eACA,YACA,SACA,0BACmD;CACnD,MAAM,OAAO,cAAc,QAAQ,eAAe,QAAQ,CAAC;CAE3D,MAAM,QAAQ,SACZ,CACE,GAAG,KAAK,GAAG,WAAW,kBACtB,IAAI,0BAA0B,EAAE,EAAE,KAC/B,QAAQ,GAAG,gBAAgB,IAAI,iBACjC,CACF,EACD;EAAE,KAAK;EAAM,UAAU;EAAM,CAC9B,CAAC,KAAK,SAAS,cAAc,KAAK,CAAC;CAEpC,MAAM,gBAAgB,GAAG,KAAK,GAAG,WAAW;CAC5C,MAAM,uBAAO,IAAI,KAAa;AAC9B,QAAO,MACJ,QAAQ,SAAS,CAAC,sBAAsB,MAAM,OAAO,GAAG,KAAK,KAAK,CAAC,CAAC,CACpE,QACE,SACC,CAAC,KAAK,WAAW,cAAc,IAC/B,KAAK,MAAM,cAAc,OAAO,CAAC,SAAS,IAAI,CACjD,CACA,QAAQ,SAAU,KAAK,IAAI,KAAK,GAAG,SAAS,KAAK,IAAI,KAAK,EAAE,MAAO,CACnE,MAAM,CACN,OAAO,gBAAgB,CACvB,KAAK,UAAU,EAAE,MAAM,EAAE;;;;;;;;AAS9B,SAAS,gBAAgB,MAAuB;CAC9C,MAAM,OAAO,aAAa,MAAM,OAAO;AACvC,KAAI,CAAC,KAAK,SAAS,WAAW,CAAE,QAAO;CAEvC,MAAM,EAAE,YAAY,UAAU,MAAM,KAAK;CACzC,MAAM,6BAAa,IAAI,KAAa;AACpC,MAAK,MAAM,QAAQ,QAAQ,MAAM;AAC/B,MACE,KAAK,SAAS,uBACd,KAAK,OAAO,UAAU,0BAEtB;AAEF,OAAK,MAAM,aAAa,KAAK,WAC3B,KACE,UAAU,SAAS,sBAClB,UAAU,SAAS,SAAS,eACzB,UAAU,SAAS,OACnB,UAAU,SAAS,WAAW,WAElC,YAAW,IAAI,UAAU,MAAM,KAAK;;AAI1C,KAAI,WAAW,SAAS,EAAG,YAAW,IAAI,WAAW;AAErD,QAAO,QAAQ,KAAK,MACjB,SACC,KAAK,SAAS,4BACd,KAAK,aAAa,SAAS,yBAC3B,KAAK,YAAY,aAAa,MAC3B,eACC,WAAW,IAAI,SAAS,gBACxB,WAAW,MAAM,SAAS,oBAC1B,WAAW,KAAK,QAAQ,SAAS,gBACjC,WAAW,IAAI,WAAW,KAAK,OAAO,KAAK,CAC9C,CACJ"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { NitroEventHandler } from "nitro/types";
|
|
2
|
+
import type { ServerFnHandlerModule } from "./get-server-fn-handlers.js";
|
|
3
|
+
/**
|
|
4
|
+
* Nitro virtual-module id for the generated server-function dispatch handler.
|
|
5
|
+
* Referenced from `nitroConfig.handlers` and provided via `nitroConfig.virtual`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const SERVER_FN_DISPATCH_VIRTUAL = "#ANALOG_SERVER_FN_DISPATCH";
|
|
8
|
+
/** The single transport route all server functions dispatch through. */
|
|
9
|
+
export declare const SERVER_FN_DISPATCH_ROUTE = "/_analog/fn/:id";
|
|
10
|
+
/** URL prefix of that route, for matching requests before the id is known. */
|
|
11
|
+
export declare const SERVER_FN_DISPATCH_PREFIX = "/_analog/fn/";
|
|
12
|
+
/**
|
|
13
|
+
* The Nitro handler registration for the server-function dispatch route.
|
|
14
|
+
* Unlike page endpoints (one handler per file), every server function shares
|
|
15
|
+
* this one `/_analog/fn/:id` route; the id selects the function at runtime.
|
|
16
|
+
*
|
|
17
|
+
* The route is fixed and NOT `/api`-prefixed: client proxies always call the
|
|
18
|
+
* absolute `/_analog/fn/:id` URL, so an `/api` prefix (as page endpoints use)
|
|
19
|
+
* would leave the handler unreachable in apps that have an API directory.
|
|
20
|
+
*/
|
|
21
|
+
export declare function getServerFnDispatchHandler(): NitroEventHandler;
|
|
22
|
+
export type BuildServerFnDispatchModuleArgs = {
|
|
23
|
+
/** Discovered `*.server.ts` modules, imported for registration side-effects. */
|
|
24
|
+
modules: ServerFnHandlerModule[];
|
|
25
|
+
/**
|
|
26
|
+
* Absolute path to the app's server config module (`app.config.server.ts`),
|
|
27
|
+
* which exports the `ApplicationConfig` (as `config`) that `main.server.ts`
|
|
28
|
+
* renders with. Handlers bootstrap against it, so they see the same DI the
|
|
29
|
+
* app configured. When absent, handlers run with only `providedIn: 'root'`.
|
|
30
|
+
*/
|
|
31
|
+
appConfigModule?: string;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Generates the source of the Nitro dispatch handler.
|
|
35
|
+
*
|
|
36
|
+
* The handler imports every discovered `*.server.ts` module so each
|
|
37
|
+
* `serverFn(...)` registers itself, imports the app's server config, then on
|
|
38
|
+
* each request looks up the function by id and runs it via `dispatchServerFn` —
|
|
39
|
+
* the same call path the validation harnesses exercise.
|
|
40
|
+
*/
|
|
41
|
+
export declare function buildServerFnDispatchModule({ modules, appConfigModule }: BuildServerFnDispatchModuleArgs): string;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { normalizePath } from "vite";
|
|
2
|
+
//#region packages/platform/src/lib/nitro/server-fn-endpoints.ts
|
|
3
|
+
/**
|
|
4
|
+
* Nitro virtual-module id for the generated server-function dispatch handler.
|
|
5
|
+
* Referenced from `nitroConfig.handlers` and provided via `nitroConfig.virtual`.
|
|
6
|
+
*/
|
|
7
|
+
var SERVER_FN_DISPATCH_VIRTUAL = "#ANALOG_SERVER_FN_DISPATCH";
|
|
8
|
+
/** The single transport route all server functions dispatch through. */
|
|
9
|
+
var SERVER_FN_DISPATCH_ROUTE = "/_analog/fn/:id";
|
|
10
|
+
/**
|
|
11
|
+
* The Nitro handler registration for the server-function dispatch route.
|
|
12
|
+
* Unlike page endpoints (one handler per file), every server function shares
|
|
13
|
+
* this one `/_analog/fn/:id` route; the id selects the function at runtime.
|
|
14
|
+
*
|
|
15
|
+
* The route is fixed and NOT `/api`-prefixed: client proxies always call the
|
|
16
|
+
* absolute `/_analog/fn/:id` URL, so an `/api` prefix (as page endpoints use)
|
|
17
|
+
* would leave the handler unreachable in apps that have an API directory.
|
|
18
|
+
*/
|
|
19
|
+
function getServerFnDispatchHandler() {
|
|
20
|
+
return {
|
|
21
|
+
route: SERVER_FN_DISPATCH_ROUTE,
|
|
22
|
+
handler: SERVER_FN_DISPATCH_VIRTUAL,
|
|
23
|
+
lazy: true
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Generates the source of the Nitro dispatch handler.
|
|
28
|
+
*
|
|
29
|
+
* The handler imports every discovered `*.server.ts` module so each
|
|
30
|
+
* `serverFn(...)` registers itself, imports the app's server config, then on
|
|
31
|
+
* each request looks up the function by id and runs it via `dispatchServerFn` —
|
|
32
|
+
* the same call path the validation harnesses exercise.
|
|
33
|
+
*/
|
|
34
|
+
function buildServerFnDispatchModule({ modules, appConfigModule }) {
|
|
35
|
+
return `import '@angular/compiler';
|
|
36
|
+
import 'zone.js/node';
|
|
37
|
+
import '@angular/platform-server/init';
|
|
38
|
+
import { createServerFnAppInjector, createServerFnEventHandler } from '@analogjs/router/server';
|
|
39
|
+
|
|
40
|
+
// Discovered server-function modules (registration side-effects).
|
|
41
|
+
${modules.map((m) => `import ${JSON.stringify(normalizePath(m.file))};`).join("\n")}
|
|
42
|
+
|
|
43
|
+
${appConfigModule ? `import { config as serverFnAppConfig } from ${JSON.stringify(normalizePath(appConfigModule))};` : `const serverFnAppConfig = { providers: [] };`}
|
|
44
|
+
|
|
45
|
+
// Bootstrapped once from the app's own server config, so a handler resolves the
|
|
46
|
+
// same DI as an SSR render (\`providedIn: 'root'\` and listed providers alike).
|
|
47
|
+
// No component is bootstrapped, so nothing renders and the router never
|
|
48
|
+
// navigates. Only REQUEST/RESPONSE are rebuilt per call.
|
|
49
|
+
export default createServerFnEventHandler(
|
|
50
|
+
createServerFnAppInjector(serverFnAppConfig),
|
|
51
|
+
);
|
|
52
|
+
`;
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
export { SERVER_FN_DISPATCH_VIRTUAL, buildServerFnDispatchModule, getServerFnDispatchHandler };
|
|
56
|
+
|
|
57
|
+
//# sourceMappingURL=server-fn-endpoints.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-fn-endpoints.js","names":[],"sources":["../../../../src/lib/nitro/server-fn-endpoints.ts"],"sourcesContent":["import type { NitroEventHandler } from 'nitro/types';\nimport { normalizePath } from 'vite';\n\nimport type { ServerFnHandlerModule } from './get-server-fn-handlers.js';\n\n/**\n * Nitro virtual-module id for the generated server-function dispatch handler.\n * Referenced from `nitroConfig.handlers` and provided via `nitroConfig.virtual`.\n */\nexport const SERVER_FN_DISPATCH_VIRTUAL = '#ANALOG_SERVER_FN_DISPATCH';\n\n/** The single transport route all server functions dispatch through. */\nexport const SERVER_FN_DISPATCH_ROUTE = '/_analog/fn/:id';\n\n/** URL prefix of that route, for matching requests before the id is known. */\nexport const SERVER_FN_DISPATCH_PREFIX = '/_analog/fn/';\n\n/**\n * The Nitro handler registration for the server-function dispatch route.\n * Unlike page endpoints (one handler per file), every server function shares\n * this one `/_analog/fn/:id` route; the id selects the function at runtime.\n *\n * The route is fixed and NOT `/api`-prefixed: client proxies always call the\n * absolute `/_analog/fn/:id` URL, so an `/api` prefix (as page endpoints use)\n * would leave the handler unreachable in apps that have an API directory.\n */\nexport function getServerFnDispatchHandler(): NitroEventHandler {\n return {\n route: SERVER_FN_DISPATCH_ROUTE,\n handler: SERVER_FN_DISPATCH_VIRTUAL,\n lazy: true,\n };\n}\n\nexport type BuildServerFnDispatchModuleArgs = {\n /** Discovered `*.server.ts` modules, imported for registration side-effects. */\n modules: ServerFnHandlerModule[];\n /**\n * Absolute path to the app's server config module (`app.config.server.ts`),\n * which exports the `ApplicationConfig` (as `config`) that `main.server.ts`\n * renders with. Handlers bootstrap against it, so they see the same DI the\n * app configured. When absent, handlers run with only `providedIn: 'root'`.\n */\n appConfigModule?: string;\n};\n\n/**\n * Generates the source of the Nitro dispatch handler.\n *\n * The handler imports every discovered `*.server.ts` module so each\n * `serverFn(...)` registers itself, imports the app's server config, then on\n * each request looks up the function by id and runs it via `dispatchServerFn` —\n * the same call path the validation harnesses exercise.\n */\nexport function buildServerFnDispatchModule({\n modules,\n appConfigModule,\n}: BuildServerFnDispatchModuleArgs): string {\n const registrationImports = modules\n .map((m) => `import ${JSON.stringify(normalizePath(m.file))};`)\n .join('\\n');\n\n // Bootstrap against the app's own server config so a handler resolves exactly\n // the services, tokens, and interceptors the app configured — one config, no\n // second provider list. Fall back to an empty config when the app has none.\n const appConfig = appConfigModule\n ? `import { config as serverFnAppConfig } from ${JSON.stringify(\n normalizePath(appConfigModule),\n )};`\n : `const serverFnAppConfig = { providers: [] };`;\n\n // `@analogjs/router/server` is a partially-compiled Angular library, and this\n // module is bundled by Nitro rather than by the app's Angular pipeline, so the\n // linker never runs over it. Loading the compiler gives it the JIT fallback.\n // `zone.js` and the server platform init match the SSR entry, so bootstrapping\n // the app injector below runs in the same environment a render would.\n //\n // The transport itself — id decoding, the malformed-body contract, dispatch,\n // and response writing — lives in `createServerFnEventHandler`, so this module\n // is only wiring: bootstrap the app injector from the app's server config, and\n // hand it to that handler.\n return `import '@angular/compiler';\nimport 'zone.js/node';\nimport '@angular/platform-server/init';\nimport { createServerFnAppInjector, createServerFnEventHandler } from '@analogjs/router/server';\n\n// Discovered server-function modules (registration side-effects).\n${registrationImports}\n\n${appConfig}\n\n// Bootstrapped once from the app's own server config, so a handler resolves the\n// same DI as an SSR render (\\`providedIn: 'root'\\` and listed providers alike).\n// No component is bootstrapped, so nothing renders and the router never\n// navigates. Only REQUEST/RESPONSE are rebuilt per call.\nexport default createServerFnEventHandler(\n createServerFnAppInjector(serverFnAppConfig),\n);\n`;\n}\n"],"mappings":";;;;;;AASA,IAAa,6BAA6B;;AAG1C,IAAa,2BAA2B;;;;;;;;;;AAcxC,SAAgB,6BAAgD;AAC9D,QAAO;EACL,OAAO;EACP,SAAS;EACT,MAAM;EACP;;;;;;;;;;AAuBH,SAAgB,4BAA4B,EAC1C,SACA,mBAC0C;AAwB1C,QAAO;;;;;;EAvBqB,QACzB,KAAK,MAAM,UAAU,KAAK,UAAU,cAAc,EAAE,KAAK,CAAC,CAAC,GAAG,CAC9D,KAAK,KAAK,CA2BO;;EAtBF,kBACd,+CAA+C,KAAK,UAClD,cAAc,gBAAgB,CAC/B,CAAC,KACF,+CAoBM"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { defineEventHandler } from 'h3';
|
|
2
2
|
|
|
3
|
-
export default
|
|
3
|
+
export default defineEventHandler(() => ({ message: 'Hello World' }));
|
package/src/lib/nx-plugin/src/generators/app/files/template-angular/vite.config.ts__template__
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/// <reference types="vitest" />
|
|
2
2
|
|
|
3
3
|
import analog from '@analogjs/platform';
|
|
4
|
+
import angular from '@analogjs/vite-plugin-angular';
|
|
5
|
+
import nitro from '@analogjs/vite-plugin-nitro';
|
|
4
6
|
import { defineConfig } from 'vite';
|
|
5
7
|
<% if (addTailwind) { %>
|
|
6
8
|
import tailwindcss from '@tailwindcss/vite';
|
|
@@ -23,6 +25,8 @@ export default defineConfig(({ mode }) => {
|
|
|
23
25
|
},
|
|
24
26
|
plugins: [
|
|
25
27
|
analog(),
|
|
28
|
+
angular(),
|
|
29
|
+
nitro(),
|
|
26
30
|
<% if (addTailwind) { %>
|
|
27
31
|
tailwindcss(),
|
|
28
32
|
<% } %>
|
|
@@ -72,6 +72,11 @@ async function appGenerator(tree, options) {
|
|
|
72
72
|
}, {});
|
|
73
73
|
(0, _nx_devkit.updateJson)(tree, "/package.json", (json) => {
|
|
74
74
|
json.dependencies["@angular/platform-server"] = `~${angularVersion}`;
|
|
75
|
+
json.overrides = {
|
|
76
|
+
...json.overrides,
|
|
77
|
+
vite: "$vite",
|
|
78
|
+
vitest: "$vitest"
|
|
79
|
+
};
|
|
75
80
|
return json;
|
|
76
81
|
});
|
|
77
82
|
require_update_index_html.updateIndex(tree, normalizedOptions.analogAppName);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generator.js","names":[],"sources":["../../../../../../../../nx-plugin/src/generators/app/generator.ts"],"sourcesContent":["import {\n formatFiles,\n getWorkspaceLayout,\n installPackagesTask,\n names,\n offsetFromRoot as determineOffsetFromRoot,\n stripIndents,\n Tree,\n addDependenciesToPackageJson,\n updateJson,\n} from '@nx/devkit';\nimport { wrapAngularDevkitSchematic } from '@nx/devkit/ngcli-adapter';\nimport { AnalogNxApplicationGeneratorOptions } from './schema';\nimport { major, coerce } from 'semver';\nimport { getInstalledPackageVersion } from '../../utils/version-utils';\nimport { addHomePage } from './lib/add-home-page';\nimport {\n belowMinimumSupportedNxVersion,\n belowMinimumSupportedOxlintNxVersion,\n MINIMUM_SUPPORTED_OXLINT_NX_VERSION,\n} from './versions/minimum-supported-versions';\nimport { addAngularApp } from './lib/add-angular-app';\nimport setupAnalogGenerator from '../init/generator';\nimport { addFiles } from './lib/add-files';\nimport { addAgentContext } from './lib/add-agent-context';\nimport { addTailwindConfig } from './lib/add-tailwind-config';\nimport { cleanupFiles } from './lib/cleanup-files';\nimport { addAnalogProjectConfig } from './lib/add-analog-project-config';\nimport { updateIndex } from './lib/update-index-html';\n\nexport interface NormalizedOptions\n extends AnalogNxApplicationGeneratorOptions, ReturnType<typeof names> {\n projectName: string;\n projectRoot: string;\n projectDirectory: string;\n parsedTags: string[];\n offsetFromRoot: string;\n appsDir: string;\n nxPackageNamespace: string;\n isNx: boolean;\n}\n\nfunction normalizeOptions(\n tree: Tree,\n options: AnalogNxApplicationGeneratorOptions,\n): NormalizedOptions {\n const isNx = tree.exists('/nx.json');\n const appsDir = isNx ? getWorkspaceLayout(tree).appsDir : 'projects';\n const allNames = names(options.analogAppName);\n const projectDirectory = allNames.fileName;\n const projectName = projectDirectory.replace(new RegExp('/', 'g'), '-');\n const projectRoot = `${appsDir}/${projectDirectory}`;\n const parsedTags = options.tags\n ? options.tags.split(',').map((s) => s.trim())\n : [];\n const offsetFromRoot = determineOffsetFromRoot(projectRoot);\n const nxPackageNamespace = '@nx';\n const addTailwind = options.addTailwind ?? true;\n\n return {\n ...options,\n ...allNames,\n projectName,\n projectRoot,\n projectDirectory,\n parsedTags,\n offsetFromRoot,\n appsDir,\n nxPackageNamespace,\n addTailwind,\n isNx,\n };\n}\n\nasync function appGenerator(\n tree: Tree,\n options: AnalogNxApplicationGeneratorOptions,\n): Promise<() => void> {\n const nxVersion = getInstalledPackageVersion(tree, 'nx');\n\n if (nxVersion && belowMinimumSupportedNxVersion(nxVersion)) {\n throw new Error(\n stripIndents`Nx v17.0.0 or newer is required to install Analog`,\n );\n }\n\n if (options.linter === 'oxlint') {\n if (!nxVersion) {\n throw new Error(\n stripIndents`The oxlint linter is only supported in Nx workspaces`,\n );\n }\n if (belowMinimumSupportedOxlintNxVersion(nxVersion)) {\n throw new Error(\n stripIndents`Nx v${MINIMUM_SUPPORTED_OXLINT_NX_VERSION} or newer is required to use the oxlint linter`,\n );\n }\n }\n\n const normalizedOptions = normalizeOptions(tree, options);\n\n if (nxVersion) {\n await addAngularApp(tree, normalizedOptions);\n } else {\n const angularAppSchematic = wrapAngularDevkitSchematic(\n '@schematics/angular',\n 'application',\n );\n await angularAppSchematic(tree, {\n projectRoot: normalizedOptions.projectRoot,\n name: normalizedOptions.analogAppName,\n });\n addAnalogProjectConfig(\n tree,\n normalizedOptions.projectRoot,\n normalizedOptions.projectName,\n normalizedOptions.parsedTags,\n normalizedOptions.name,\n normalizedOptions.appsDir,\n normalizedOptions.nxPackageNamespace,\n );\n }\n\n await setupAnalogGenerator(tree, {\n project: normalizedOptions.analogAppName,\n vitest: true,\n });\n\n const angularVersion = getInstalledPackageVersion(tree, '@angular/core');\n const coercedAngularVersion = coerce(angularVersion ?? '');\n if (!coercedAngularVersion) {\n throw new Error('Could not determine installed Angular version.');\n }\n const majorAngularVersion = major(coercedAngularVersion);\n addFiles(tree, normalizedOptions, majorAngularVersion);\n addDependenciesToPackageJson(\n tree,\n {\n 'front-matter': '^4.0.2',\n marked: '^18.0.0',\n mermaid: '^10.2.4',\n prismjs: '^1.29.0',\n },\n {},\n );\n\n updateJson<{
|
|
1
|
+
{"version":3,"file":"generator.js","names":[],"sources":["../../../../../../../../nx-plugin/src/generators/app/generator.ts"],"sourcesContent":["import {\n formatFiles,\n getWorkspaceLayout,\n installPackagesTask,\n names,\n offsetFromRoot as determineOffsetFromRoot,\n stripIndents,\n Tree,\n addDependenciesToPackageJson,\n updateJson,\n} from '@nx/devkit';\nimport { wrapAngularDevkitSchematic } from '@nx/devkit/ngcli-adapter';\nimport { AnalogNxApplicationGeneratorOptions } from './schema';\nimport { major, coerce } from 'semver';\nimport { getInstalledPackageVersion } from '../../utils/version-utils';\nimport { addHomePage } from './lib/add-home-page';\nimport {\n belowMinimumSupportedNxVersion,\n belowMinimumSupportedOxlintNxVersion,\n MINIMUM_SUPPORTED_OXLINT_NX_VERSION,\n} from './versions/minimum-supported-versions';\nimport { addAngularApp } from './lib/add-angular-app';\nimport setupAnalogGenerator from '../init/generator';\nimport { addFiles } from './lib/add-files';\nimport { addAgentContext } from './lib/add-agent-context';\nimport { addTailwindConfig } from './lib/add-tailwind-config';\nimport { cleanupFiles } from './lib/cleanup-files';\nimport { addAnalogProjectConfig } from './lib/add-analog-project-config';\nimport { updateIndex } from './lib/update-index-html';\n\nexport interface NormalizedOptions\n extends AnalogNxApplicationGeneratorOptions, ReturnType<typeof names> {\n projectName: string;\n projectRoot: string;\n projectDirectory: string;\n parsedTags: string[];\n offsetFromRoot: string;\n appsDir: string;\n nxPackageNamespace: string;\n isNx: boolean;\n}\n\nfunction normalizeOptions(\n tree: Tree,\n options: AnalogNxApplicationGeneratorOptions,\n): NormalizedOptions {\n const isNx = tree.exists('/nx.json');\n const appsDir = isNx ? getWorkspaceLayout(tree).appsDir : 'projects';\n const allNames = names(options.analogAppName);\n const projectDirectory = allNames.fileName;\n const projectName = projectDirectory.replace(new RegExp('/', 'g'), '-');\n const projectRoot = `${appsDir}/${projectDirectory}`;\n const parsedTags = options.tags\n ? options.tags.split(',').map((s) => s.trim())\n : [];\n const offsetFromRoot = determineOffsetFromRoot(projectRoot);\n const nxPackageNamespace = '@nx';\n const addTailwind = options.addTailwind ?? true;\n\n return {\n ...options,\n ...allNames,\n projectName,\n projectRoot,\n projectDirectory,\n parsedTags,\n offsetFromRoot,\n appsDir,\n nxPackageNamespace,\n addTailwind,\n isNx,\n };\n}\n\nasync function appGenerator(\n tree: Tree,\n options: AnalogNxApplicationGeneratorOptions,\n): Promise<() => void> {\n const nxVersion = getInstalledPackageVersion(tree, 'nx');\n\n if (nxVersion && belowMinimumSupportedNxVersion(nxVersion)) {\n throw new Error(\n stripIndents`Nx v17.0.0 or newer is required to install Analog`,\n );\n }\n\n if (options.linter === 'oxlint') {\n if (!nxVersion) {\n throw new Error(\n stripIndents`The oxlint linter is only supported in Nx workspaces`,\n );\n }\n if (belowMinimumSupportedOxlintNxVersion(nxVersion)) {\n throw new Error(\n stripIndents`Nx v${MINIMUM_SUPPORTED_OXLINT_NX_VERSION} or newer is required to use the oxlint linter`,\n );\n }\n }\n\n const normalizedOptions = normalizeOptions(tree, options);\n\n if (nxVersion) {\n await addAngularApp(tree, normalizedOptions);\n } else {\n const angularAppSchematic = wrapAngularDevkitSchematic(\n '@schematics/angular',\n 'application',\n );\n await angularAppSchematic(tree, {\n projectRoot: normalizedOptions.projectRoot,\n name: normalizedOptions.analogAppName,\n });\n addAnalogProjectConfig(\n tree,\n normalizedOptions.projectRoot,\n normalizedOptions.projectName,\n normalizedOptions.parsedTags,\n normalizedOptions.name,\n normalizedOptions.appsDir,\n normalizedOptions.nxPackageNamespace,\n );\n }\n\n await setupAnalogGenerator(tree, {\n project: normalizedOptions.analogAppName,\n vitest: true,\n });\n\n const angularVersion = getInstalledPackageVersion(tree, '@angular/core');\n const coercedAngularVersion = coerce(angularVersion ?? '');\n if (!coercedAngularVersion) {\n throw new Error('Could not determine installed Angular version.');\n }\n const majorAngularVersion = major(coercedAngularVersion);\n addFiles(tree, normalizedOptions, majorAngularVersion);\n addDependenciesToPackageJson(\n tree,\n {\n 'front-matter': '^4.0.2',\n marked: '^18.0.0',\n mermaid: '^10.2.4',\n prismjs: '^1.29.0',\n },\n {},\n );\n\n updateJson<{\n dependencies: Record<string, string>;\n overrides?: Record<string, unknown>;\n }>(tree, '/package.json', (json) => {\n json.dependencies['@angular/platform-server'] = `~${angularVersion}`;\n json.overrides = {\n ...json.overrides,\n vite: '$vite',\n vitest: '$vitest',\n };\n\n return json;\n });\n\n updateIndex(tree, normalizedOptions.analogAppName);\n\n if (normalizedOptions.addTailwind) {\n await addTailwindConfig(tree, normalizedOptions.projectName);\n }\n\n addHomePage(tree, normalizedOptions, majorAngularVersion);\n\n if (!normalizedOptions.skipAgentContext) {\n addAgentContext(tree, normalizedOptions.projectRoot);\n }\n\n cleanupFiles(tree, normalizedOptions);\n\n if (!normalizedOptions.skipFormat) {\n await formatFiles(tree);\n }\n\n return () => {\n installPackagesTask(tree);\n };\n}\n\nexport default appGenerator;\n"],"mappings":";;;;;;;;;;;;;;;;AA0CA,SAAS,iBACP,MACA,SACmB;CACnB,MAAM,OAAO,KAAK,OAAO,WAAW;CACpC,MAAM,UAAU,QAAA,GAAA,WAAA,oBAA0B,KAAK,CAAC,UAAU;CAC1D,MAAM,YAAA,GAAA,WAAA,OAAiB,QAAQ,cAAc;CAC7C,MAAM,mBAAmB,SAAS;CAClC,MAAM,cAAc,iBAAiB,wBAAQ,IAAI,OAAO,KAAK,IAAI,EAAE,IAAI;CACvE,MAAM,cAAc,GAAG,QAAQ,GAAG;CAClC,MAAM,aAAa,QAAQ,OACvB,QAAQ,KAAK,MAAM,IAAI,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC,GAC5C,EAAE;CACN,MAAM,kBAAA,GAAA,WAAA,gBAAyC,YAAY;CAC3D,MAAM,qBAAqB;CAC3B,MAAM,cAAc,QAAQ,eAAe;AAE3C,QAAO;EACL,GAAG;EACH,GAAG;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD;;AAGH,eAAe,aACb,MACA,SACqB;CACrB,MAAM,YAAY,sBAAA,2BAA2B,MAAM,KAAK;AAExD,KAAI,aAAa,mCAAA,+BAA+B,UAAU,CACxD,OAAM,IAAI,MACR,WAAA,YAAY,oDACb;AAGH,KAAI,QAAQ,WAAW,UAAU;AAC/B,MAAI,CAAC,UACH,OAAM,IAAI,MACR,WAAA,YAAY,uDACb;AAEH,MAAI,mCAAA,qCAAqC,UAAU,CACjD,OAAM,IAAI,MACR,WAAA,YAAY,OAAO,mCAAA,oCAAoC,gDACxD;;CAIL,MAAM,oBAAoB,iBAAiB,MAAM,QAAQ;AAEzD,KAAI,UACF,OAAM,wBAAA,cAAc,MAAM,kBAAkB;MACvC;AAKL,SAAA,GAAA,yBAAA,4BAHE,uBACA,cACD,CACyB,MAAM;GAC9B,aAA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