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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"analogjs-router-server.mjs","names":[],"sources":["../../server/src/server-fn/registry.ts","../../server/src/server-fn/node-context.ts","../../server/src/server-fn/interceptors.ts","../../server/src/server-fn/same-origin.ts","../../server/src/server-fn/dispatch.ts","../../server/src/server-fn/ssr-dispatcher.ts","../../server/src/provide-server-context.ts","../../server/src/utils/reset-component-def-tviews.ts","../../server/src/render.ts","../../server/src/utils/stream-html.ts","../../server/src/utils/stream-shell.ts","../../server/src/utils/stream-request.ts","../../server/src/defer-reconcile-runtime.ts","../../server/src/utils/ssr-stream-lifecycle.ts","../../server/src/ssr-navigation.ts","../../server/src/render-stream.ts","../../server/src/server-fn/server-fn.ts","../../server/src/server-fn/app-injector.ts","../../server/src/server-fn/event-handler.ts"],"sourcesContent":["import type { ServerFnDef } from '@analogjs/router';\n\n/**\n * Server-side registry of server functions, keyed by id. A `.server.ts` module\n * populates it as a side effect of `serverFn(...)` running at import time; the\n * Nitro dispatch route imports those modules to fill it, then looks up by id.\n */\nexport const serverFnRegistry: Map<string, ServerFnDef> = new Map<\n string,\n ServerFnDef\n>();\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { H3Event } from 'h3';\n\ntype NodeContext = NonNullable<H3Event['node']>;\ntype NodeRuntimeContext = NodeContext & {\n req: IncomingMessage;\n res: ServerResponse;\n};\n\n/**\n * Dispatch provides the Node request and response through `REQUEST` and\n * `RESPONSE`, which are typed as Node primitives, so server functions only run\n * on a Node runtime. h3 leaves `node` undefined on other runtimes. Calls made\n * in-process while rendering may have no response.\n */\nexport function assertNodeContext(\n event: Pick<H3Event, 'node'>,\n): NodeRuntimeContext {\n const node = event.node;\n\n if (!node?.req) {\n throw new Error(\n '@analogjs/router: server functions require a Node runtime.',\n );\n }\n\n return node as NodeRuntimeContext;\n}\n","import { InjectionToken, type Provider } from '@angular/core';\n\nimport type { ServerFnContext } from '@analogjs/router';\n\n/** Context threaded through the interceptor chain and handed to the handler. */\nexport interface ServerFnInterceptorContext {\n readonly input: unknown;\n readonly context: ServerFnContext;\n /** Return a new context with additional typed fields merged in. */\n with(\n patch: Partial<ServerFnContext> & Record<string, unknown>,\n ): ServerFnInterceptorContext;\n}\n\nexport type ServerFnNext = (\n ctx: ServerFnInterceptorContext,\n) => Promise<unknown>;\n\n/** Functional interceptor, modeled on `HttpInterceptorFn`. */\nexport type ServerFnInterceptorFn = (\n ctx: ServerFnInterceptorContext,\n next: ServerFnNext,\n) => Promise<unknown> | unknown;\n\nexport const SERVER_FN_INTERCEPTORS: InjectionToken<ServerFnInterceptorFn[]> =\n new InjectionToken<ServerFnInterceptorFn[]>('SERVER_FN_INTERCEPTORS');\n\nexport interface ServerFnsFeature {\n providers: Provider[];\n}\n\n/** `withServerFnInterceptors([...])` — registers the chain (DI, ordered). */\nexport function withServerFnInterceptors(\n interceptors: ServerFnInterceptorFn[],\n): ServerFnsFeature {\n return {\n providers: interceptors.map((fn) => ({\n provide: SERVER_FN_INTERCEPTORS,\n useValue: fn,\n multi: true,\n })),\n };\n}\n\n/** `provideServerFns(withServerFnInterceptors(...))` — mirrors provideHttpClient. */\nexport function provideServerFns(...features: ServerFnsFeature[]): Provider[] {\n return features.flatMap((f) => f.providers);\n}\n\nfunction makeCtx(\n input: unknown,\n context: ServerFnContext,\n): ServerFnInterceptorContext {\n return {\n input,\n context,\n with(patch) {\n return makeCtx(input, { ...context, ...patch } as ServerFnContext);\n },\n };\n}\n\n/**\n * Run the interceptor chain, then the handler, threading the context.\n *\n * `runInCtx` re-establishes the DI injection context around each interceptor\n * and the handler individually. This is what keeps `inject()` working in a\n * handler even when an upstream interceptor `await`s before calling `next`\n * (which would otherwise resume outside Angular's synchronous injection\n * context). It defaults to a pass-through for non-DI callers/tests.\n */\nexport async function runInterceptors(\n interceptors: ServerFnInterceptorFn[],\n input: unknown,\n handler: (\n input: unknown,\n context: ServerFnContext,\n ) => Promise<unknown> | unknown,\n runInCtx: <T>(fn: () => T) => T = (fn) => fn(),\n): Promise<unknown> {\n let i = -1;\n const dispatch: ServerFnNext = async (ctx) => {\n i += 1;\n if (i < interceptors.length) {\n return runInCtx(() => interceptors[i](ctx, dispatch));\n }\n return runInCtx(() => handler(ctx.input, ctx.context));\n };\n return dispatch(makeCtx(input, {} as ServerFnContext));\n}\n","/**\n * Same-origin enforcement for the server-function HTTP transport.\n *\n * Server functions are same-origin RPC: a client proxy only ever calls the\n * relative `/_analog/fn/:id` URL of its own app. A cross-origin page must not be\n * able to invoke them against a logged-in user (a CSRF-shaped attack), so the\n * transport rejects browser requests whose origin is not the app's own — out of\n * the box, with no per-app configuration.\n *\n * The signals used (`Sec-Fetch-Site`, `Origin`) are added by the browser and\n * cannot be forged by a cross-origin page's `fetch`. Non-browser callers (curl,\n * server-to-server, SSR in-process) send neither, so they are unaffected: the\n * guard blocks the cross-origin browser attack it is meant to, and nothing else.\n */\n\nimport { InjectionToken } from '@angular/core';\n\nimport type { ServerFnsFeature } from './interceptors';\n\n/** Node/h3 header bag shape (`IncomingHttpHeaders`). */\nexport type HeaderBag = Record<string, string | string[] | undefined>;\n\n/**\n * Origins permitted beyond the app's own, registered through DI:\n * `provideServerFns(withAllowedOrigins([...]))`. Empty by default — the\n * transport is same-origin unless an app opts out explicitly.\n */\nexport const SERVER_FN_ALLOWED_ORIGINS: InjectionToken<string[]> =\n new InjectionToken<string[]>('SERVER_FN_ALLOWED_ORIGINS');\n\n/**\n * `withAllowedOrigins([...])` — permit cross-origin browser calls from the\n * listed origins, or pass `'*'` to disable the same-origin guard entirely.\n * Server functions are frequently cookie-authenticated, so this is an explicit\n * opt-out of CSRF protection: allow-list the exact origins you control.\n */\nexport function withAllowedOrigins(origins: string[]): ServerFnsFeature {\n return {\n providers: origins.map((origin) => ({\n provide: SERVER_FN_ALLOWED_ORIGINS,\n useValue: origin,\n multi: true,\n })),\n };\n}\n\nfunction firstHeader(value: string | string[] | undefined): string | undefined {\n return Array.isArray(value) ? value[0] : value;\n}\n\n/**\n * Whether an HTTP request to a server function may proceed.\n *\n * Allowed when the request is same-origin, carries no browser-origin signal at\n * all (a non-browser client, or a same-origin GET that omits `Origin`), or its\n * `Origin` is listed in `allowedOrigins`. Passing `'*'` in `allowedOrigins`\n * disables the check — the explicit opt-in to cross-origin access.\n *\n * `Sec-Fetch-Site` is the authoritative signal when present: `same-origin` and\n * `none` (a direct navigation, not a cross-site fetch) pass; `same-site` and\n * `cross-site` require an explicit `allowedOrigins` entry. When the header is\n * absent (older browsers, some proxies) the `Origin` host is compared to the\n * request host as a fallback.\n */\nexport function isServerFnOriginAllowed(\n headers: HeaderBag,\n allowedOrigins: readonly string[] = [],\n): boolean {\n if (allowedOrigins.includes('*')) {\n return true;\n }\n\n const origin = firstHeader(headers['origin']);\n const originAllowlisted =\n origin !== undefined && allowedOrigins.includes(origin);\n\n const site = firstHeader(headers['sec-fetch-site']);\n if (site) {\n if (site === 'same-origin' || site === 'none') {\n return true;\n }\n // same-site / cross-site: only when the origin is explicitly permitted.\n return originAllowlisted;\n }\n\n // No `Sec-Fetch-Site`: fall back to comparing the `Origin` host to the host.\n if (!origin) {\n // Non-browser client, or a same-origin GET with no `Origin` — not the\n // cross-origin browser request this guard exists to reject.\n return true;\n }\n if (originAllowlisted) {\n return true;\n }\n\n const host =\n firstHeader(headers['x-forwarded-host']) ?? firstHeader(headers['host']);\n if (!host) {\n return false;\n }\n try {\n return new URL(origin).host === host;\n } catch {\n return false;\n }\n}\n","import {\n Injector,\n runInInjectionContext,\n type StaticProvider,\n} from '@angular/core';\nimport { BASE_URL, LOCALE, REQUEST, RESPONSE } from '@analogjs/router/tokens';\nimport type { H3Event } from 'h3';\n\nimport { detectLocale, getBaseUrl } from '../provide-server-context';\nimport { serverFnRegistry } from './registry';\nimport { assertNodeContext } from './node-context';\nimport { SERVER_FN_INTERCEPTORS, runInterceptors } from './interceptors';\nimport {\n SERVER_FN_ALLOWED_ORIGINS,\n isServerFnOriginAllowed,\n type HeaderBag,\n} from './same-origin';\n\nexport interface DispatchResult {\n status: number;\n body: unknown;\n /**\n * Headers from a returned `Response` (`fail`/`redirect`): Location, … The\n * value is an array when the header legitimately repeats, which is why\n * `Set-Cookie` is read separately below — collapsing several cookies into one\n * comma-joined value corrupts them.\n */\n headers?: Record<string, string | string[]>;\n}\n\nexport interface DispatchServerFnOptions {\n /**\n * The app's environment injector. The per-request injector is created as its\n * child, so handlers resolve app services (and `providedIn: 'root'` services,\n * when this is the app's bootstrapped injector) and registered interceptors\n * without re-listing them per request.\n */\n parent?: Injector;\n /** Extra per-request providers, for direct callers without an app injector. */\n providers?: StaticProvider[];\n /** Request HTTP method; enforced against the function's configured method. */\n method?: string;\n /**\n * Origins permitted beyond same-origin, merged with any registered through DI\n * (`provideServerFns(withAllowedOrigins([...]))`). The transport is\n * same-origin by default (cross-origin browser calls are rejected with 403);\n * `'*'` disables the check entirely. Only consulted for HTTP-transport calls\n * (those that pass `method`).\n */\n allowedOrigins?: string[];\n}\n\n/**\n * Server-side dispatch for a server function call.\n *\n * 1. reject cross-origin browser calls (403), unless allow-listed — HTTP\n * transport only (in-process callers omit `method` and are exempt)\n * 2. look up the function by id\n * 3. enforce the configured HTTP method (405 on mismatch)\n * 4. require a JSON body on input-bearing calls (415 otherwise)\n * 5. validate `input` against the Standard-Schema (4xx on failure)\n * 6. build a per-request injector (REQUEST/RESPONSE + app providers)\n * 7. run the interceptor chain, then the handler, re-entering\n * `runInInjectionContext` at every hop so `inject()` works even after an\n * interceptor `await`s before calling `next`\n * 8. a `Response` returned by an interceptor/handler (`fail`/`redirect`)\n * short-circuits with its status AND headers\n *\n * `options.method` is the request's HTTP method; when provided it is enforced\n * against the function's configured method AND it turns on the same-origin\n * guard. Transports (the generated Nitro handler) always pass it; trusted\n * in-process callers may omit it, which also exempts them from the origin guard.\n */\nexport async function dispatchServerFn(\n id: string,\n rawInput: unknown,\n event: Pick<H3Event, 'node'>,\n options: DispatchServerFnOptions = {},\n): Promise<DispatchResult> {\n const { parent, providers = [], method, allowedOrigins = [] } = options;\n const node = assertNodeContext(event);\n const headers = (node.req.headers ?? {}) as HeaderBag;\n\n // Same-origin guard runs first — before we even confirm the function exists —\n // so a cross-origin page cannot probe which ids are registered. Gated on\n // `method` so only HTTP-transport calls are checked; in-process callers omit\n // it. The signals (`Origin`/`Sec-Fetch-Site`) are browser-set and unforgeable.\n if (method) {\n const allowed = [\n ...allowedOrigins,\n ...(parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []),\n ];\n if (!isServerFnOriginAllowed(headers, allowed)) {\n return {\n status: 403,\n body: { message: 'Cross-origin server function call rejected' },\n };\n }\n }\n\n const def = serverFnRegistry.get(id);\n if (!def) {\n return { status: 404, body: { message: `Unknown server function: ${id}` } };\n }\n\n // Enforce the transport method: a GET-only read must not be POSTable, and an\n // input-bearing POST must not be reachable via GET.\n if (method && method.toUpperCase() !== def.method) {\n return {\n status: 405,\n body: { message: `Method ${method} not allowed for ${id}` },\n headers: { Allow: def.method },\n };\n }\n\n // Input travels as a JSON body. Reject anything else before decoding, so a\n // form post from a cross-origin page (which cannot set a JSON content type\n // without a CORS preflight) never reaches a handler. HTTP transport only.\n if (method && def.method === 'POST' && !isJsonContentType(headers)) {\n return {\n status: 415,\n body: { message: 'Server functions accept an application/json body' },\n };\n }\n\n let input = rawInput;\n if (def.config.input) {\n const result = await def.config.input['~standard'].validate(rawInput);\n if ('issues' in result && result.issues) {\n return { status: 400, body: { errors: result.issues } };\n }\n input = (result as { value: unknown }).value;\n }\n\n // Child of the app injector: only the request tokens are per-request; app\n // services + interceptors resolve up the parent chain. All four are provided\n // here so a handler resolves them the same way it would inside a component\n // during SSR, whether it was reached over HTTP or in-process.\n const req = node.req as Parameters<typeof getBaseUrl>[0];\n const locale = detectLocale(req);\n const injector = Injector.create({\n parent,\n providers: [\n { provide: REQUEST, useValue: node.req },\n { provide: RESPONSE, useValue: node.res },\n { provide: BASE_URL, useValue: getBaseUrl(req) },\n ...(locale ? [{ provide: LOCALE, useValue: locale }] : []),\n ...providers,\n ],\n });\n\n // Re-enter the injection context at each hop rather than wrapping the whole\n // chain once: an interceptor that awaits before `next` would otherwise run the\n // handler outside the context and break `inject()`.\n const runInCtx = <T>(fn: () => T): T => runInInjectionContext(injector, fn);\n const interceptors = injector.get(SERVER_FN_INTERCEPTORS, []);\n const outcome = await runInterceptors(\n interceptors,\n input,\n def.handler,\n runInCtx,\n );\n\n if (outcome instanceof Response) {\n const text = await outcome.text();\n const body = text ? safeJson(text) : null;\n const headers: Record<string, string | string[]> = {};\n outcome.headers.forEach((value, key) => {\n if (key.toLowerCase() !== 'set-cookie') {\n headers[key] = value;\n }\n });\n // `Headers.forEach` yields cookies comma-joined into a single value, which\n // is not a valid way to send more than one; `getSetCookie` keeps them apart.\n const setCookie = outcome.headers.getSetCookie?.() ?? [];\n if (setCookie.length) {\n headers['set-cookie'] = setCookie;\n }\n return {\n status: outcome.status,\n body,\n headers: Object.keys(headers).length ? headers : undefined,\n };\n }\n\n return { status: 200, body: outcome };\n}\n\nfunction isJsonContentType(headers: HeaderBag): boolean {\n const contentType = headers['content-type'];\n const value = Array.isArray(contentType) ? contentType[0] : contentType;\n if (!value) {\n return false;\n }\n const mediaType = value.split(';')[0].trim().toLowerCase();\n return mediaType === 'application/json' || mediaType.endsWith('+json');\n}\n\nfunction safeJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n","import { Injector } from '@angular/core';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport type { ServerRequest, ServerResponse } from '@analogjs/router/tokens';\nimport type { ServerFn, ServerFnDispatcher } from '@analogjs/router';\nimport type { H3Event } from 'h3';\n\nimport { dispatchServerFn } from './dispatch';\n\n/**\n * The in-process transport used during SSR. `ServerFnClient` picks this up from\n * DI and calls the handler directly instead of issuing an HTTP request back\n * into the app — the render and the handler already share a process and a\n * request, so the round-trip only adds latency (and would need an absolute URL).\n *\n * `method` is deliberately not passed to `dispatchServerFn`: this is a trusted\n * in-process caller, so the HTTP-transport-only checks (same-origin, method\n * enforcement, content type) do not apply. Validation and the interceptor chain\n * still run, so an SSR call behaves like a browser call in every other respect.\n *\n * A non-2xx result is thrown as an `HttpErrorResponse` so the failure surfaces\n * on `resource.error()` exactly as it does in the browser.\n */\nexport function createServerFnDispatcher(\n req: ServerRequest,\n res: ServerResponse,\n): ServerFnDispatcher {\n const event = { node: { req, res } } as unknown as Pick<H3Event, 'node'>;\n\n return async <In, Out>(\n fn: ServerFn<In, Out>,\n input: In,\n injector: Injector,\n ): Promise<Out> => {\n const { status, body } = await dispatchServerFn(fn.id, input, event, {\n parent: injector,\n });\n\n if (status < 200 || status > 299) {\n throw new HttpErrorResponse({ status, error: body, url: fn.url });\n }\n\n return body as Out;\n };\n}\n","import { StaticProvider, ɵresetCompiledComponents } from '@angular/core';\nimport { ɵSERVER_CONTEXT as SERVER_CONTEXT } from '@angular/platform-server';\n\nimport {\n BASE_URL,\n INTERNAL_FETCH,\n LOCALE,\n REQUEST,\n RESPONSE,\n ServerInternalFetch,\n ServerRequest,\n ServerResponse,\n} from '../../tokens/src/index.js';\nimport { SERVER_FN_DISPATCHER } from '@analogjs/router';\n\nimport { createServerFnDispatcher } from './server-fn/ssr-dispatcher';\n\ndeclare const ANALOG_I18N_FIXED_LOCALE: string | undefined;\n\nfunction getHeaderValue(\n value: string | string[] | undefined,\n): string | undefined {\n return Array.isArray(value) ? value[0] : value;\n}\n\nfunction getRequestHeader(\n req: ServerRequest,\n name: string,\n): string | undefined {\n const headers = (req as { headers?: unknown }).headers;\n\n if (!headers) {\n return undefined;\n }\n\n if (\n typeof headers === 'object' &&\n headers !== null &&\n 'get' in headers &&\n typeof headers.get === 'function'\n ) {\n return headers.get(name) ?? undefined;\n }\n\n return getHeaderValue(\n (headers as Record<string, string | string[] | undefined>)[name],\n );\n}\n\nexport function provideServerContext({\n req,\n res,\n fetch,\n}: {\n req: ServerRequest;\n res: ServerResponse;\n fetch?: ServerInternalFetch;\n}): StaticProvider[] {\n const baseUrl = getBaseUrl(req);\n // A locale worker from @analogjs/vite-plugin-nitro renders a single locale.\n const locale =\n (typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&\n ANALOG_I18N_FIXED_LOCALE) ||\n detectLocale(req);\n\n // Optional chaining: a Nitro-bundled caller has no `import.meta.env` at all.\n if (import.meta.env?.DEV) {\n ɵresetCompiledComponents();\n }\n\n return [\n { provide: SERVER_CONTEXT, useValue: 'ssr-analog' },\n { provide: REQUEST, useValue: req },\n { provide: RESPONSE, useValue: res },\n { provide: BASE_URL, useValue: baseUrl },\n { provide: INTERNAL_FETCH, useValue: fetch },\n // Server functions called while rendering run in-process, in this injector.\n {\n provide: SERVER_FN_DISPATCHER,\n useValue: createServerFnDispatcher(req, res),\n },\n ...(locale ? [{ provide: LOCALE, useValue: locale }] : []),\n ];\n}\n\nexport function getBaseUrl(req: ServerRequest): string {\n const protocol = getRequestProtocol(req);\n const host =\n getRequestHeader(req, 'x-forwarded-host') ??\n getRequestHeader(req, 'host') ??\n 'localhost';\n const originalUrl = req.originalUrl || req.url || '/';\n const parsedUrl = new URL(\n '',\n `${protocol}://${host}${\n originalUrl.endsWith('/')\n ? originalUrl.substring(0, originalUrl.length - 1)\n : originalUrl\n }`,\n );\n const baseUrl = parsedUrl.origin;\n\n return baseUrl;\n}\n\nexport function getRequestProtocol(\n req: ServerRequest,\n opts: { xForwardedProto?: boolean } = {},\n): string {\n const forwardedProto = getRequestHeader(req, 'x-forwarded-proto')\n ?.split(',')[0]\n ?.trim();\n\n if (opts.xForwardedProto !== false && forwardedProto === 'https') {\n return 'https';\n }\n\n return (req.connection as { encrypted?: boolean })?.encrypted\n ? 'https'\n : 'http';\n}\n\n/**\n * Detects the locale from the request URL path prefix or Accept-Language header.\n * URL prefix takes priority (e.g. /fr/about -> 'fr').\n */\nexport function detectLocale(req: ServerRequest): string | undefined {\n const url = req.originalUrl || req.url || '';\n const localeFromUrl = extractLocaleFromUrl(url);\n if (localeFromUrl) {\n return localeFromUrl;\n }\n\n return parseAcceptLanguage(getRequestHeader(req, 'accept-language'));\n}\n\n/**\n * Extracts a locale from the first URL path segment if it matches\n * a BCP 47-like pattern (e.g. 'en', 'en-US', 'zh-Hans-CN').\n */\nexport function extractLocaleFromUrl(url: string): string | undefined {\n const pathname = url.split('?')[0];\n const segments = pathname.split('/').filter(Boolean);\n if (segments.length === 0) {\n return undefined;\n }\n\n const firstSegment = segments[0];\n // Match BCP 47 language tags: 2-letter language code with optional region/script\n if (/^[a-z]{2}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2}|\\d{3})?$/.test(firstSegment)) {\n return firstSegment;\n }\n\n return undefined;\n}\n\n/**\n * Parses the Accept-Language header and returns the most preferred language.\n */\nexport function parseAcceptLanguage(\n header: string | undefined,\n): string | undefined {\n if (!header) {\n return undefined;\n }\n\n const locales = header\n .split(',')\n .map((part) => {\n const [locale, qPart] = part.trim().split(';');\n const q = qPart ? parseFloat(qPart.replace('q=', '')) : 1;\n return { locale: locale.trim(), q };\n })\n .sort((a, b) => b.q - a.q);\n\n return locales[0]?.locale || undefined;\n}\n","declare const ANALOG_I18N_FIXED_LOCALE: string | undefined;\n\n/**\n * Nulls `def.tView` on every component definition that Angular has\n * compiled in this process. Angular caches the result of `consts()` on\n * `def.tView` — that factory is where `$localize` tagged templates are\n * evaluated — so without this reset the first rendered locale would be\n * frozen into the cache for the process lifetime.\n *\n * The set on `globalThis.__ngComponentDefs` is populated by a Vite\n * transform in `@analogjs/platform` that patches `@angular/core`'s\n * `getComponentId()` to mirror every compiled component definition to\n * a global Set, bypassing the `ngServerMode` guard that normally\n * prevents registration on the server.\n */\nexport function resetComponentDefTViews(): void {\n if (\n typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&\n ANALOG_I18N_FIXED_LOCALE\n )\n return;\n const defs = (globalThis as any).__ngComponentDefs as Set<any> | undefined;\n if (!defs) return;\n for (const def of defs) {\n def.tView = null;\n }\n}\n","import {\n ApplicationConfig,\n Provider,\n Type,\n enableProdMode,\n} from '@angular/core';\nimport {\n bootstrapApplication,\n type BootstrapContext,\n} from '@angular/platform-browser';\nimport { renderApplication } from '@angular/platform-server';\nimport type { ServerContext } from '../../tokens/src/index.js';\n\nimport { provideServerContext } from './provide-server-context';\nimport { resetComponentDefTViews } from './utils/reset-component-def-tviews';\n\n// Optional chaining: the server-function dispatch endpoint imports this entry\n// from a Nitro bundle, where `import.meta.env` is not defined at all.\nif (import.meta.env?.PROD) {\n enableProdMode();\n}\n\n/**\n * Returns a function that accepts the navigation URL,\n * the root HTML, and server context.\n *\n * @param rootComponent\n * @param config\n * @param platformProviders\n * @returns Promise<string>\n */\nexport function render(\n rootComponent: Type<unknown>,\n config: ApplicationConfig,\n platformProviders: Provider[] = [],\n) {\n function bootstrap(context: BootstrapContext) {\n return bootstrapApplication(rootComponent, config, context);\n }\n\n return async function render(\n url: string,\n document: string,\n serverContext: ServerContext,\n ): Promise<string> {\n resetComponentDefTViews();\n\n const html = await renderApplication(bootstrap, {\n document,\n url,\n platformProviders: [\n provideServerContext(serverContext),\n platformProviders,\n ],\n });\n\n return html;\n };\n}\n","/**\n * Pure string helpers for slicing a fully rendered SSR document into the parts\n * the streaming renderer flushes: the shell up to `<body>`, the authoritative\n * `<body>` inner HTML for the tail, and the authoritative `<head>` inner HTML\n * for the finalize-time head reconcile. Extracted from `render-stream` so they\n * can be unit tested without driving the platform.\n */\n\n/** Byte offset just after the opening `<body>` tag, or 0 if none. */\nexport function afterBodyOpen(html: string): number {\n const m = /<body[^>]*>/i.exec(html);\n return m ? m.index + m[0].length : 0;\n}\n\n/** Inner HTML of `<body>` from a fully rendered document string. */\nexport function bodyInner(html: string): string {\n const start = afterBodyOpen(html);\n const end = html.lastIndexOf('</body>');\n return html.slice(start, end > -1 ? end : html.length);\n}\n\n/** Inner HTML of `<head>` from a fully rendered document string. */\nexport function headInner(html: string): string {\n const open = /<head[^>]*>/i.exec(html);\n if (!open) return '';\n const start = open.index + open[0].length;\n const end = html.indexOf('</head>', start);\n return html.slice(start, end > -1 ? end : start);\n}\n","import { runInInjectionContext, type PlatformRef } from '@angular/core';\nimport { PlatformState } from '@angular/platform-server';\n\n/** Preload bootstrap modules, but leave execution to the authoritative tail. */\nexport function createStreamShell(platform: PlatformRef): string {\n const state = platform.injector.get(PlatformState);\n const document = (state.getDocument() as Document).cloneNode(\n true,\n ) as Document;\n for (const script of Array.from(\n document.head.querySelectorAll('script[type=\"module\"]'),\n )) {\n const src = script.getAttribute('src');\n if (src) {\n const preload = document.createElement('link');\n preload.setAttribute('rel', 'modulepreload');\n preload.setAttribute('href', src);\n for (const name of [\n 'crossorigin',\n 'integrity',\n 'referrerpolicy',\n 'nonce',\n 'fetchpriority',\n ]) {\n const value = script.getAttribute(name);\n if (value !== null) preload.setAttribute(name, value);\n }\n script.parentNode!.replaceChild(preload, script);\n } else {\n script.parentNode!.removeChild(script);\n }\n }\n while (document.body.firstChild)\n document.body.removeChild(document.body.firstChild);\n const html = runInInjectionContext(platform.injector, () =>\n new PlatformState(document).renderToString(),\n );\n return html.slice(0, html.lastIndexOf('</body>'));\n}\n","import type { ServerContext } from '@analogjs/router/tokens';\n\n/**\n * Per-request decisions about whether the streaming renderer should fall back\n * to a buffered render. Extracted from `render-stream` so they can be unit\n * tested without driving the platform.\n */\n\n/**\n * User agents that receive a fully buffered render (with a resolved `<head>`)\n * instead of the streamed shell. Streaming flushes the head before the app has\n * set a dynamic title/meta and reconciles it via a finalize script; a crawler\n * that does not run that script would index the shell's static head. Mirrors\n * Nuxt's bot bypass — streaming targets interactive clients, bots get the\n * buffered path whose head is byte-identical to the classic `render()`.\n */\nexport const SSR_BOT_RE: RegExp =\n /bot|crawl|spider|slurp|mediapartners|facebookexternalhit|embedly|quora link preview|outbrain|pinterest|vkshare|w3c_validator|whatsapp|telegrambot|lighthouse|google-inspectiontool|headlesschrome|bingpreview/i;\n\nexport function isLikelyBot(serverContext: ServerContext): boolean {\n const ua = serverContext?.req?.headers?.['user-agent'];\n return typeof ua === 'string' && SSR_BOT_RE.test(ua);\n}\n\n/**\n * Whether streaming is disabled for this request by a `streaming: false` route\n * rule. The platform plugin translates that rule into an `x-analog-no-streaming`\n * response header (mirroring how `ssr: false` becomes `x-analog-no-ssr`); when\n * present, `renderStream` produces the buffered `render()` output for this\n * route instead of streaming. On Nitro v3, which renders without a Node\n * response, the header is forwarded on the request instead.\n */\nexport function streamingDisabledByRoute(\n serverContext: ServerContext,\n): boolean {\n if (serverContext?.streaming !== undefined) {\n return !serverContext.streaming;\n }\n\n return (\n serverContext?.res?.getHeader?.('x-analog-no-streaming') === 'true' ||\n serverContext?.req?.headers?.['x-analog-no-streaming'] === 'true'\n );\n}\n","/**\n * Tiny client runtime for progressive streaming SSR — EXPERIMENTAL.\n *\n * `renderStream` streams the document in three parts:\n * 1. the head + this runtime + an empty `<div data-analog-stream>` region;\n * 2. each `@defer` block, as it resolves on the server, as a\n * `<template data-analog-defer=\"ID\">…</template>` followed by a call to\n * `window.__analogPaint(\"ID\")` — this runtime paints the block into the\n * streaming region immediately, so content appears progressively and out\n * of document order;\n * 3. the authoritative document tail: the app's resolved `<head>` in a\n * `<template data-analog-head>` and the hydration-annotated body in a\n * `<template data-analog-authoritative>`, followed by\n * `window.__analogReconcileHead()` + `window.__analogFinalize()`. The head\n * is reconciled first (a dynamically-set `<title>`/meta is applied to the\n * live document, since the streamed shell head was flushed before the app\n * ran), then the body is swapped to the exact document Angular's\n * incremental hydration expects.\n *\n * Emitted into the document by `renderStream`. Exported as a string so it can\n * be injected verbatim and unit-tested against a DOM.\n */\nexport const DEFER_RECONCILE_RUNTIME = /* js */ `\n(function () {\n var completed = false;\n var headModules = [];\n function activateModule(source) {\n var script = document.createElement('script');\n Array.from(source.attributes).forEach(function (attr) {\n script.setAttribute(attr.name, attr.value);\n });\n if (source.hasAttribute('nonce')) script.nonce = source.nonce;\n if (!source.hasAttribute('async')) script.async = false;\n script.textContent = source.textContent;\n return script;\n }\n function region() {\n return document.querySelector('[data-analog-stream]');\n }\n function showError() {\n document.title = 'Unable to load this page';\n var robots = document.head.querySelector('meta[name=\"robots\"]');\n if (!robots) {\n robots = document.createElement('meta');\n robots.setAttribute('name', 'robots');\n document.head.appendChild(robots);\n }\n robots.setAttribute('content', 'noindex');\n var error = document.createElement('main');\n error.setAttribute('data-analog-render-error', '');\n error.setAttribute('role', 'alert');\n var heading = document.createElement('h1');\n heading.textContent = 'Unable to load this page';\n var message = document.createElement('p');\n message.textContent = 'The page could not finish loading.';\n error.appendChild(heading);\n error.appendChild(message);\n document.body.replaceChildren(error);\n }\n function checkCompletion() {\n if (!completed && region()) showError();\n }\n window.__analogFail = showError;\n // A Worker HTTP adapter can turn a stream error into ordinary EOF. The\n // authoritative tail, rather than transport completion, proves SSR success.\n document.addEventListener('DOMContentLoaded', checkCompletion, { once: true });\n window.__analogPaint = function (id) {\n var tpl = document.querySelector('template[data-analog-defer=\"' + id + '\"]');\n var r = region();\n if (!tpl || !r) return;\n r.appendChild(tpl.content.cloneNode(true));\n tpl.remove();\n };\n window.__analogReconcileHead = function () {\n // The shell head was flushed before the app rendered, so any title/meta the\n // app set during render (Title/Meta services, route meta) is missing from\n // the live document. Apply the authoritative head here, before hydration —\n // matching how a buffered render would have produced the head. Idempotent:\n // tags already present (charset, viewport, stylesheet/preload links) are\n // matched and left as-is; only changed/added ones are updated.\n var tpl = document.querySelector('template[data-analog-head]');\n if (!tpl) return;\n var frag = tpl.content;\n var head = document.head;\n frag.querySelectorAll('script[type=\"module\"]').forEach(function (script) {\n headModules.push(script.cloneNode(true));\n });\n var title = frag.querySelector('title');\n if (title) document.title = title.textContent || '';\n function metaKey(m) {\n if (m.hasAttribute('charset')) return 'charset';\n var attrs = ['name', 'property', 'http-equiv', 'itemprop'];\n for (var i = 0; i < attrs.length; i++) {\n if (m.hasAttribute(attrs[i])) return attrs[i] + '=' + m.getAttribute(attrs[i]);\n }\n return null;\n }\n var existingMeta = {};\n var metas = head.querySelectorAll('meta');\n for (var i = 0; i < metas.length; i++) {\n var k = metaKey(metas[i]);\n if (k) existingMeta[k] = metas[i];\n }\n frag.querySelectorAll('meta').forEach(function (m) {\n var key = metaKey(m);\n if (key == null) return;\n if (existingMeta[key]) existingMeta[key].replaceWith(m.cloneNode(true));\n else head.appendChild(m.cloneNode(true));\n });\n var existingHref = {};\n var links = head.querySelectorAll('link[href]');\n for (var j = 0; j < links.length; j++) {\n existingHref[links[j].getAttribute('href')] = true;\n }\n frag.querySelectorAll('link').forEach(function (l) {\n var href = l.getAttribute('href');\n if (href && existingHref[href]) return;\n head.appendChild(l.cloneNode(true));\n if (href) existingHref[href] = true;\n });\n tpl.remove();\n };\n window.__analogFinalize = function () {\n var auth = document.querySelector('template[data-analog-authoritative]');\n if (!auth) return;\n completed = true;\n document.removeEventListener('DOMContentLoaded', checkCompletion);\n // Replace the entire body — preview region, block templates and runtime\n // scripts — with just the authoritative body, so the reconciled DOM matches\n // a buffered render byte-for-byte before hydration boots.\n var body = auth.content.cloneNode(true);\n var bodyModules = Array.from(body.querySelectorAll('script[type=\"module\"]'));\n document.body.replaceChildren(body);\n headModules.forEach(function (script) {\n document.head.appendChild(activateModule(script));\n });\n headModules = [];\n bodyModules.forEach(function (script) {\n script.replaceWith(activateModule(script));\n });\n };\n})();\n`;\n","/** Owns stream closure, queued block flushes and platform cleanup across completion and cancellation. */\nexport interface SsrStreamWriter {\n readonly active: boolean;\n enqueue(html: string): void;\n scheduleBlock(serialize: () => string): void;\n finishBlocks(): Promise<void>;\n}\n\nexport function createSsrStream(options: {\n signal?: AbortSignal;\n waitUntil?(task: Promise<void>): void;\n errorHtml?: string;\n render(writer: SsrStreamWriter): Promise<void>;\n destroy(): Promise<void>;\n}): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n const pending = new Map<\n ReturnType<typeof setTimeout>,\n { promise: Promise<void>; resolve(): void }\n >();\n let state: 'rendering' | 'closing' | 'closed' | 'failed' | 'cancelled' =\n 'rendering';\n let capturing = true;\n let cleanup: Promise<void> | undefined;\n let controller: ReadableStreamDefaultController<Uint8Array>;\n let keepAlive: ReturnType<typeof setInterval> | undefined;\n let complete!: () => void;\n const completed = new Promise<void>((resolve) => {\n complete = resolve;\n });\n\n function destroy(): Promise<void> {\n capturing = false;\n clearInterval(keepAlive);\n options.signal?.removeEventListener('abort', abort);\n for (const [timer, task] of pending) {\n clearTimeout(timer);\n task.resolve();\n }\n pending.clear();\n return (cleanup ??= Promise.resolve()\n .then(options.destroy)\n .finally(complete));\n }\n\n function fail(error: unknown, aborted = false): void {\n if (state !== 'rendering' && state !== 'closing') return;\n const documentComplete = state === 'closing';\n state = 'failed';\n if (options.errorHtml && !aborted) {\n console.error('[analog ssr]', error);\n if (!documentComplete)\n controller.enqueue(encoder.encode(options.errorHtml));\n controller.close();\n } else {\n controller.error(error);\n }\n // The stream already owns the original failure. Consume cleanup failures\n // here; the render finalizer and body cancellation also await cleanup.\n void destroy().catch(() => undefined);\n }\n\n function abort(): void {\n fail(\n options.signal?.reason ??\n new DOMException('The render was aborted.', 'AbortError'),\n true,\n );\n }\n\n const writer: SsrStreamWriter = {\n get active() {\n return state === 'rendering';\n },\n enqueue(html) {\n if (state === 'rendering') controller.enqueue(encoder.encode(html));\n },\n scheduleBlock(serialize) {\n if (state !== 'rendering' || !capturing) return;\n let resolve!: () => void;\n const promise = new Promise<void>((finish) => {\n resolve = finish;\n });\n const timer = setTimeout(() => {\n try {\n if (state === 'rendering') writer.enqueue(serialize());\n } catch (error) {\n fail(error);\n } finally {\n pending.delete(timer);\n resolve();\n }\n }, 0);\n pending.set(timer, { promise, resolve });\n },\n async finishBlocks() {\n capturing = false;\n await Promise.all([...pending.values()].map((task) => task.promise));\n },\n };\n\n return new ReadableStream<Uint8Array>({\n start(streamController) {\n controller = streamController;\n if (options.waitUntil) {\n options.waitUntil(completed);\n // Workers detect a disconnected HTTP client on a subsequent write.\n // Keep the stream observable while Angular waits for asynchronous data.\n keepAlive = setInterval(\n () => writer.enqueue('<!--analog-render-pending-->'),\n 1000,\n );\n }\n options.signal?.addEventListener('abort', abort, { once: true });\n if (options.signal?.aborted) abort();\n // Do not return the render promise: cancellation must be able to run\n // while bootstrap or application stability is still pending.\n void (async () => {\n try {\n if (state === 'rendering') await options.render(writer);\n if (state === 'rendering') {\n state = 'closing';\n await destroy();\n if (state === 'closing') {\n state = 'closed';\n controller.close();\n }\n }\n } catch (error) {\n fail(error);\n } finally {\n await destroy();\n }\n })().catch(fail);\n },\n cancel() {\n state = 'cancelled';\n return destroy();\n },\n });\n}\n","import {\n DestroyRef,\n ENVIRONMENT_INITIALIZER,\n inject,\n makeEnvironmentProviders,\n type EnvironmentProviders,\n} from '@angular/core';\nimport { NavigationEnd, NavigationError, Router } from '@angular/router';\n\n/** Angular can settle initial navigation after an error without rejecting renderApplication. */\nexport function createSsrNavigationTracker(): {\n provider: EnvironmentProviders;\n throwIfFailed: () => void;\n} {\n let failure: NavigationError | undefined;\n return {\n provider: makeEnvironmentProviders([\n {\n provide: ENVIRONMENT_INITIALIZER,\n multi: true,\n useValue() {\n const router = inject(Router, { optional: true });\n if (!router) return;\n const subscription = router.events.subscribe((event) => {\n if (event instanceof NavigationError) failure = event;\n else if (event instanceof NavigationEnd) failure = undefined;\n });\n inject(DestroyRef).onDestroy(() => subscription.unsubscribe());\n },\n },\n ]),\n throwIfFailed(): void {\n if (failure) throw failure.error;\n },\n };\n}\n","/**\n * Progressive streaming SSR renderer — EXPERIMENTAL.\n *\n * Returns a `ReadableStream<Uint8Array>` that flushes bytes DURING the render,\n * not after it:\n * 1. the document head + a client reconcile runtime are flushed immediately,\n * before the app has finished rendering, so the browser starts fetching\n * assets right away;\n * 2. each `@defer (hydrate …)` block's content is flushed the moment it\n * resolves on the server — out of document order — while later blocks are\n * still pending (proven: a slow block does not hold back an early one);\n * 3. once the app is stable, the authoritative, fully hydration-annotated\n * document is flushed as the tail. This is byte-identical to a buffered\n * `renderApplication`, and is what Angular's incremental hydration runs\n * against on the client.\n *\n * Unlike a buffered renderer, this drives the platform directly\n * (`platformServer` + `bootstrapApplication` + `ɵrenderInternal`) so it can\n * interleave flushes with rendering. Angular's hydration annotation is\n * whole-document (the root's `ngh` index references every `@defer` container),\n * so the authoritative hydration payload is necessarily the tail: RENDERING\n * streams progressively, and hydration begins once the tail arrives.\n *\n * Depends on an upstream Angular per-block resolution hook exposed on two\n * globals (see {@link SsrStreamingGlobals}). When the primitive is absent,\n * `renderStream` degrades to a single buffered chunk so behaviour matches the\n * classic `render()` path, which is unchanged and remains the default.\n */\nimport {\n ApplicationConfig,\n Provider,\n Type,\n enableProdMode,\n} from '@angular/core';\nimport {\n bootstrapApplication,\n type BootstrapContext,\n} from '@angular/platform-browser';\nimport {\n renderApplication,\n platformServer,\n INITIAL_CONFIG,\n ɵrenderInternal as renderInternal,\n} from '@angular/platform-server';\nimport type { PlatformRef } from '@angular/core';\nimport type { ServerContext } from '@analogjs/router/tokens';\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport { provideServerContext } from './provide-server-context';\nimport { resetComponentDefTViews } from './utils/reset-component-def-tviews';\nimport { bodyInner, headInner } from './utils/stream-html';\nimport { createStreamShell } from './utils/stream-shell';\nimport { isLikelyBot, streamingDisabledByRoute } from './utils/stream-request';\nimport { DEFER_RECONCILE_RUNTIME } from './defer-reconcile-runtime';\nimport { createSsrStream } from './utils/ssr-stream-lifecycle';\nimport { createSsrNavigationTracker } from './ssr-navigation';\n\nif (import.meta.env?.PROD) {\n enableProdMode();\n}\n\n/**\n * Shape of the upstream Angular streaming primitive we consume, published on\n * `globalThis` by the streaming-enabled `@angular/core` build (see the\n * `deferStreamingPlugin` in `@analogjs/platform`):\n * - `__analogSsrDeferCapture` — the patched core invokes it once per resolved\n * `@defer` block on the server, passing the block's live `lContainer`. We\n * install a stable dispatcher here that routes to the current render (see\n * `installCaptureDispatcher`).\n * - `__analogSsrInternals.collectNativeNodesInLContainer` — collects a block's\n * rendered root nodes so we can serialize them via domino `outerHTML`.\n */\ninterface SsrStreamingGlobals {\n __analogSsrDeferCapture?: (ev: {\n ssrUniqueId: string | null;\n lContainer: unknown;\n }) => void;\n __analogSsrInternals?: {\n collectNativeNodesInLContainer?: (\n lContainer: unknown,\n out: unknown[],\n ) => void;\n };\n}\n\nfunction streamingPrimitiveAvailable(): boolean {\n const g: typeof globalThis & SsrStreamingGlobals = globalThis;\n return (\n typeof g.__analogSsrInternals?.collectNativeNodesInLContainer === 'function'\n );\n}\n\ntype DeferCaptureEvent = { ssrUniqueId: string | null; lContainer: unknown };\ntype DeferCaptureHandler = (ev: DeferCaptureEvent) => void;\n\n/**\n * Per-render capture handlers live in async-local storage, not a single shared\n * global slot, so concurrent renders in one process do not clobber each other.\n * `globalThis.__analogSsrDeferCapture` is a stable dispatcher installed once; it\n * routes each resolved `@defer` block to the handler of the render whose async\n * context it fired in. A block that resolves outside any render (no store) is a\n * no-op.\n */\nconst captureStore = new AsyncLocalStorage<DeferCaptureHandler>();\nconst CAPTURE_ZONE_KEY = 'analogSsrDeferCapture';\ninterface CaptureZone {\n fork(spec: {\n name: string;\n properties: Record<string, DeferCaptureHandler>;\n }): CaptureZone;\n run<T>(callback: () => T): T;\n get(key: typeof CAPTURE_ZONE_KEY): DeferCaptureHandler | undefined;\n}\n\nfunction currentCaptureZone(): CaptureZone | undefined {\n const host: typeof globalThis & { Zone?: { current: CaptureZone } } =\n globalThis;\n return host.Zone?.current;\n}\n\nfunction runWithCapture<T>(handler: DeferCaptureHandler, render: () => T): T {\n const zone = currentCaptureZone();\n return captureStore.run(handler, () =>\n zone === undefined\n ? render()\n : zone\n .fork({\n name: 'analog-ssr-capture',\n properties: { [CAPTURE_ZONE_KEY]: handler },\n })\n .run(render),\n );\n}\n\nfunction installCaptureDispatcher(): void {\n const g: typeof globalThis & {\n __analogSsrDeferCapture?: DeferCaptureHandler & {\n __analogDispatcher?: boolean;\n };\n } = globalThis;\n if (g.__analogSsrDeferCapture?.__analogDispatcher) return;\n const dispatch: DeferCaptureHandler & { __analogDispatcher?: boolean } = (\n ev,\n ) => {\n const zoneHandler = currentCaptureZone()?.get(CAPTURE_ZONE_KEY);\n (zoneHandler ?? captureStore.getStore())?.(ev);\n };\n dispatch.__analogDispatcher = true;\n g.__analogSsrDeferCapture = dispatch;\n}\n\nlet warnedMissingPrimitive = false;\nfunction warnMissingPrimitiveOnce(): void {\n if (warnedMissingPrimitive || !import.meta.env?.DEV) return;\n warnedMissingPrimitive = true;\n console.warn(\n '[@analogjs/router] renderStream: the streaming hook was not found on ' +\n '@angular/core, so rendering falls back to buffered. Enable ' +\n '`experimental.streaming` in your Analog config; if it already is, your ' +\n 'installed Angular version may be incompatible with the streaming patch.',\n );\n}\n\n/**\n * Serialize a `@defer` block's live domino subtree to HTML. Called a macrotask\n * after the block resolves, by which point change detection has filled in the\n * block's interpolations.\n */\nfunction serializeLContainerHtml(lContainer: unknown): string {\n const g: typeof globalThis & SsrStreamingGlobals = globalThis;\n const collect = g.__analogSsrInternals?.collectNativeNodesInLContainer;\n if (!collect) return '';\n const nodes: {\n nodeType: number;\n outerHTML?: string;\n data?: string;\n nodeValue?: string;\n }[] = [];\n collect(lContainer, nodes);\n let html = '';\n for (const node of nodes) {\n if (node.nodeType === 1) html += node.outerHTML ?? '';\n else if (node.nodeType === 3)\n html += (node.data ?? node.nodeValue ?? '')\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;');\n }\n return html;\n}\n\n/** Destroy the platform on a macrotask, matching `renderApplication`. */\nfunction asyncDestroyPlatform(platformRef: PlatformRef): Promise<void> {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n try {\n platformRef.destroy();\n resolve();\n } catch (error) {\n reject(error);\n }\n }, 0);\n });\n}\n\n/**\n * Returns a function that renders a URL to a `ReadableStream<Uint8Array>`.\n *\n * Usage in main.server.ts:\n * ```ts\n * import { renderStream } from '@analogjs/router/server';\n * export default renderStream(App, config);\n * ```\n */\nexport function renderStream(\n rootComponent: Type<unknown>,\n config: ApplicationConfig,\n platformProviders: Provider[] = [],\n) {\n return async function renderStream(\n url: string,\n document: string,\n serverContext: ServerContext,\n ): Promise<ReadableStream<Uint8Array>> {\n serverContext.signal?.throwIfAborted();\n const navigation = createSsrNavigationTracker();\n const applicationConfig = {\n ...config,\n providers: [...config.providers, navigation.provider],\n };\n const bootstrap = (context: BootstrapContext) =>\n bootstrapApplication(rootComponent, applicationConfig, context);\n // Reset before every render — both the buffered fallback below and the\n // streaming path — so a prior render's locale/consts are not frozen for the\n // process lifetime (parity with render.ts).\n resetComponentDefTViews();\n\n // Fall back to a single buffered chunk so output matches the classic path\n // for:\n // - crawlers, which may not run the finalize script that reconciles a\n // dynamic <head>, so they get a buffered render with a resolved head;\n // - routes with a `streaming: false` rule (opt out per route);\n // - a missing streaming primitive.\n const primitiveAvailable = streamingPrimitiveAvailable();\n const bot = isLikelyBot(serverContext);\n const routeDisabled = streamingDisabledByRoute(serverContext);\n if (bot || routeDisabled || !primitiveAvailable) {\n // Warn only when the primitive is genuinely absent — the bot and\n // route-opt-out paths fall back to buffered by design, not by degradation.\n if (!bot && !routeDisabled && !primitiveAvailable) {\n warnMissingPrimitiveOnce();\n }\n const html = await renderApplication(bootstrap, {\n document,\n url,\n platformProviders: [\n provideServerContext(serverContext),\n platformProviders,\n ],\n });\n navigation.throwIfFailed();\n return new ReadableStream({\n start(controller) {\n controller.enqueue(new TextEncoder().encode(html as string));\n controller.close();\n },\n });\n }\n\n installCaptureDispatcher();\n const platformRef = platformServer([\n { provide: INITIAL_CONFIG, useValue: { document, url } },\n provideServerContext(serverContext),\n platformProviders,\n ]);\n\n let shell: string;\n try {\n shell = createStreamShell(platformRef);\n } catch (error) {\n await asyncDestroyPlatform(platformRef);\n throw error;\n }\n\n return createSsrStream({\n signal: serverContext.signal,\n waitUntil: serverContext.waitUntil,\n errorHtml: serverContext.renderErrorsAsHtml\n ? '<script data-analog-error>window.__analogFail&&window.__analogFail();</script></body></html>'\n : undefined,\n destroy: () => asyncDestroyPlatform(platformRef),\n async render(writer) {\n let blockIndex = 0;\n const seen = new Set<unknown>();\n const onBlockResolved: DeferCaptureHandler = (event) => {\n if (!writer.active || seen.has(event.lContainer)) return;\n seen.add(event.lContainer);\n const id = `s${blockIndex++}`;\n writer.scheduleBlock(\n () =>\n `<template data-analog-defer=\"${id}\">${serializeLContainerHtml(event.lContainer)}</template>` +\n `<script>window.__analogPaint&&window.__analogPaint(${JSON.stringify(id)})</script>`,\n );\n };\n\n await runWithCapture(onBlockResolved, async () => {\n writer.enqueue(\n shell +\n `<script>${DEFER_RECONCILE_RUNTIME}</script>` +\n '<div data-analog-stream></div>',\n );\n const appRef = await bootstrap({ platformRef });\n if (!writer.active) return;\n await appRef.whenStable();\n if (!writer.active) return;\n navigation.throwIfFailed();\n await writer.finishBlocks();\n if (!writer.active) return;\n const authoritative = await renderInternal(platformRef, appRef);\n navigation.throwIfFailed();\n writer.enqueue(\n `<template data-analog-head>${headInner(authoritative)}</template>` +\n `<template data-analog-authoritative>${bodyInner(authoritative)}</template>` +\n '<script>window.__analogReconcileHead&&window.__analogReconcileHead();' +\n 'window.__analogFinalize&&window.__analogFinalize()</script></body></html>',\n );\n });\n },\n });\n };\n}\n","import { createServerFnRef } from '@analogjs/router';\nimport type {\n ServerFn,\n ServerFnConfig,\n ServerFnHandler,\n StandardSchemaV1,\n} from '@analogjs/router';\n\nimport { serverFnRegistry } from './registry';\n\n/**\n * Define a server function. Authored in a `*.server.ts` module.\n *\n * Three call shapes, chosen for ergonomics — they all normalize to the same\n * `(config, handler)` form and the build transform derives the route id for each:\n *\n * ```ts\n * serverFn(() => inject(Svc).list()); // input-less GET\n * serverFn(schema, (input) => …); // schema ⇒ POST + input\n * serverFn({ method: 'POST' }, () => …); // explicit config\n * ```\n *\n * On the server the function self-registers and its handler runs via\n * `dispatchServerFn`. On the client the build transform replaces the body with a\n * proxy that calls `/_analog/fn/<id>`; the reference still carries\n * `id`/`url`/`method` so `injectServerFn`/`ServerFnClient` can dispatch.\n */\nexport function serverFn<Out>(\n handler: ServerFnHandler<void, Out>,\n): ServerFn<void, Out>;\nexport function serverFn<In, Out>(\n input: StandardSchemaV1<In>,\n handler: ServerFnHandler<In, Out>,\n): ServerFn<In, Out>;\nexport function serverFn<In, Out>(\n config: ServerFnConfig<In>,\n handler: ServerFnHandler<In, Out>,\n): ServerFn<In, Out>;\nexport function serverFn(\n arg1: unknown,\n arg2?: ServerFnHandler<unknown, unknown>,\n): ServerFn<unknown, unknown> {\n const { config, handler } = normalizeArgs(arg1, arg2);\n\n // GET is reserved for input-less reads; an input schema requires POST (the\n // input travels in the body, not the query). Build transforms reject this too.\n if (config.method === 'GET' && config.input) {\n throw new Error(\n '[analog] a serverFn with `input` must use POST; GET is reserved for input-less reads.',\n );\n }\n\n // `createServerFnRef` throws if the build-derived id is missing, so `ref.id`\n // is the authoritative route key here.\n const ref = createServerFnRef<unknown, unknown>(config);\n\n serverFnRegistry.set(ref.id, {\n id: ref.id,\n method: ref.method,\n config,\n handler,\n });\n\n return ref;\n}\n\nfunction normalizeArgs(\n arg1: unknown,\n arg2?: ServerFnHandler<unknown, unknown>,\n): {\n config: ServerFnConfig<unknown>;\n handler: ServerFnHandler<unknown, unknown>;\n} {\n // serverFn(handler) — input-less GET.\n if (typeof arg1 === 'function') {\n return {\n config: {},\n handler: arg1 as ServerFnHandler<unknown, unknown>,\n };\n }\n // serverFn(schema, handler) — a Standard Schema ⇒ POST + input.\n if (isStandardSchema(arg1)) {\n return {\n config: { input: arg1 as StandardSchemaV1<unknown> },\n handler: arg2 as ServerFnHandler<unknown, unknown>,\n };\n }\n // serverFn(config, handler) — explicit config object.\n return {\n config: (arg1 as ServerFnConfig<unknown>) ?? {},\n handler: arg2 as ServerFnHandler<unknown, unknown>,\n };\n}\n\nfunction isStandardSchema(value: unknown): value is StandardSchemaV1<unknown> {\n return typeof value === 'object' && value !== null && '~standard' in value;\n}\n","import {\n type ApplicationConfig,\n Injector,\n type StaticProvider,\n} from '@angular/core';\nimport { createApplication } from '@angular/platform-browser';\nimport {\n platformServer,\n provideServerRendering,\n} from '@angular/platform-server';\n\n/**\n * Builds the parent injector the server-function dispatch endpoint runs handlers\n * against, over HTTP.\n *\n * A plain `Injector.create({ providers })` resolves explicitly-listed providers\n * but not tree-shakeable `providedIn: 'root'` services — those attach to a\n * *bootstrapped* application's root injector, which `Injector.create` is not.\n * So the in-process SSR leg (whose parent is the app's own bootstrapped\n * injector) resolved `root` services while the HTTP leg did not — the same\n * handler could work while rendering and fail when called from the browser.\n *\n * Bootstrapping a real application on the server platform closes that gap: the\n * returned `appRef.injector` is a root environment injector, so both listed\n * providers and `providedIn: 'root'` services resolve, matching SSR.\n *\n * The generated endpoint passes the app's own server `ApplicationConfig` (the\n * one `main.server.ts` renders with), so a handler sees exactly the DI the app\n * configured — services, tokens, and interceptors alike — with no second\n * provider list to keep in sync. No root component is bootstrapped\n * (`createApplication`, not `bootstrapApplication`), so nothing renders, no\n * change detection runs, and the router registers but never navigates. It is a\n * DI container with the app's providers, built once and reused for the process,\n * with only `REQUEST`/`RESPONSE` rebuilt per call in the child.\n *\n * A bare provider array is also accepted (direct callers and tests without an\n * app config); it is wrapped with `provideServerRendering` so the server tokens\n * resolve the same way.\n */\nexport async function createServerFnAppInjector(\n configOrProviders: ApplicationConfig | StaticProvider[] = [],\n): Promise<Injector> {\n const config: ApplicationConfig = Array.isArray(configOrProviders)\n ? { providers: [provideServerRendering(), ...configOrProviders] }\n : configOrProviders;\n\n const appRef = await createApplication(config, {\n platformRef: platformServer(),\n });\n return appRef.injector;\n}\n","import type { Injector } from '@angular/core';\nimport {\n eventHandler,\n getRouterParam,\n readBody,\n type EventHandler,\n type H3Event,\n} from 'h3';\n\nimport { dispatchServerFn } from './dispatch';\nimport { assertNodeContext } from './node-context';\n\n/**\n * The h3 request/response layer for the server-function dispatch route.\n *\n * `createServerFnAppInjector` bootstraps the parent injector once; this wraps\n * that in the `/_analog/fn/:id` handler the Nitro build registers. Kept as a\n * runtime function (rather than inlined into the generated module) so the\n * transport behaviour — body decoding, the malformed-body contract, and header\n * propagation — is unit-tested directly instead of by matching generated source.\n *\n * `appInjector` may be a promise: the generated module bootstraps the app at\n * import time and passes the pending injector, which is awaited on first request\n * and resolved instantly thereafter.\n */\nexport function createServerFnEventHandler(\n appInjector: Injector | Promise<Injector>,\n): EventHandler {\n return eventHandler((event) => handleServerFnRequest(event, appInjector));\n}\n\n/**\n * Decode a server-function request, dispatch it, and write the result to the\n * h3 response. Same-origin, method, content-type, validation, and interceptors\n * are enforced inside `dispatchServerFn`; this owns only the h3 I/O around it.\n */\nexport async function handleServerFnRequest(\n event: H3Event,\n appInjector: Injector | Promise<Injector>,\n): Promise<unknown> {\n const node = assertNodeContext(event);\n const id = getRouterParam(event, 'id') ?? '';\n\n // h3 parses the body before dispatch gets a say, and its parse error is an\n // HTML/500-shaped response rather than the JSON contract callers expect.\n let input: unknown;\n if (event.method !== 'GET') {\n try {\n input = await readBody(event);\n } catch {\n node.res.statusCode = 400;\n return { message: 'Malformed request body' };\n }\n }\n\n const { status, body, headers } = await dispatchServerFn(id, input, event, {\n parent: await appInjector,\n method: event.method,\n });\n\n node.res.statusCode = status;\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n node.res.setHeader(key, value);\n }\n }\n return body;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAOA,IAAa,mCAA6C,IAAI,IAAG;;;;;;;;;ACQjE,SAAgB,kBACd,OAA4B;CAE5B,MAAM,OAAO,MAAM;CAEnB,IAAI,CAAC,MAAM,KACT,MAAM,IAAI,MACR,4DAA4D;CAIhE,OAAO;AACT;;;ACHA,IAAa,yBACX,IAAI,eAAwC,wBAAwB;;AAOtE,SAAgB,yBACd,cAAqC;CAErC,OAAO,EACL,WAAW,aAAa,KAAK,QAAQ;EACnC,SAAS;EACT,UAAU;EACV,OAAO;CACR,EAAC,EACH;AACH;;AAGA,S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MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC/C,KAAK,IAAI,UAAU,KAAK,KAAK;CAGjC,OAAO;AACT"}
1
+ {"version":3,"file":"analogjs-router-server.mjs","names":["fetch"],"sources":["../../server/src/server-fn/registry.ts","../../server/src/server-fn/node-context.ts","../../server/src/server-fn/interceptors.ts","../../server/src/server-fn/same-origin.ts","../../server/src/server-fn/dispatch.ts","../../server/src/server-fn/ssr-dispatcher.ts","../../server/src/provide-server-context.ts","../../server/src/utils/reset-component-def-tviews.ts","../../server/src/render.ts","../../server/src/utils/stream-html.ts","../../server/src/utils/stream-shell.ts","../../server/src/utils/stream-request.ts","../../server/src/defer-reconcile-runtime.ts","../../server/src/utils/ssr-stream-lifecycle.ts","../../server/src/ssr-navigation.ts","../../server/src/render-stream.ts","../../../../node_modules/.pnpm/ofetch@2.0.0-alpha.3/node_modules/ofetch/dist/index.mjs","../../../../node_modules/.pnpm/radix3@1.1.2/node_modules/radix3/dist/index.mjs","../../server/src/server-fn/app-injector.ts","../../server/src/server-manifest.ts","../../server/src/request-handler.ts","../../server/src/node-handler.ts","../../server/src/server-fn/server-fn.ts","../../server/src/server-fn/event-handler.ts"],"sourcesContent":["import type { ServerFnDef } from '@analogjs/router';\n\n/**\n * Server-side registry of server functions, keyed by id. A `.server.ts` module\n * populates it as a side effect of `serverFn(...)` running at import time; the\n * Nitro dispatch route imports those modules to fill it, then looks up by id.\n */\nexport const serverFnRegistry: Map<string, ServerFnDef> = new Map<\n string,\n ServerFnDef\n>();\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { H3Event } from 'h3';\n\ntype NodeContext = NonNullable<H3Event['node']>;\ntype NodeRuntimeContext = NodeContext & {\n req: IncomingMessage;\n res: ServerResponse;\n};\n\n/**\n * Dispatch provides the Node request and response through `REQUEST` and\n * `RESPONSE`, which are typed as Node primitives, so server functions only run\n * on a Node runtime. h3 leaves `node` undefined on other runtimes. Calls made\n * in-process while rendering may have no response.\n */\nexport function assertNodeContext(\n event: Pick<H3Event, 'node'>,\n): NodeRuntimeContext {\n const node = event.node;\n\n if (!node?.req) {\n throw new Error(\n '@analogjs/router: server functions require a Node runtime.',\n );\n }\n\n return node as NodeRuntimeContext;\n}\n","import { InjectionToken, type Provider } from '@angular/core';\n\nimport type { ServerFnContext } from '@analogjs/router';\n\n/** Context threaded through the interceptor chain and handed to the handler. */\nexport interface ServerFnInterceptorContext {\n readonly input: unknown;\n readonly context: ServerFnContext;\n /** Return a new context with additional typed fields merged in. */\n with(\n patch: Partial<ServerFnContext> & Record<string, unknown>,\n ): ServerFnInterceptorContext;\n}\n\nexport type ServerFnNext = (\n ctx: ServerFnInterceptorContext,\n) => Promise<unknown>;\n\n/** Functional interceptor, modeled on `HttpInterceptorFn`. */\nexport type ServerFnInterceptorFn = (\n ctx: ServerFnInterceptorContext,\n next: ServerFnNext,\n) => Promise<unknown> | unknown;\n\nexport const SERVER_FN_INTERCEPTORS: InjectionToken<ServerFnInterceptorFn[]> =\n new InjectionToken<ServerFnInterceptorFn[]>('SERVER_FN_INTERCEPTORS');\n\nexport interface ServerFnsFeature {\n providers: Provider[];\n}\n\n/** `withServerFnInterceptors([...])` — registers the chain (DI, ordered). */\nexport function withServerFnInterceptors(\n interceptors: ServerFnInterceptorFn[],\n): ServerFnsFeature {\n return {\n providers: interceptors.map((fn) => ({\n provide: SERVER_FN_INTERCEPTORS,\n useValue: fn,\n multi: true,\n })),\n };\n}\n\n/** `provideServerFns(withServerFnInterceptors(...))` — mirrors provideHttpClient. */\nexport function provideServerFns(...features: ServerFnsFeature[]): Provider[] {\n return features.flatMap((f) => f.providers);\n}\n\nfunction makeCtx(\n input: unknown,\n context: ServerFnContext,\n): ServerFnInterceptorContext {\n return {\n input,\n context,\n with(patch) {\n return makeCtx(input, { ...context, ...patch } as ServerFnContext);\n },\n };\n}\n\n/**\n * Run the interceptor chain, then the handler, threading the context.\n *\n * `runInCtx` re-establishes the DI injection context around each interceptor\n * and the handler individually. This is what keeps `inject()` working in a\n * handler even when an upstream interceptor `await`s before calling `next`\n * (which would otherwise resume outside Angular's synchronous injection\n * context). It defaults to a pass-through for non-DI callers/tests.\n */\nexport async function runInterceptors(\n interceptors: ServerFnInterceptorFn[],\n input: unknown,\n handler: (\n input: unknown,\n context: ServerFnContext,\n ) => Promise<unknown> | unknown,\n runInCtx: <T>(fn: () => T) => T = (fn) => fn(),\n): Promise<unknown> {\n let i = -1;\n const dispatch: ServerFnNext = async (ctx) => {\n i += 1;\n if (i < interceptors.length) {\n return runInCtx(() => interceptors[i](ctx, dispatch));\n }\n return runInCtx(() => handler(ctx.input, ctx.context));\n };\n return dispatch(makeCtx(input, {} as ServerFnContext));\n}\n","/**\n * Same-origin enforcement for the server-function HTTP transport.\n *\n * Server functions are same-origin RPC: a client proxy only ever calls the\n * relative `/_analog/fn/:id` URL of its own app. A cross-origin page must not be\n * able to invoke them against a logged-in user (a CSRF-shaped attack), so the\n * transport rejects browser requests whose origin is not the app's own — out of\n * the box, with no per-app configuration.\n *\n * The signals used (`Sec-Fetch-Site`, `Origin`) are added by the browser and\n * cannot be forged by a cross-origin page's `fetch`. Non-browser callers (curl,\n * server-to-server, SSR in-process) send neither, so they are unaffected: the\n * guard blocks the cross-origin browser attack it is meant to, and nothing else.\n */\n\nimport { InjectionToken } from '@angular/core';\n\nimport type { ServerFnsFeature } from './interceptors';\n\n/** Node/h3 header bag shape (`IncomingHttpHeaders`). */\nexport type HeaderBag = Record<string, string | string[] | undefined>;\n\n/**\n * Origins permitted beyond the app's own, registered through DI:\n * `provideServerFns(withAllowedOrigins([...]))`. Empty by default — the\n * transport is same-origin unless an app opts out explicitly.\n */\nexport const SERVER_FN_ALLOWED_ORIGINS: InjectionToken<string[]> =\n new InjectionToken<string[]>('SERVER_FN_ALLOWED_ORIGINS');\n\n/**\n * `withAllowedOrigins([...])` — permit cross-origin browser calls from the\n * listed origins, or pass `'*'` to disable the same-origin guard entirely.\n * Server functions are frequently cookie-authenticated, so this is an explicit\n * opt-out of CSRF protection: allow-list the exact origins you control.\n */\nexport function withAllowedOrigins(origins: string[]): ServerFnsFeature {\n return {\n providers: origins.map((origin) => ({\n provide: SERVER_FN_ALLOWED_ORIGINS,\n useValue: origin,\n multi: true,\n })),\n };\n}\n\nfunction firstHeader(value: string | string[] | undefined): string | undefined {\n return Array.isArray(value) ? value[0] : value;\n}\n\n/**\n * Whether an HTTP request to a server function may proceed.\n *\n * Allowed when the request is same-origin, carries no browser-origin signal at\n * all (a non-browser client, or a same-origin GET that omits `Origin`), or its\n * `Origin` is listed in `allowedOrigins`. Passing `'*'` in `allowedOrigins`\n * disables the check — the explicit opt-in to cross-origin access.\n *\n * `Sec-Fetch-Site` is the authoritative signal when present: `same-origin` and\n * `none` (a direct navigation, not a cross-site fetch) pass; `same-site` and\n * `cross-site` require an explicit `allowedOrigins` entry. When the header is\n * absent (older browsers, some proxies) the `Origin` host is compared to the\n * request host as a fallback.\n */\nexport function isServerFnOriginAllowed(\n headers: HeaderBag,\n allowedOrigins: readonly string[] = [],\n): boolean {\n if (allowedOrigins.includes('*')) {\n return true;\n }\n\n const origin = firstHeader(headers['origin']);\n const originAllowlisted =\n origin !== undefined && allowedOrigins.includes(origin);\n\n const site = firstHeader(headers['sec-fetch-site']);\n if (site) {\n if (site === 'same-origin' || site === 'none') {\n return true;\n }\n // same-site / cross-site: only when the origin is explicitly permitted.\n return originAllowlisted;\n }\n\n // No `Sec-Fetch-Site`: fall back to comparing the `Origin` host to the host.\n if (!origin) {\n // Non-browser client, or a same-origin GET with no `Origin` — not the\n // cross-origin browser request this guard exists to reject.\n return true;\n }\n if (originAllowlisted) {\n return true;\n }\n\n const host =\n firstHeader(headers['x-forwarded-host']) ?? firstHeader(headers['host']);\n if (!host) {\n return false;\n }\n try {\n return new URL(origin).host === host;\n } catch {\n return false;\n }\n}\n","import {\n Injector,\n runInInjectionContext,\n type StaticProvider,\n} from '@angular/core';\nimport { BASE_URL, LOCALE, REQUEST, RESPONSE } from '@analogjs/router/tokens';\nimport type { H3Event } from 'h3';\n\nimport { detectLocale, getBaseUrl } from '../provide-server-context';\nimport { serverFnRegistry } from './registry';\nimport { assertNodeContext } from './node-context';\nimport { SERVER_FN_INTERCEPTORS, runInterceptors } from './interceptors';\nimport {\n SERVER_FN_ALLOWED_ORIGINS,\n isServerFnOriginAllowed,\n type HeaderBag,\n} from './same-origin';\n\nexport interface DispatchResult {\n status: number;\n body: unknown;\n /**\n * Headers from a returned `Response` (`fail`/`redirect`): Location, … The\n * value is an array when the header legitimately repeats, which is why\n * `Set-Cookie` is read separately below — collapsing several cookies into one\n * comma-joined value corrupts them.\n */\n headers?: Record<string, string | string[]>;\n}\n\nexport interface DispatchServerFnOptions {\n /**\n * The app's environment injector. The per-request injector is created as its\n * child, so handlers resolve app services (and `providedIn: 'root'` services,\n * when this is the app's bootstrapped injector) and registered interceptors\n * without re-listing them per request.\n */\n parent?: Injector;\n /** Extra per-request providers, for direct callers without an app injector. */\n providers?: StaticProvider[];\n /** Request HTTP method; enforced against the function's configured method. */\n method?: string;\n /**\n * Origins permitted beyond same-origin, merged with any registered through DI\n * (`provideServerFns(withAllowedOrigins([...]))`). The transport is\n * same-origin by default (cross-origin browser calls are rejected with 403);\n * `'*'` disables the check entirely. Only consulted for HTTP-transport calls\n * (those that pass `method`).\n */\n allowedOrigins?: string[];\n}\n\n/**\n * Server-side dispatch for a server function call.\n *\n * 1. reject cross-origin browser calls (403), unless allow-listed — HTTP\n * transport only (in-process callers omit `method` and are exempt)\n * 2. look up the function by id\n * 3. enforce the configured HTTP method (405 on mismatch)\n * 4. require a JSON body on input-bearing calls (415 otherwise)\n * 5. validate `input` against the Standard-Schema (4xx on failure)\n * 6. build a per-request injector (REQUEST/RESPONSE + app providers)\n * 7. run the interceptor chain, then the handler, re-entering\n * `runInInjectionContext` at every hop so `inject()` works even after an\n * interceptor `await`s before calling `next`\n * 8. a `Response` returned by an interceptor/handler (`fail`/`redirect`)\n * short-circuits with its status AND headers\n *\n * `options.method` is the request's HTTP method; when provided it is enforced\n * against the function's configured method AND it turns on the same-origin\n * guard. Transports (the generated Nitro handler) always pass it; trusted\n * in-process callers may omit it, which also exempts them from the origin guard.\n */\nexport async function dispatchServerFn(\n id: string,\n rawInput: unknown,\n event: Pick<H3Event, 'node'>,\n options: DispatchServerFnOptions = {},\n): Promise<DispatchResult> {\n const { parent, providers = [], method, allowedOrigins = [] } = options;\n const node = assertNodeContext(event);\n const headers = (node.req.headers ?? {}) as HeaderBag;\n\n // Same-origin guard runs first — before we even confirm the function exists —\n // so a cross-origin page cannot probe which ids are registered. Gated on\n // `method` so only HTTP-transport calls are checked; in-process callers omit\n // it. The signals (`Origin`/`Sec-Fetch-Site`) are browser-set and unforgeable.\n if (method) {\n const allowed = [\n ...allowedOrigins,\n ...(parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []),\n ];\n if (!isServerFnOriginAllowed(headers, allowed)) {\n return {\n status: 403,\n body: { message: 'Cross-origin server function call rejected' },\n };\n }\n }\n\n const def = serverFnRegistry.get(id);\n if (!def) {\n return { status: 404, body: { message: `Unknown server function: ${id}` } };\n }\n\n // Enforce the transport method: a GET-only read must not be POSTable, and an\n // input-bearing POST must not be reachable via GET.\n if (method && method.toUpperCase() !== def.method) {\n return {\n status: 405,\n body: { message: `Method ${method} not allowed for ${id}` },\n headers: { Allow: def.method },\n };\n }\n\n // Input travels as a JSON body. Reject anything else before decoding, so a\n // form post from a cross-origin page (which cannot set a JSON content type\n // without a CORS preflight) never reaches a handler. HTTP transport only.\n if (method && def.method === 'POST' && !isJsonContentType(headers)) {\n return {\n status: 415,\n body: { message: 'Server functions accept an application/json body' },\n };\n }\n\n let input = rawInput;\n if (def.config.input) {\n const result = await def.config.input['~standard'].validate(rawInput);\n if ('issues' in result && result.issues) {\n return { status: 400, body: { errors: result.issues } };\n }\n input = (result as { value: unknown }).value;\n }\n\n // Child of the app injector: only the request tokens are per-request; app\n // services + interceptors resolve up the parent chain. All four are provided\n // here so a handler resolves them the same way it would inside a component\n // during SSR, whether it was reached over HTTP or in-process.\n const req = node.req as Parameters<typeof getBaseUrl>[0];\n const locale = detectLocale(req);\n const injector = Injector.create({\n parent,\n providers: [\n { provide: REQUEST, useValue: node.req },\n { provide: RESPONSE, useValue: node.res },\n { provide: BASE_URL, useValue: getBaseUrl(req) },\n ...(locale ? [{ provide: LOCALE, useValue: locale }] : []),\n ...providers,\n ],\n });\n\n // Re-enter the injection context at each hop rather than wrapping the whole\n // chain once: an interceptor that awaits before `next` would otherwise run the\n // handler outside the context and break `inject()`.\n const runInCtx = <T>(fn: () => T): T => runInInjectionContext(injector, fn);\n const interceptors = injector.get(SERVER_FN_INTERCEPTORS, []);\n const outcome = await runInterceptors(\n interceptors,\n input,\n def.handler,\n runInCtx,\n );\n\n if (outcome instanceof Response) {\n const text = await outcome.text();\n const body = text ? safeJson(text) : null;\n const headers: Record<string, string | string[]> = {};\n outcome.headers.forEach((value, key) => {\n if (key.toLowerCase() !== 'set-cookie') {\n headers[key] = value;\n }\n });\n // `Headers.forEach` yields cookies comma-joined into a single value, which\n // is not a valid way to send more than one; `getSetCookie` keeps them apart.\n const setCookie = outcome.headers.getSetCookie?.() ?? [];\n if (setCookie.length) {\n headers['set-cookie'] = setCookie;\n }\n return {\n status: outcome.status,\n body,\n headers: Object.keys(headers).length ? headers : undefined,\n };\n }\n\n return { status: 200, body: outcome };\n}\n\nfunction isJsonContentType(headers: HeaderBag): boolean {\n const contentType = headers['content-type'];\n const value = Array.isArray(contentType) ? contentType[0] : contentType;\n if (!value) {\n return false;\n }\n const mediaType = value.split(';')[0].trim().toLowerCase();\n return mediaType === 'application/json' || mediaType.endsWith('+json');\n}\n\nfunction safeJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n","import { Injector } from '@angular/core';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport type { ServerRequest, ServerResponse } from '@analogjs/router/tokens';\nimport type { ServerFn, ServerFnDispatcher } from '@analogjs/router';\nimport type { H3Event } from 'h3';\n\nimport { dispatchServerFn } from './dispatch';\n\n/**\n * The in-process transport used during SSR. `ServerFnClient` picks this up from\n * DI and calls the handler directly instead of issuing an HTTP request back\n * into the app — the render and the handler already share a process and a\n * request, so the round-trip only adds latency (and would need an absolute URL).\n *\n * `method` is deliberately not passed to `dispatchServerFn`: this is a trusted\n * in-process caller, so the HTTP-transport-only checks (same-origin, method\n * enforcement, content type) do not apply. Validation and the interceptor chain\n * still run, so an SSR call behaves like a browser call in every other respect.\n *\n * A non-2xx result is thrown as an `HttpErrorResponse` so the failure surfaces\n * on `resource.error()` exactly as it does in the browser.\n */\nexport function createServerFnDispatcher(\n req: ServerRequest,\n res: ServerResponse,\n): ServerFnDispatcher {\n const event = { node: { req, res } } as unknown as Pick<H3Event, 'node'>;\n\n return async <In, Out>(\n fn: ServerFn<In, Out>,\n input: In,\n injector: Injector,\n ): Promise<Out> => {\n const { status, body } = await dispatchServerFn(fn.id, input, event, {\n parent: injector,\n });\n\n if (status < 200 || status > 299) {\n throw new HttpErrorResponse({ status, error: body, url: fn.url });\n }\n\n return body as Out;\n };\n}\n","import { StaticProvider, ɵresetCompiledComponents } from '@angular/core';\nimport { ɵSERVER_CONTEXT as SERVER_CONTEXT } from '@angular/platform-server';\n\nimport {\n BASE_URL,\n INTERNAL_FETCH,\n LOCALE,\n REQUEST,\n RESPONSE,\n ServerInternalFetch,\n ServerRequest,\n ServerResponse,\n} from '../../tokens/src/index.js';\nimport { SERVER_FN_DISPATCHER } from '@analogjs/router';\n\nimport { createServerFnDispatcher } from './server-fn/ssr-dispatcher';\n\ndeclare const ANALOG_I18N_FIXED_LOCALE: string | undefined;\n\nfunction getHeaderValue(\n value: string | string[] | undefined,\n): string | undefined {\n return Array.isArray(value) ? value[0] : value;\n}\n\nfunction getRequestHeader(\n req: ServerRequest,\n name: string,\n): string | undefined {\n const headers = (req as { headers?: unknown }).headers;\n\n if (!headers) {\n return undefined;\n }\n\n if (\n typeof headers === 'object' &&\n headers !== null &&\n 'get' in headers &&\n typeof headers.get === 'function'\n ) {\n return headers.get(name) ?? undefined;\n }\n\n return getHeaderValue(\n (headers as Record<string, string | string[] | undefined>)[name],\n );\n}\n\nexport function provideServerContext({\n req,\n res,\n fetch,\n}: {\n req: ServerRequest;\n res: ServerResponse;\n fetch?: ServerInternalFetch;\n}): StaticProvider[] {\n const baseUrl = getBaseUrl(req);\n // A locale worker from @analogjs/vite-plugin-nitro renders a single locale.\n const locale =\n (typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&\n ANALOG_I18N_FIXED_LOCALE) ||\n detectLocale(req);\n\n // Optional chaining: a Nitro-bundled caller has no `import.meta.env` at all.\n if (import.meta.env?.DEV) {\n ɵresetCompiledComponents();\n }\n\n return [\n { provide: SERVER_CONTEXT, useValue: 'ssr-analog' },\n { provide: REQUEST, useValue: req },\n { provide: RESPONSE, useValue: res },\n { provide: BASE_URL, useValue: baseUrl },\n { provide: INTERNAL_FETCH, useValue: fetch },\n // Server functions called while rendering run in-process, in this injector.\n {\n provide: SERVER_FN_DISPATCHER,\n useValue: createServerFnDispatcher(req, res),\n },\n ...(locale ? [{ provide: LOCALE, useValue: locale }] : []),\n ];\n}\n\nexport function getBaseUrl(req: ServerRequest): string {\n const protocol = getRequestProtocol(req);\n const host =\n getRequestHeader(req, 'x-forwarded-host') ??\n getRequestHeader(req, 'host') ??\n 'localhost';\n const originalUrl = req.originalUrl || req.url || '/';\n const parsedUrl = new URL(\n '',\n `${protocol}://${host}${\n originalUrl.endsWith('/')\n ? originalUrl.substring(0, originalUrl.length - 1)\n : originalUrl\n }`,\n );\n const baseUrl = parsedUrl.origin;\n\n return baseUrl;\n}\n\nexport function getRequestProtocol(\n req: ServerRequest,\n opts: { xForwardedProto?: boolean } = {},\n): string {\n const forwardedProto = getRequestHeader(req, 'x-forwarded-proto')\n ?.split(',')[0]\n ?.trim();\n\n if (opts.xForwardedProto !== false && forwardedProto === 'https') {\n return 'https';\n }\n\n return (req.connection as { encrypted?: boolean })?.encrypted\n ? 'https'\n : 'http';\n}\n\n/**\n * Detects the locale from the request URL path prefix or Accept-Language header.\n * URL prefix takes priority (e.g. /fr/about -> 'fr').\n */\nexport function detectLocale(req: ServerRequest): string | undefined {\n const url = req.originalUrl || req.url || '';\n const localeFromUrl = extractLocaleFromUrl(url);\n if (localeFromUrl) {\n return localeFromUrl;\n }\n\n return parseAcceptLanguage(getRequestHeader(req, 'accept-language'));\n}\n\n/**\n * Extracts a locale from the first URL path segment if it matches\n * a BCP 47-like pattern (e.g. 'en', 'en-US', 'zh-Hans-CN').\n */\nexport function extractLocaleFromUrl(url: string): string | undefined {\n const pathname = url.split('?')[0];\n const segments = pathname.split('/').filter(Boolean);\n if (segments.length === 0) {\n return undefined;\n }\n\n const firstSegment = segments[0];\n // Match BCP 47 language tags: 2-letter language code with optional region/script\n if (/^[a-z]{2}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2}|\\d{3})?$/.test(firstSegment)) {\n return firstSegment;\n }\n\n return undefined;\n}\n\n/**\n * Parses the Accept-Language header and returns the most preferred language.\n */\nexport function parseAcceptLanguage(\n header: string | undefined,\n): string | undefined {\n if (!header) {\n return undefined;\n }\n\n const locales = header\n .split(',')\n .map((part) => {\n const [locale, qPart] = part.trim().split(';');\n const q = qPart ? parseFloat(qPart.replace('q=', '')) : 1;\n return { locale: locale.trim(), q };\n })\n .sort((a, b) => b.q - a.q);\n\n return locales[0]?.locale || undefined;\n}\n","declare const ANALOG_I18N_FIXED_LOCALE: string | undefined;\n\n/**\n * Nulls `def.tView` on every component definition that Angular has\n * compiled in this process. Angular caches the result of `consts()` on\n * `def.tView` — that factory is where `$localize` tagged templates are\n * evaluated — so without this reset the first rendered locale would be\n * frozen into the cache for the process lifetime.\n *\n * The set on `globalThis.__ngComponentDefs` is populated by a Vite\n * transform in `@analogjs/platform` that patches `@angular/core`'s\n * `getComponentId()` to mirror every compiled component definition to\n * a global Set, bypassing the `ngServerMode` guard that normally\n * prevents registration on the server.\n */\nexport function resetComponentDefTViews(): void {\n if (\n typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&\n ANALOG_I18N_FIXED_LOCALE\n )\n return;\n const defs = (globalThis as any).__ngComponentDefs as Set<any> | undefined;\n if (!defs) return;\n for (const def of defs) {\n def.tView = null;\n }\n}\n","import {\n ApplicationConfig,\n Provider,\n Type,\n enableProdMode,\n} from '@angular/core';\nimport {\n bootstrapApplication,\n type BootstrapContext,\n} from '@angular/platform-browser';\nimport { renderApplication } from '@angular/platform-server';\nimport type { ServerContext } from '../../tokens/src/index.js';\n\nimport { provideServerContext } from './provide-server-context';\nimport { resetComponentDefTViews } from './utils/reset-component-def-tviews';\n\n// Optional chaining: the server-function dispatch endpoint imports this entry\n// from a Nitro bundle, where `import.meta.env` is not defined at all.\nif (import.meta.env?.PROD) {\n enableProdMode();\n}\n\n/**\n * Returns a function that accepts the navigation URL,\n * the root HTML, and server context.\n *\n * @param rootComponent\n * @param config\n * @param platformProviders\n * @returns Promise<string>\n */\nexport function render(\n rootComponent: Type<unknown>,\n config: ApplicationConfig,\n platformProviders: Provider[] = [],\n) {\n function bootstrap(context: BootstrapContext) {\n return bootstrapApplication(rootComponent, config, context);\n }\n\n return async function render(\n url: string,\n document: string,\n serverContext: ServerContext,\n ): Promise<string> {\n resetComponentDefTViews();\n\n const html = await renderApplication(bootstrap, {\n document,\n url,\n platformProviders: [\n provideServerContext(serverContext),\n platformProviders,\n ],\n });\n\n return html;\n };\n}\n","/**\n * Pure string helpers for slicing a fully rendered SSR document into the parts\n * the streaming renderer flushes: the shell up to `<body>`, the authoritative\n * `<body>` inner HTML for the tail, and the authoritative `<head>` inner HTML\n * for the finalize-time head reconcile. Extracted from `render-stream` so they\n * can be unit tested without driving the platform.\n */\n\n/** Byte offset just after the opening `<body>` tag, or 0 if none. */\nexport function afterBodyOpen(html: string): number {\n const m = /<body[^>]*>/i.exec(html);\n return m ? m.index + m[0].length : 0;\n}\n\n/** Inner HTML of `<body>` from a fully rendered document string. */\nexport function bodyInner(html: string): string {\n const start = afterBodyOpen(html);\n const end = html.lastIndexOf('</body>');\n return html.slice(start, end > -1 ? end : html.length);\n}\n\n/** Inner HTML of `<head>` from a fully rendered document string. */\nexport function headInner(html: string): string {\n const open = /<head[^>]*>/i.exec(html);\n if (!open) return '';\n const start = open.index + open[0].length;\n const end = html.indexOf('</head>', start);\n return html.slice(start, end > -1 ? end : start);\n}\n","import { runInInjectionContext, type PlatformRef } from '@angular/core';\nimport { PlatformState } from '@angular/platform-server';\n\n/** Preload bootstrap modules, but leave execution to the authoritative tail. */\nexport function createStreamShell(platform: PlatformRef): string {\n const state = platform.injector.get(PlatformState);\n const document = (state.getDocument() as Document).cloneNode(\n true,\n ) as Document;\n for (const script of Array.from(\n document.head.querySelectorAll('script[type=\"module\"]'),\n )) {\n const src = script.getAttribute('src');\n if (src) {\n const preload = document.createElement('link');\n preload.setAttribute('rel', 'modulepreload');\n preload.setAttribute('href', src);\n for (const name of [\n 'crossorigin',\n 'integrity',\n 'referrerpolicy',\n 'nonce',\n 'fetchpriority',\n ]) {\n const value = script.getAttribute(name);\n if (value !== null) preload.setAttribute(name, value);\n }\n script.parentNode!.replaceChild(preload, script);\n } else {\n script.parentNode!.removeChild(script);\n }\n }\n while (document.body.firstChild)\n document.body.removeChild(document.body.firstChild);\n const html = runInInjectionContext(platform.injector, () =>\n new PlatformState(document).renderToString(),\n );\n return html.slice(0, html.lastIndexOf('</body>'));\n}\n","import type { ServerContext } from '@analogjs/router/tokens';\n\n/**\n * Per-request decisions about whether the streaming renderer should fall back\n * to a buffered render. Extracted from `render-stream` so they can be unit\n * tested without driving the platform.\n */\n\n/**\n * User agents that receive a fully buffered render (with a resolved `<head>`)\n * instead of the streamed shell. Streaming flushes the head before the app has\n * set a dynamic title/meta and reconciles it via a finalize script; a crawler\n * that does not run that script would index the shell's static head. Mirrors\n * Nuxt's bot bypass — streaming targets interactive clients, bots get the\n * buffered path whose head is byte-identical to the classic `render()`.\n */\nexport const SSR_BOT_RE: RegExp =\n /bot|crawl|spider|slurp|mediapartners|facebookexternalhit|embedly|quora link preview|outbrain|pinterest|vkshare|w3c_validator|whatsapp|telegrambot|lighthouse|google-inspectiontool|headlesschrome|bingpreview/i;\n\nexport function isLikelyBot(serverContext: ServerContext): boolean {\n const ua = serverContext?.req?.headers?.['user-agent'];\n return typeof ua === 'string' && SSR_BOT_RE.test(ua);\n}\n\n/**\n * Whether streaming is disabled for this request by a `streaming: false` route\n * rule. The platform plugin translates that rule into an `x-analog-no-streaming`\n * response header (mirroring how `ssr: false` becomes `x-analog-no-ssr`); when\n * present, `renderStream` produces the buffered `render()` output for this\n * route instead of streaming. On Nitro v3, which renders without a Node\n * response, the header is forwarded on the request instead.\n */\nexport function streamingDisabledByRoute(\n serverContext: ServerContext,\n): boolean {\n if (serverContext?.streaming !== undefined) {\n return !serverContext.streaming;\n }\n\n return (\n serverContext?.res?.getHeader?.('x-analog-no-streaming') === 'true' ||\n serverContext?.req?.headers?.['x-analog-no-streaming'] === 'true'\n );\n}\n","/**\n * Tiny client runtime for progressive streaming SSR — EXPERIMENTAL.\n *\n * `renderStream` streams the document in three parts:\n * 1. the head + this runtime + an empty `<div data-analog-stream>` region;\n * 2. each `@defer` block, as it resolves on the server, as a\n * `<template data-analog-defer=\"ID\">…</template>` followed by a call to\n * `window.__analogPaint(\"ID\")` — this runtime paints the block into the\n * streaming region immediately, so content appears progressively and out\n * of document order;\n * 3. the authoritative document tail: the app's resolved `<head>` in a\n * `<template data-analog-head>` and the hydration-annotated body in a\n * `<template data-analog-authoritative>`, followed by\n * `window.__analogReconcileHead()` + `window.__analogFinalize()`. The head\n * is reconciled first (a dynamically-set `<title>`/meta is applied to the\n * live document, since the streamed shell head was flushed before the app\n * ran), then the body is swapped to the exact document Angular's\n * incremental hydration expects.\n *\n * Emitted into the document by `renderStream`. Exported as a string so it can\n * be injected verbatim and unit-tested against a DOM.\n */\nexport const DEFER_RECONCILE_RUNTIME = /* js */ `\n(function () {\n var completed = false;\n var headModules = [];\n function activateModule(source) {\n var script = document.createElement('script');\n Array.from(source.attributes).forEach(function (attr) {\n script.setAttribute(attr.name, attr.value);\n });\n if (source.hasAttribute('nonce')) script.nonce = source.nonce;\n if (!source.hasAttribute('async')) script.async = false;\n script.textContent = source.textContent;\n return script;\n }\n function region() {\n return document.querySelector('[data-analog-stream]');\n }\n function showError() {\n document.title = 'Unable to load this page';\n var robots = document.head.querySelector('meta[name=\"robots\"]');\n if (!robots) {\n robots = document.createElement('meta');\n robots.setAttribute('name', 'robots');\n document.head.appendChild(robots);\n }\n robots.setAttribute('content', 'noindex');\n var error = document.createElement('main');\n error.setAttribute('data-analog-render-error', '');\n error.setAttribute('role', 'alert');\n var heading = document.createElement('h1');\n heading.textContent = 'Unable to load this page';\n var message = document.createElement('p');\n message.textContent = 'The page could not finish loading.';\n error.appendChild(heading);\n error.appendChild(message);\n document.body.replaceChildren(error);\n }\n function checkCompletion() {\n if (!completed && region()) showError();\n }\n window.__analogFail = showError;\n // A Worker HTTP adapter can turn a stream error into ordinary EOF. The\n // authoritative tail, rather than transport completion, proves SSR success.\n document.addEventListener('DOMContentLoaded', checkCompletion, { once: true });\n window.__analogPaint = function (id) {\n var tpl = document.querySelector('template[data-analog-defer=\"' + id + '\"]');\n var r = region();\n if (!tpl || !r) return;\n r.appendChild(tpl.content.cloneNode(true));\n tpl.remove();\n };\n window.__analogReconcileHead = function () {\n // The shell head was flushed before the app rendered, so any title/meta the\n // app set during render (Title/Meta services, route meta) is missing from\n // the live document. Apply the authoritative head here, before hydration —\n // matching how a buffered render would have produced the head. Idempotent:\n // tags already present (charset, viewport, stylesheet/preload links) are\n // matched and left as-is; only changed/added ones are updated.\n var tpl = document.querySelector('template[data-analog-head]');\n if (!tpl) return;\n var frag = tpl.content;\n var head = document.head;\n frag.querySelectorAll('script[type=\"module\"]').forEach(function (script) {\n headModules.push(script.cloneNode(true));\n });\n var title = frag.querySelector('title');\n if (title) document.title = title.textContent || '';\n function metaKey(m) {\n if (m.hasAttribute('charset')) return 'charset';\n var attrs = ['name', 'property', 'http-equiv', 'itemprop'];\n for (var i = 0; i < attrs.length; i++) {\n if (m.hasAttribute(attrs[i])) return attrs[i] + '=' + m.getAttribute(attrs[i]);\n }\n return null;\n }\n var existingMeta = {};\n var metas = head.querySelectorAll('meta');\n for (var i = 0; i < metas.length; i++) {\n var k = metaKey(metas[i]);\n if (k) existingMeta[k] = metas[i];\n }\n frag.querySelectorAll('meta').forEach(function (m) {\n var key = metaKey(m);\n if (key == null) return;\n if (existingMeta[key]) existingMeta[key].replaceWith(m.cloneNode(true));\n else head.appendChild(m.cloneNode(true));\n });\n var existingHref = {};\n var links = head.querySelectorAll('link[href]');\n for (var j = 0; j < links.length; j++) {\n existingHref[links[j].getAttribute('href')] = true;\n }\n frag.querySelectorAll('link').forEach(function (l) {\n var href = l.getAttribute('href');\n if (href && existingHref[href]) return;\n head.appendChild(l.cloneNode(true));\n if (href) existingHref[href] = true;\n });\n tpl.remove();\n };\n window.__analogFinalize = function () {\n var auth = document.querySelector('template[data-analog-authoritative]');\n if (!auth) return;\n completed = true;\n document.removeEventListener('DOMContentLoaded', checkCompletion);\n // Replace the entire body — preview region, block templates and runtime\n // scripts — with just the authoritative body, so the reconciled DOM matches\n // a buffered render byte-for-byte before hydration boots.\n var body = auth.content.cloneNode(true);\n var bodyModules = Array.from(body.querySelectorAll('script[type=\"module\"]'));\n document.body.replaceChildren(body);\n headModules.forEach(function (script) {\n document.head.appendChild(activateModule(script));\n });\n headModules = [];\n bodyModules.forEach(function (script) {\n script.replaceWith(activateModule(script));\n });\n };\n})();\n`;\n","/** Owns stream closure, queued block flushes and platform cleanup across completion and cancellation. */\nexport interface SsrStreamWriter {\n readonly active: boolean;\n enqueue(html: string): void;\n scheduleBlock(serialize: () => string): void;\n finishBlocks(): Promise<void>;\n}\n\nexport function createSsrStream(options: {\n signal?: AbortSignal;\n waitUntil?(task: Promise<void>): void;\n errorHtml?: string;\n render(writer: SsrStreamWriter): Promise<void>;\n destroy(): Promise<void>;\n}): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n const pending = new Map<\n ReturnType<typeof setTimeout>,\n { promise: Promise<void>; resolve(): void }\n >();\n let state: 'rendering' | 'closing' | 'closed' | 'failed' | 'cancelled' =\n 'rendering';\n let capturing = true;\n let cleanup: Promise<void> | undefined;\n let controller: ReadableStreamDefaultController<Uint8Array>;\n let keepAlive: ReturnType<typeof setInterval> | undefined;\n let complete!: () => void;\n const completed = new Promise<void>((resolve) => {\n complete = resolve;\n });\n\n function destroy(): Promise<void> {\n capturing = false;\n clearInterval(keepAlive);\n options.signal?.removeEventListener('abort', abort);\n for (const [timer, task] of pending) {\n clearTimeout(timer);\n task.resolve();\n }\n pending.clear();\n return (cleanup ??= Promise.resolve()\n .then(options.destroy)\n .finally(complete));\n }\n\n function fail(error: unknown, aborted = false): void {\n if (state !== 'rendering' && state !== 'closing') return;\n const documentComplete = state === 'closing';\n state = 'failed';\n if (options.errorHtml && !aborted) {\n console.error('[analog ssr]', error);\n if (!documentComplete)\n controller.enqueue(encoder.encode(options.errorHtml));\n controller.close();\n } else {\n controller.error(error);\n }\n // The stream already owns the original failure. Consume cleanup failures\n // here; the render finalizer and body cancellation also await cleanup.\n void destroy().catch(() => undefined);\n }\n\n function abort(): void {\n fail(\n options.signal?.reason ??\n new DOMException('The render was aborted.', 'AbortError'),\n true,\n );\n }\n\n const writer: SsrStreamWriter = {\n get active() {\n return state === 'rendering';\n },\n enqueue(html) {\n if (state === 'rendering') controller.enqueue(encoder.encode(html));\n },\n scheduleBlock(serialize) {\n if (state !== 'rendering' || !capturing) return;\n let resolve!: () => void;\n const promise = new Promise<void>((finish) => {\n resolve = finish;\n });\n const timer = setTimeout(() => {\n try {\n if (state === 'rendering') writer.enqueue(serialize());\n } catch (error) {\n fail(error);\n } finally {\n pending.delete(timer);\n resolve();\n }\n }, 0);\n pending.set(timer, { promise, resolve });\n },\n async finishBlocks() {\n capturing = false;\n await Promise.all([...pending.values()].map((task) => task.promise));\n },\n };\n\n return new ReadableStream<Uint8Array>({\n start(streamController) {\n controller = streamController;\n if (options.waitUntil) {\n options.waitUntil(completed);\n // Workers detect a disconnected HTTP client on a subsequent write.\n // Keep the stream observable while Angular waits for asynchronous data.\n keepAlive = setInterval(\n () => writer.enqueue('<!--analog-render-pending-->'),\n 1000,\n );\n }\n options.signal?.addEventListener('abort', abort, { once: true });\n if (options.signal?.aborted) abort();\n // Do not return the render promise: cancellation must be able to run\n // while bootstrap or application stability is still pending.\n void (async () => {\n try {\n if (state === 'rendering') await options.render(writer);\n if (state === 'rendering') {\n state = 'closing';\n await destroy();\n if (state === 'closing') {\n state = 'closed';\n controller.close();\n }\n }\n } catch (error) {\n fail(error);\n } finally {\n await destroy();\n }\n })().catch(fail);\n },\n cancel() {\n state = 'cancelled';\n return destroy();\n },\n });\n}\n","import {\n DestroyRef,\n ENVIRONMENT_INITIALIZER,\n inject,\n makeEnvironmentProviders,\n type EnvironmentProviders,\n} from '@angular/core';\nimport { NavigationEnd, NavigationError, Router } from '@angular/router';\n\n/** Angular can settle initial navigation after an error without rejecting renderApplication. */\nexport function createSsrNavigationTracker(): {\n provider: EnvironmentProviders;\n throwIfFailed: () => void;\n} {\n let failure: NavigationError | undefined;\n return {\n provider: makeEnvironmentProviders([\n {\n provide: ENVIRONMENT_INITIALIZER,\n multi: true,\n useValue() {\n const router = inject(Router, { optional: true });\n if (!router) return;\n const subscription = router.events.subscribe((event) => {\n if (event instanceof NavigationError) failure = event;\n else if (event instanceof NavigationEnd) failure = undefined;\n });\n inject(DestroyRef).onDestroy(() => subscription.unsubscribe());\n },\n },\n ]),\n throwIfFailed(): void {\n if (failure) throw failure.error;\n },\n };\n}\n","/**\n * Progressive streaming SSR renderer — EXPERIMENTAL.\n *\n * Returns a `ReadableStream<Uint8Array>` that flushes bytes DURING the render,\n * not after it:\n * 1. the document head + a client reconcile runtime are flushed immediately,\n * before the app has finished rendering, so the browser starts fetching\n * assets right away;\n * 2. each `@defer (hydrate …)` block's content is flushed the moment it\n * resolves on the server — out of document order — while later blocks are\n * still pending (proven: a slow block does not hold back an early one);\n * 3. once the app is stable, the authoritative, fully hydration-annotated\n * document is flushed as the tail. This is byte-identical to a buffered\n * `renderApplication`, and is what Angular's incremental hydration runs\n * against on the client.\n *\n * Unlike a buffered renderer, this drives the platform directly\n * (`platformServer` + `bootstrapApplication` + `ɵrenderInternal`) so it can\n * interleave flushes with rendering. Angular's hydration annotation is\n * whole-document (the root's `ngh` index references every `@defer` container),\n * so the authoritative hydration payload is necessarily the tail: RENDERING\n * streams progressively, and hydration begins once the tail arrives.\n *\n * Depends on an upstream Angular per-block resolution hook exposed on two\n * globals (see {@link SsrStreamingGlobals}). When the primitive is absent,\n * `renderStream` degrades to a single buffered chunk so behaviour matches the\n * classic `render()` path, which is unchanged and remains the default.\n */\nimport {\n ApplicationConfig,\n Provider,\n Type,\n enableProdMode,\n} from '@angular/core';\nimport {\n bootstrapApplication,\n type BootstrapContext,\n} from '@angular/platform-browser';\nimport {\n renderApplication,\n platformServer,\n INITIAL_CONFIG,\n ɵrenderInternal as renderInternal,\n} from '@angular/platform-server';\nimport type { PlatformRef } from '@angular/core';\nimport type { ServerContext } from '@analogjs/router/tokens';\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport { provideServerContext } from './provide-server-context';\nimport { resetComponentDefTViews } from './utils/reset-component-def-tviews';\nimport { bodyInner, headInner } from './utils/stream-html';\nimport { createStreamShell } from './utils/stream-shell';\nimport { isLikelyBot, streamingDisabledByRoute } from './utils/stream-request';\nimport { DEFER_RECONCILE_RUNTIME } from './defer-reconcile-runtime';\nimport { createSsrStream } from './utils/ssr-stream-lifecycle';\nimport { createSsrNavigationTracker } from './ssr-navigation';\n\nif (import.meta.env?.PROD) {\n enableProdMode();\n}\n\n/**\n * Shape of the upstream Angular streaming primitive we consume, published on\n * `globalThis` by the streaming-enabled `@angular/core` build (see the\n * `deferStreamingPlugin` in `@analogjs/platform`):\n * - `__analogSsrDeferCapture` — the patched core invokes it once per resolved\n * `@defer` block on the server, passing the block's live `lContainer`. We\n * install a stable dispatcher here that routes to the current render (see\n * `installCaptureDispatcher`).\n * - `__analogSsrInternals.collectNativeNodesInLContainer` — collects a block's\n * rendered root nodes so we can serialize them via domino `outerHTML`.\n */\ninterface SsrStreamingGlobals {\n __analogSsrDeferCapture?: (ev: {\n ssrUniqueId: string | null;\n lContainer: unknown;\n }) => void;\n __analogSsrInternals?: {\n collectNativeNodesInLContainer?: (\n lContainer: unknown,\n out: unknown[],\n ) => void;\n };\n}\n\nfunction streamingPrimitiveAvailable(): boolean {\n const g: typeof globalThis & SsrStreamingGlobals = globalThis;\n return (\n typeof g.__analogSsrInternals?.collectNativeNodesInLContainer === 'function'\n );\n}\n\ntype DeferCaptureEvent = { ssrUniqueId: string | null; lContainer: unknown };\ntype DeferCaptureHandler = (ev: DeferCaptureEvent) => void;\n\n/**\n * Per-render capture handlers live in async-local storage, not a single shared\n * global slot, so concurrent renders in one process do not clobber each other.\n * `globalThis.__analogSsrDeferCapture` is a stable dispatcher installed once; it\n * routes each resolved `@defer` block to the handler of the render whose async\n * context it fired in. A block that resolves outside any render (no store) is a\n * no-op.\n */\nconst captureStore = new AsyncLocalStorage<DeferCaptureHandler>();\nconst CAPTURE_ZONE_KEY = 'analogSsrDeferCapture';\ninterface CaptureZone {\n fork(spec: {\n name: string;\n properties: Record<string, DeferCaptureHandler>;\n }): CaptureZone;\n run<T>(callback: () => T): T;\n get(key: typeof CAPTURE_ZONE_KEY): DeferCaptureHandler | undefined;\n}\n\nfunction currentCaptureZone(): CaptureZone | undefined {\n const host: typeof globalThis & { Zone?: { current: CaptureZone } } =\n globalThis;\n return host.Zone?.current;\n}\n\nfunction runWithCapture<T>(handler: DeferCaptureHandler, render: () => T): T {\n const zone = currentCaptureZone();\n return captureStore.run(handler, () =>\n zone === undefined\n ? render()\n : zone\n .fork({\n name: 'analog-ssr-capture',\n properties: { [CAPTURE_ZONE_KEY]: handler },\n })\n .run(render),\n );\n}\n\nfunction installCaptureDispatcher(): void {\n const g: typeof globalThis & {\n __analogSsrDeferCapture?: DeferCaptureHandler & {\n __analogDispatcher?: boolean;\n };\n } = globalThis;\n if (g.__analogSsrDeferCapture?.__analogDispatcher) return;\n const dispatch: DeferCaptureHandler & { __analogDispatcher?: boolean } = (\n ev,\n ) => {\n const zoneHandler = currentCaptureZone()?.get(CAPTURE_ZONE_KEY);\n (zoneHandler ?? captureStore.getStore())?.(ev);\n };\n dispatch.__analogDispatcher = true;\n g.__analogSsrDeferCapture = dispatch;\n}\n\nlet warnedMissingPrimitive = false;\nfunction warnMissingPrimitiveOnce(): void {\n if (warnedMissingPrimitive || !import.meta.env?.DEV) return;\n warnedMissingPrimitive = true;\n console.warn(\n '[@analogjs/router] renderStream: the streaming hook was not found on ' +\n '@angular/core, so rendering falls back to buffered. Enable ' +\n '`experimental.streaming` in your Analog config; if it already is, your ' +\n 'installed Angular version may be incompatible with the streaming patch.',\n );\n}\n\n/**\n * Serialize a `@defer` block's live domino subtree to HTML. Called a macrotask\n * after the block resolves, by which point change detection has filled in the\n * block's interpolations.\n */\nfunction serializeLContainerHtml(lContainer: unknown): string {\n const g: typeof globalThis & SsrStreamingGlobals = globalThis;\n const collect = g.__analogSsrInternals?.collectNativeNodesInLContainer;\n if (!collect) return '';\n const nodes: {\n nodeType: number;\n outerHTML?: string;\n data?: string;\n nodeValue?: string;\n }[] = [];\n collect(lContainer, nodes);\n let html = '';\n for (const node of nodes) {\n if (node.nodeType === 1) html += node.outerHTML ?? '';\n else if (node.nodeType === 3)\n html += (node.data ?? node.nodeValue ?? '')\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;');\n }\n return html;\n}\n\n/** Destroy the platform on a macrotask, matching `renderApplication`. */\nfunction asyncDestroyPlatform(platformRef: PlatformRef): Promise<void> {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n try {\n platformRef.destroy();\n resolve();\n } catch (error) {\n reject(error);\n }\n }, 0);\n });\n}\n\n/**\n * Returns a function that renders a URL to a `ReadableStream<Uint8Array>`.\n *\n * Usage in main.server.ts:\n * ```ts\n * import { renderStream } from '@analogjs/router/server';\n * export default renderStream(App, config);\n * ```\n */\nexport function renderStream(\n rootComponent: Type<unknown>,\n config: ApplicationConfig,\n platformProviders: Provider[] = [],\n) {\n return async function renderStream(\n url: string,\n document: string,\n serverContext: ServerContext,\n ): Promise<ReadableStream<Uint8Array>> {\n serverContext.signal?.throwIfAborted();\n const navigation = createSsrNavigationTracker();\n const applicationConfig = {\n ...config,\n providers: [...config.providers, navigation.provider],\n };\n const bootstrap = (context: BootstrapContext) =>\n bootstrapApplication(rootComponent, applicationConfig, context);\n // Reset before every render — both the buffered fallback below and the\n // streaming path — so a prior render's locale/consts are not frozen for the\n // process lifetime (parity with render.ts).\n resetComponentDefTViews();\n\n // Fall back to a single buffered chunk so output matches the classic path\n // for:\n // - crawlers, which may not run the finalize script that reconciles a\n // dynamic <head>, so they get a buffered render with a resolved head;\n // - routes with a `streaming: false` rule (opt out per route);\n // - a missing streaming primitive.\n const primitiveAvailable = streamingPrimitiveAvailable();\n const bot = isLikelyBot(serverContext);\n const routeDisabled = streamingDisabledByRoute(serverContext);\n if (bot || routeDisabled || !primitiveAvailable) {\n // Warn only when the primitive is genuinely absent — the bot and\n // route-opt-out paths fall back to buffered by design, not by degradation.\n if (!bot && !routeDisabled && !primitiveAvailable) {\n warnMissingPrimitiveOnce();\n }\n const html = await renderApplication(bootstrap, {\n document,\n url,\n platformProviders: [\n provideServerContext(serverContext),\n platformProviders,\n ],\n });\n navigation.throwIfFailed();\n return new ReadableStream({\n start(controller) {\n controller.enqueue(new TextEncoder().encode(html as string));\n controller.close();\n },\n });\n }\n\n installCaptureDispatcher();\n const platformRef = platformServer([\n { provide: INITIAL_CONFIG, useValue: { document, url } },\n provideServerContext(serverContext),\n platformProviders,\n ]);\n\n let shell: string;\n try {\n shell = createStreamShell(platformRef);\n } catch (error) {\n await asyncDestroyPlatform(platformRef);\n throw error;\n }\n\n return createSsrStream({\n signal: serverContext.signal,\n waitUntil: serverContext.waitUntil,\n errorHtml: serverContext.renderErrorsAsHtml\n ? '<script data-analog-error>window.__analogFail&&window.__analogFail();</script></body></html>'\n : undefined,\n destroy: () => asyncDestroyPlatform(platformRef),\n async render(writer) {\n let blockIndex = 0;\n const seen = new Set<unknown>();\n const onBlockResolved: DeferCaptureHandler = (event) => {\n if (!writer.active || seen.has(event.lContainer)) return;\n seen.add(event.lContainer);\n const id = `s${blockIndex++}`;\n writer.scheduleBlock(\n () =>\n `<template data-analog-defer=\"${id}\">${serializeLContainerHtml(event.lContainer)}</template>` +\n `<script>window.__analogPaint&&window.__analogPaint(${JSON.stringify(id)})</script>`,\n );\n };\n\n await runWithCapture(onBlockResolved, async () => {\n writer.enqueue(\n shell +\n `<script>${DEFER_RECONCILE_RUNTIME}</script>` +\n '<div data-analog-stream></div>',\n );\n const appRef = await bootstrap({ platformRef });\n if (!writer.active) return;\n await appRef.whenStable();\n if (!writer.active) return;\n navigation.throwIfFailed();\n await writer.finishBlocks();\n if (!writer.active) return;\n const authoritative = await renderInternal(platformRef, appRef);\n navigation.throwIfFailed();\n writer.enqueue(\n `<template data-analog-head>${headInner(authoritative)}</template>` +\n `<template data-analog-authoritative>${bodyInner(authoritative)}</template>` +\n '<script>window.__analogReconcileHead&&window.__analogReconcileHead();' +\n 'window.__analogFinalize&&window.__analogFinalize()</script></body></html>',\n );\n });\n },\n });\n };\n}\n","//#region src/utils.url.ts\n/**\n* Joins the given base URL and path, ensuring that there is only one slash between them.\n*/\nfunction joinURL(base, path) {\n\tif (!base || base === \"/\") return path || \"/\";\n\tif (!path || path === \"/\") return base || \"/\";\n\tconst baseHasTrailing = base[base.length - 1] === \"/\";\n\tconst pathHasLeading = path[0] === \"/\";\n\tif (baseHasTrailing && pathHasLeading) return base + path.slice(1);\n\tif (!baseHasTrailing && !pathHasLeading) return `${base}/${path}`;\n\treturn base + path;\n}\n/**\n* Adds the base path to the input path, if it is not already present.\n*/\nfunction withBase(input = \"\", base = \"\") {\n\tif (!base || base === \"/\") return input;\n\tconst _base = withoutTrailingSlash(base);\n\tif (input.startsWith(_base)) return input;\n\treturn joinURL(_base, input);\n}\nfunction withoutTrailingSlash(path) {\n\tif (!path || path === \"/\") return \"/\";\n\treturn path[path.length - 1] === \"/\" ? path.slice(0, -1) : path;\n}\n/**\n* Returns the URL with the given query parameters. If a query parameter is undefined, it is omitted.\n*/\nfunction withQuery(input, query) {\n\tif (!query || Object.keys(query).length === 0) return input;\n\tconst searchIndex = input.indexOf(\"?\");\n\tif (searchIndex === -1) {\n\t\tconst normalizedQuery = Object.entries(query).filter(([, value]) => value !== void 0).flatMap(([key, value]) => {\n\t\t\tif (Array.isArray(value)) return value.map((item) => [key, normalizeQueryValue(item)]);\n\t\t\treturn [[key, normalizeQueryValue(value)]];\n\t\t});\n\t\tconst queryString$1 = new URLSearchParams(normalizedQuery).toString();\n\t\treturn queryString$1 ? `${input}?${queryString$1}` : input;\n\t}\n\tconst searchParams = new URLSearchParams(input.slice(searchIndex + 1));\n\tconst base = input.slice(0, searchIndex);\n\tfor (const [key, value] of Object.entries(query)) if (value === void 0) searchParams.delete(key);\n\telse if (Array.isArray(value)) for (const item of value) searchParams.append(key, normalizeQueryValue(item));\n\telse searchParams.set(key, normalizeQueryValue(value));\n\tconst queryString = searchParams.toString();\n\treturn queryString ? `${base}?${queryString}` : base;\n}\nfunction normalizeQueryValue(value) {\n\tif (value === null) return \"\";\n\tif (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\tif (typeof value === \"object\") return JSON.stringify(value);\n\treturn String(value);\n}\n\n//#endregion\n//#region src/error.ts\nvar FetchError = class extends Error {\n\tconstructor(message, opts) {\n\t\tsuper(message, opts);\n\t\tthis.name = \"FetchError\";\n\t\tif (opts?.cause && !this.cause) this.cause = opts.cause;\n\t}\n};\nfunction createFetchError(ctx) {\n\tconst errorMessage = ctx.error?.message || ctx.error?.toString() || \"\";\n\tconst method = ctx.request?.method || ctx.options?.method || \"GET\";\n\tconst url = ctx.request?.url || String(ctx.request) || \"/\";\n\tconst fetchError = new FetchError(`${`[${method}] ${JSON.stringify(url)}`}: ${ctx.response ? `${ctx.response.status} ${ctx.response.statusText}` : \"<no response>\"}${errorMessage ? ` ${errorMessage}` : \"\"}`, ctx.error ? { cause: ctx.error } : void 0);\n\tfor (const key of [\n\t\t\"request\",\n\t\t\"options\",\n\t\t\"response\"\n\t]) Object.defineProperty(fetchError, key, { get() {\n\t\treturn ctx[key];\n\t} });\n\tfor (const [key, refKey] of [\n\t\t[\"data\", \"_data\"],\n\t\t[\"status\", \"status\"],\n\t\t[\"statusCode\", \"status\"],\n\t\t[\"statusText\", \"statusText\"],\n\t\t[\"statusMessage\", \"statusText\"]\n\t]) Object.defineProperty(fetchError, key, { get() {\n\t\treturn ctx.response && ctx.response[refKey];\n\t} });\n\treturn fetchError;\n}\n\n//#endregion\n//#region src/utils.ts\nconst payloadMethods = new Set(Object.freeze([\n\t\"PATCH\",\n\t\"POST\",\n\t\"PUT\",\n\t\"DELETE\"\n]));\nfunction isPayloadMethod(method = \"GET\") {\n\treturn payloadMethods.has(method.toUpperCase());\n}\nfunction isJSONSerializable(value) {\n\tif (value === void 0) return false;\n\tconst t = typeof value;\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) return true;\n\tif (t !== \"object\") return false;\n\tif (Array.isArray(value)) return true;\n\tif (value.buffer) return false;\n\tif (value instanceof FormData || value instanceof URLSearchParams) return false;\n\treturn value.constructor && value.constructor.name === \"Object\" || typeof value.toJSON === \"function\";\n}\nconst textTypes = new Set([\n\t\"image/svg\",\n\t\"application/xml\",\n\t\"application/xhtml\",\n\t\"application/html\"\n]);\nconst JSON_RE = /^application\\/(?:[\\w!#$%&*.^`~-]*\\+)?json(;.+)?$/i;\nfunction detectResponseType(_contentType = \"\") {\n\tif (!_contentType) return \"json\";\n\tconst contentType = _contentType.split(\";\").shift() || \"\";\n\tif (JSON_RE.test(contentType)) return \"json\";\n\tif (contentType === \"text/event-stream\") return \"stream\";\n\tif (textTypes.has(contentType) || contentType.startsWith(\"text/\")) return \"text\";\n\treturn \"blob\";\n}\nfunction resolveFetchOptions(request, input, defaults, Headers$1) {\n\tconst headers = mergeHeaders(input?.headers ?? request?.headers, defaults?.headers, Headers$1);\n\tlet query;\n\tif (defaults?.query || defaults?.params || input?.params || input?.query) query = {\n\t\t...defaults?.params,\n\t\t...defaults?.query,\n\t\t...input?.params,\n\t\t...input?.query\n\t};\n\treturn {\n\t\t...defaults,\n\t\t...input,\n\t\tquery,\n\t\tparams: query,\n\t\theaders\n\t};\n}\nfunction mergeHeaders(input, defaults, Headers$1) {\n\tif (!defaults) return new Headers$1(input);\n\tconst headers = new Headers$1(defaults);\n\tif (input) for (const [key, value] of Symbol.iterator in input || Array.isArray(input) ? input : new Headers$1(input)) headers.set(key, value);\n\treturn headers;\n}\nasync function callHooks(context, hooks) {\n\tif (hooks) if (Array.isArray(hooks)) for (const hook of hooks) await hook(context);\n\telse await hooks(context);\n}\n\n//#endregion\n//#region src/fetch.ts\nconst retryStatusCodes = new Set([\n\t408,\n\t409,\n\t425,\n\t429,\n\t500,\n\t502,\n\t503,\n\t504\n]);\nconst nullBodyResponses = new Set([\n\t101,\n\t204,\n\t205,\n\t304\n]);\nfunction createFetch(globalOptions = {}) {\n\tconst { fetch: fetch$1 = globalThis.fetch } = globalOptions;\n\tasync function onError(context) {\n\t\tconst isAbort = context.error && context.error.name === \"AbortError\" && !context.options.timeout || false;\n\t\tif (context.options.retry !== false && !isAbort) {\n\t\t\tlet retries;\n\t\t\tif (typeof context.options.retry === \"number\") retries = context.options.retry;\n\t\t\telse retries = isPayloadMethod(context.options.method) ? 0 : 1;\n\t\t\tconst responseCode = context.response && context.response.status || 500;\n\t\t\tif (retries > 0 && (Array.isArray(context.options.retryStatusCodes) ? context.options.retryStatusCodes.includes(responseCode) : retryStatusCodes.has(responseCode))) {\n\t\t\t\tconst retryDelay = typeof context.options.retryDelay === \"function\" ? context.options.retryDelay(context) : context.options.retryDelay || 0;\n\t\t\t\tif (retryDelay > 0) await new Promise((resolve) => setTimeout(resolve, retryDelay));\n\t\t\t\treturn $fetchRaw(context.request, {\n\t\t\t\t\t...context.options,\n\t\t\t\t\tretry: retries - 1\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst error = createFetchError(context);\n\t\tif (Error.captureStackTrace) Error.captureStackTrace(error, $fetchRaw);\n\t\tthrow error;\n\t}\n\tconst $fetchRaw = async function $fetchRaw$1(_request, _options = {}) {\n\t\tconst context = {\n\t\t\trequest: _request,\n\t\t\toptions: resolveFetchOptions(_request, _options, globalOptions.defaults, Headers),\n\t\t\tresponse: void 0,\n\t\t\terror: void 0\n\t\t};\n\t\tif (context.options.method) context.options.method = context.options.method.toUpperCase();\n\t\tif (context.options.onRequest) await callHooks(context, context.options.onRequest);\n\t\tif (typeof context.request === \"string\") {\n\t\t\tif (context.options.baseURL) context.request = withBase(context.request, context.options.baseURL);\n\t\t\tif (context.options.query) {\n\t\t\t\tcontext.request = withQuery(context.request, context.options.query);\n\t\t\t\tdelete context.options.query;\n\t\t\t}\n\t\t\tif (\"query\" in context.options) delete context.options.query;\n\t\t\tif (\"params\" in context.options) delete context.options.params;\n\t\t}\n\t\tif (context.options.body && isPayloadMethod(context.options.method)) {\n\t\t\tif (isJSONSerializable(context.options.body)) {\n\t\t\t\tconst contentType = context.options.headers.get(\"content-type\");\n\t\t\t\tif (typeof context.options.body !== \"string\") context.options.body = contentType === \"application/x-www-form-urlencoded\" ? new URLSearchParams(context.options.body).toString() : JSON.stringify(context.options.body);\n\t\t\t\tcontext.options.headers = new Headers(context.options.headers || {});\n\t\t\t\tif (!contentType) context.options.headers.set(\"content-type\", \"application/json\");\n\t\t\t\tif (!context.options.headers.has(\"accept\")) context.options.headers.set(\"accept\", \"application/json\");\n\t\t\t} else if (\"pipeTo\" in context.options.body && typeof context.options.body.pipeTo === \"function\" || typeof context.options.body.pipe === \"function\") {\n\t\t\t\tif (!(\"duplex\" in context.options)) context.options.duplex = \"half\";\n\t\t\t}\n\t\t}\n\t\tif (context.options.timeout) context.options.signal = context.options.signal ? AbortSignal.any([AbortSignal.timeout(context.options.timeout), context.options.signal]) : AbortSignal.timeout(context.options.timeout);\n\t\ttry {\n\t\t\tcontext.response = await fetch$1(context.request, context.options);\n\t\t} catch (error) {\n\t\t\tcontext.error = error;\n\t\t\tif (context.options.onRequestError) await callHooks(context, context.options.onRequestError);\n\t\t\treturn await onError(context);\n\t\t}\n\t\tif ((context.response.body || context.response._bodyInit) && !nullBodyResponses.has(context.response.status) && context.options.method !== \"HEAD\") {\n\t\t\tconst responseType = (context.options.parseResponse ? \"json\" : context.options.responseType) || detectResponseType(context.response.headers.get(\"content-type\") || \"\");\n\t\t\tswitch (responseType) {\n\t\t\t\tcase \"json\": {\n\t\t\t\t\tconst data = await context.response.text();\n\t\t\t\t\tif (data) {\n\t\t\t\t\t\tconst parseFunction = context.options.parseResponse || JSON.parse;\n\t\t\t\t\t\tcontext.response._data = parseFunction(data);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"stream\":\n\t\t\t\t\tcontext.response._data = context.response.body || context.response._bodyInit;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: context.response._data = await context.response[responseType]();\n\t\t\t}\n\t\t}\n\t\tif (context.options.onResponse) await callHooks(context, context.options.onResponse);\n\t\tif (!context.options.ignoreResponseError && context.response.status >= 400 && context.response.status < 600) {\n\t\t\tif (context.options.onResponseError) await callHooks(context, context.options.onResponseError);\n\t\t\treturn await onError(context);\n\t\t}\n\t\treturn context.response;\n\t};\n\tconst $fetch$1 = async function $fetch$2(request, options) {\n\t\treturn (await $fetchRaw(request, options))._data;\n\t};\n\t$fetch$1.raw = $fetchRaw;\n\t$fetch$1.native = (...args) => fetch$1(...args);\n\t$fetch$1.create = (defaultOptions = {}, customGlobalOptions = {}) => createFetch({\n\t\t...globalOptions,\n\t\t...customGlobalOptions,\n\t\tdefaults: {\n\t\t\t...globalOptions.defaults,\n\t\t\t...customGlobalOptions.defaults,\n\t\t\t...defaultOptions\n\t\t}\n\t});\n\treturn $fetch$1;\n}\n\n//#endregion\n//#region src/index.ts\nconst fetch = globalThis.fetch ? (...args) => globalThis.fetch(...args) : () => Promise.reject(/* @__PURE__ */ new Error(\"[ofetch] global.fetch is not supported!\"));\nconst ofetch = createFetch({ fetch });\nconst $fetch = ofetch;\n\n//#endregion\nexport { $fetch, FetchError, createFetch, createFetchError, fetch, ofetch };","const NODE_TYPES = {\n NORMAL: 0,\n WILDCARD: 1,\n PLACEHOLDER: 2\n};\n\nfunction createRouter(options = {}) {\n const ctx = {\n options,\n rootNode: createRadixNode(),\n staticRoutesMap: {}\n };\n const normalizeTrailingSlash = (p) => options.strictTrailingSlash ? p : p.replace(/\\/$/, \"\") || \"/\";\n if (options.routes) {\n for (const path in options.routes) {\n insert(ctx, normalizeTrailingSlash(path), options.routes[path]);\n }\n }\n return {\n ctx,\n lookup: (path) => lookup(ctx, normalizeTrailingSlash(path)),\n insert: (path, data) => insert(ctx, normalizeTrailingSlash(path), data),\n remove: (path) => remove(ctx, normalizeTrailingSlash(path))\n };\n}\nfunction lookup(ctx, path) {\n const staticPathNode = ctx.staticRoutesMap[path];\n if (staticPathNode) {\n return staticPathNode.data;\n }\n const sections = path.split(\"/\");\n const params = {};\n let paramsFound = false;\n let wildcardNode = null;\n let node = ctx.rootNode;\n let wildCardParam = null;\n for (let i = 0; i < sections.length; i++) {\n const section = sections[i];\n if (node.wildcardChildNode !== null) {\n wildcardNode = node.wildcardChildNode;\n wildCardParam = sections.slice(i).join(\"/\");\n }\n const nextNode = node.children.get(section);\n if (nextNode === void 0) {\n if (node && node.placeholderChildren.length > 1) {\n const remaining = sections.length - i;\n node = node.placeholderChildren.find((c) => c.maxDepth === remaining) || null;\n } else {\n node = node.placeholderChildren[0] || null;\n }\n if (!node) {\n break;\n }\n if (node.paramName) {\n params[node.paramName] = section;\n }\n paramsFound = true;\n } else {\n node = nextNode;\n }\n }\n if ((node === null || node.data === null) && wildcardNode !== null) {\n node = wildcardNode;\n params[node.paramName || \"_\"] = wildCardParam;\n paramsFound = true;\n }\n if (!node) {\n return null;\n }\n if (paramsFound) {\n return {\n ...node.data,\n params: paramsFound ? params : void 0\n };\n }\n return node.data;\n}\nfunction insert(ctx, path, data) {\n let isStaticRoute = true;\n const sections = path.split(\"/\");\n let node = ctx.rootNode;\n let _unnamedPlaceholderCtr = 0;\n const matchedNodes = [node];\n for (const section of sections) {\n let childNode;\n if (childNode = node.children.get(section)) {\n node = childNode;\n } else {\n const type = getNodeType(section);\n childNode = createRadixNode({ type, parent: node });\n node.children.set(section, childNode);\n if (type === NODE_TYPES.PLACEHOLDER) {\n childNode.paramName = section === \"*\" ? `_${_unnamedPlaceholderCtr++}` : section.slice(1);\n node.placeholderChildren.push(childNode);\n isStaticRoute = false;\n } else if (type === NODE_TYPES.WILDCARD) {\n node.wildcardChildNode = childNode;\n childNode.paramName = section.slice(\n 3\n /* \"**:\" */\n ) || \"_\";\n isStaticRoute = false;\n }\n matchedNodes.push(childNode);\n node = childNode;\n }\n }\n for (const [depth, node2] of matchedNodes.entries()) {\n node2.maxDepth = Math.max(matchedNodes.length - depth, node2.maxDepth || 0);\n }\n node.data = data;\n if (isStaticRoute === true) {\n ctx.staticRoutesMap[path] = node;\n }\n return node;\n}\nfunction remove(ctx, path) {\n let success = false;\n const sections = path.split(\"/\");\n let node = ctx.rootNode;\n for (const section of sections) {\n node = node.children.get(section);\n if (!node) {\n return success;\n }\n }\n if (node.data) {\n const lastSection = sections.at(-1) || \"\";\n node.data = null;\n if (Object.keys(node.children).length === 0 && node.parent) {\n node.parent.children.delete(lastSection);\n node.parent.wildcardChildNode = null;\n node.parent.placeholderChildren = [];\n }\n success = true;\n }\n return success;\n}\nfunction createRadixNode(options = {}) {\n return {\n type: options.type || NODE_TYPES.NORMAL,\n maxDepth: 0,\n parent: options.parent || null,\n children: /* @__PURE__ */ new Map(),\n data: options.data || null,\n paramName: options.paramName || null,\n wildcardChildNode: null,\n placeholderChildren: []\n };\n}\nfunction getNodeType(str) {\n if (str.startsWith(\"**\")) {\n return NODE_TYPES.WILDCARD;\n }\n if (str[0] === \":\" || str === \"*\") {\n return NODE_TYPES.PLACEHOLDER;\n }\n return NODE_TYPES.NORMAL;\n}\n\nfunction toRouteMatcher(router) {\n const table = _routerNodeToTable(\"\", router.ctx.rootNode);\n return _createMatcher(table, router.ctx.options.strictTrailingSlash);\n}\nfunction _createMatcher(table, strictTrailingSlash) {\n return {\n ctx: { table },\n matchAll: (path) => _matchRoutes(path, table, strictTrailingSlash)\n };\n}\nfunction _createRouteTable() {\n return {\n static: /* @__PURE__ */ new Map(),\n wildcard: /* @__PURE__ */ new Map(),\n dynamic: /* @__PURE__ */ new Map()\n };\n}\nfunction _exportMatcherFromTable(table) {\n const obj = /* @__PURE__ */ Object.create(null);\n for (const property in table) {\n obj[property] = property === \"dynamic\" ? Object.fromEntries(\n [...table[property].entries()].map(([key, value]) => [\n key,\n _exportMatcherFromTable(value)\n ])\n ) : Object.fromEntries(table[property].entries());\n }\n return obj;\n}\nfunction exportMatcher(matcher) {\n return _exportMatcherFromTable(matcher.ctx.table);\n}\nfunction _createTableFromExport(matcherExport) {\n const table = {};\n for (const property in matcherExport) {\n table[property] = property === \"dynamic\" ? new Map(\n Object.entries(matcherExport[property]).map(([key, value]) => [\n key,\n _createTableFromExport(value)\n ])\n ) : new Map(\n Object.entries(matcherExport[property])\n );\n }\n return table;\n}\nfunction createMatcherFromExport(matcherExport) {\n return _createMatcher(_createTableFromExport(matcherExport));\n}\nfunction _matchRoutes(path, table, strictTrailingSlash) {\n if (strictTrailingSlash !== true && path.endsWith(\"/\")) {\n path = path.slice(0, -1) || \"/\";\n }\n const matches = [];\n for (const [key, value] of _sortRoutesMap(table.wildcard)) {\n if (path === key || path.startsWith(key + \"/\")) {\n matches.push(value);\n }\n }\n for (const [key, value] of _sortRoutesMap(table.dynamic)) {\n if (path.startsWith(key + \"/\")) {\n const subPath = \"/\" + path.slice(key.length).split(\"/\").splice(2).join(\"/\");\n matches.push(..._matchRoutes(subPath, value));\n }\n }\n const staticMatch = table.static.get(path);\n if (staticMatch) {\n matches.push(staticMatch);\n }\n return matches.filter(Boolean);\n}\nfunction _sortRoutesMap(m) {\n return [...m.entries()].sort((a, b) => a[0].length - b[0].length);\n}\nfunction _routerNodeToTable(initialPath, initialNode) {\n const table = _createRouteTable();\n function _addNode(path, node) {\n if (path) {\n if (node.type === NODE_TYPES.NORMAL && !(path.includes(\"*\") || path.includes(\":\"))) {\n if (node.data) {\n table.static.set(path, node.data);\n }\n } else if (node.type === NODE_TYPES.WILDCARD) {\n table.wildcard.set(path.replace(\"/**\", \"\"), node.data);\n } else if (node.type === NODE_TYPES.PLACEHOLDER) {\n const subTable = _routerNodeToTable(\"\", node);\n if (node.data) {\n subTable.static.set(\"/\", node.data);\n }\n table.dynamic.set(path.replace(/\\/\\*|\\/:\\w+/, \"\"), subTable);\n return;\n }\n }\n for (const [childPath, child] of node.children.entries()) {\n _addNode(`${path}/${childPath}`.replace(\"//\", \"/\"), child);\n }\n }\n _addNode(initialPath, initialNode);\n return table;\n}\n\nexport { NODE_TYPES, createMatcherFromExport, createRouter, exportMatcher, toRouteMatcher };\n","import {\n type ApplicationConfig,\n Injector,\n type StaticProvider,\n} from '@angular/core';\nimport { createApplication } from '@angular/platform-browser';\nimport {\n platformServer,\n provideServerRendering,\n} from '@angular/platform-server';\n\n/**\n * Builds the parent injector the server-function dispatch endpoint runs handlers\n * against, over HTTP.\n *\n * A plain `Injector.create({ providers })` resolves explicitly-listed providers\n * but not tree-shakeable `providedIn: 'root'` services — those attach to a\n * *bootstrapped* application's root injector, which `Injector.create` is not.\n * So the in-process SSR leg (whose parent is the app's own bootstrapped\n * injector) resolved `root` services while the HTTP leg did not — the same\n * handler could work while rendering and fail when called from the browser.\n *\n * Bootstrapping a real application on the server platform closes that gap: the\n * returned `appRef.injector` is a root environment injector, so both listed\n * providers and `providedIn: 'root'` services resolve, matching SSR.\n *\n * The generated endpoint passes the app's own server `ApplicationConfig` (the\n * one `main.server.ts` renders with), so a handler sees exactly the DI the app\n * configured — services, tokens, and interceptors alike — with no second\n * provider list to keep in sync. No root component is bootstrapped\n * (`createApplication`, not `bootstrapApplication`), so nothing renders, no\n * change detection runs, and the router registers but never navigates. It is a\n * DI container with the app's providers, built once and reused for the process,\n * with only `REQUEST`/`RESPONSE` rebuilt per call in the child.\n *\n * A bare provider array is also accepted (direct callers and tests without an\n * app config); it is wrapped with `provideServerRendering` so the server tokens\n * resolve the same way.\n */\nexport async function createServerFnAppInjector(\n configOrProviders: ApplicationConfig | StaticProvider[] = [],\n): Promise<Injector> {\n const config: ApplicationConfig = Array.isArray(configOrProviders)\n ? { providers: [provideServerRendering(), ...configOrProviders] }\n : configOrProviders;\n\n const appRef = await createApplication(config, {\n platformRef: platformServer(),\n });\n return appRef.injector;\n}\n","import type { ApplicationConfig } from '@angular/core';\nimport type { ServerContext } from '@analogjs/router/tokens';\n\nexport type PageEndpointModule = {\n load?: (ctx: unknown) => unknown;\n action?: (ctx: unknown) => unknown;\n};\n\nexport type ServerRender = (\n url: string,\n document: string,\n context: ServerContext,\n) => Promise<string | ReadableStream<Uint8Array>>;\n\n/** Everything the request handler needs from the app, as lazy imports. */\nexport type AnalogServerManifest = {\n apiPrefix: string;\n /** The HTML document to render around the app, for a request URL. */\n template: (url: string) => Promise<string>;\n /** The app's SSR entry (`main.server.ts` default export). */\n render: () => Promise<ServerRender>;\n /** The app's server config (`app.config.server.ts`). */\n config: () => Promise<ApplicationConfig>;\n /** Every `*.server.ts`, imported so server functions register. */\n serverFnModules: (() => Promise<unknown>)[];\n /** Page endpoint route → `*.server.ts` module. */\n pageEndpoints: Record<string, () => Promise<PageEndpointModule>>;\n};\n\n/**\n * Filled in at build time by the platform's server build, the same way the\n * router plugin fills in `ANALOG_ROUTE_FILES`. Empty without it.\n */\nexport const ANALOG_SERVER_MANIFEST: Partial<AnalogServerManifest> = {};\n","import type { Injector } from '@angular/core';\nimport type { ServerContext } from '@analogjs/router/tokens';\nimport * as h3 from 'h3';\nimport { IncomingMessage, ServerResponse } from 'node:http';\nimport { Socket } from 'node:net';\nimport { $fetch } from 'ofetch';\nimport { createRouter } from 'radix3';\n\nimport { getBaseUrl } from './provide-server-context';\nimport { createServerFnAppInjector } from './server-fn/app-injector';\nimport { dispatchServerFn } from './server-fn/dispatch';\nimport {\n ANALOG_SERVER_MANIFEST,\n type AnalogServerManifest,\n type PageEndpointModule,\n} from './server-manifest';\n\n/**\n * The Node request and response behind a `Request`, when the host has them.\n * They become Analog's `REQUEST`/`RESPONSE` and the page endpoint `req`/`res`.\n */\nexport type AnalogRequestContext = {\n req: IncomingMessage;\n res: ServerResponse;\n};\n\n/**\n * A `Response` for Analog's requests, or `null` for anything else. Without a\n * context (fetch-native hosts), a Node request/response pair is created from\n * the `Request`, and what the app sets on that response is folded into the\n * returned `Response`.\n */\nexport type AnalogRequestHandler = (\n request: Request,\n context?: AnalogRequestContext,\n) => Promise<Response | null>;\n\nexport type AnalogRequestOptions = {\n /**\n * Serves server-side fetches that Analog doesn't handle, such as the host's\n * own routes. Fetch-native hosts can pass their app's `fetch`.\n */\n fetch?: (request: Request) => Promise<Response>;\n};\n\ntype PageRoute = { importEndpoint: () => Promise<PageEndpointModule> };\n\nconst SERVER_FN_PREFIX = '/_analog/fn/';\n\n/**\n * Handles Analog's requests: server functions and page endpoints, then SSR\n * for GET requests outside the API prefix. Static client files are the\n * host's job; serve them first, without an index fallback, or SSR answers\n * asset URLs.\n */\nexport function createAnalogRequestHandler(\n options: AnalogRequestOptions = {},\n): AnalogRequestHandler {\n const manifest = serverManifest();\n const apiPrefix = `/${manifest.apiPrefix}/`;\n const pageEndpointPrefix = `${apiPrefix}_analog/pages/`;\n const pageRoutes = createRouter<PageRoute>({\n routes: Object.fromEntries(\n Object.entries(manifest.pageEndpoints).map(([route, importEndpoint]) => [\n route,\n { importEndpoint },\n ]),\n ),\n });\n // Server functions register when their module is imported, so dispatch\n // waits for every module along with the app injector.\n const appInjector = Promise.all([\n manifest.config(),\n ...manifest.serverFnModules.map((load) => load()),\n ]).then(([config]) => createServerFnAppInjector(config));\n // Failures surface on server function requests, not as unhandled rejections.\n appInjector.catch(() => undefined);\n\n async function route(\n request: Request,\n url: URL,\n context: AnalogRequestContext,\n ): Promise<Response | null> {\n if (url.pathname.startsWith(SERVER_FN_PREFIX)) {\n const id = url.pathname.slice(SERVER_FN_PREFIX.length);\n return callServerFn(id, request, context, await appInjector);\n }\n if (url.pathname.startsWith(pageEndpointPrefix)) {\n const match = pageRoutes.lookup(url.pathname);\n return match\n ? callPageEndpoint(\n match,\n request,\n url,\n context,\n serverFetch(baseUrl(context)),\n )\n : null;\n }\n if (request.method === 'GET' && !url.pathname.startsWith(apiPrefix)) {\n return renderPage(\n manifest,\n request,\n url,\n context,\n serverFetch(baseUrl(context)),\n );\n }\n return null;\n }\n\n const handle: AnalogRequestHandler = async (request, context) => {\n const url = new URL(request.url);\n if (context) {\n return route(request, url, context);\n }\n const created = nodeContext(request, url);\n const response = await route(request, url, created);\n return response && withResponseHeaders(response, created.res);\n };\n\n /**\n * An ofetch instance for page endpoints' `fetch` and the router's SSR\n * interceptor, which records responses in TransferState. Same-origin\n * requests run in-process, as on Nitro, so they never go to the host named\n * by the client's `Host` header.\n */\n function serverFetch(origin: string): typeof $fetch {\n return $fetch.create(\n { baseURL: origin },\n {\n fetch: async (input, init) => {\n const request = new Request(input, init);\n if (new URL(request.url).origin !== origin) {\n return fetch(request);\n }\n return (\n (await handle(request)) ??\n (await options.fetch?.(request)) ??\n new Response(null, { status: 404 })\n );\n },\n },\n );\n }\n\n return handle;\n}\n\n/** The origin `BASE_URL` holds, so absolute URLs built from it stay in-process. */\nfunction baseUrl(context: AnalogRequestContext): string {\n return getBaseUrl(context.req as ServerContext['req']);\n}\n\nfunction serverManifest(): AnalogServerManifest {\n if (!ANALOG_SERVER_MANIFEST.render) {\n throw new Error(\n '[@analogjs/router] createAnalogRequestHandler() needs the server build from `analog({ server })`, which fills in the server manifest.',\n );\n }\n return ANALOG_SERVER_MANIFEST as AnalogServerManifest;\n}\n\nasync function callServerFn(\n id: string,\n request: Request,\n context: AnalogRequestContext,\n parent: Injector,\n): Promise<Response> {\n let input: unknown;\n if (request.method !== 'GET') {\n const text = await request.text();\n try {\n input = text ? JSON.parse(text) : undefined;\n } catch {\n return Response.json(\n { message: 'Malformed request body' },\n { status: 400 },\n );\n }\n }\n const { status, body, headers } = await dispatchServerFn(\n id,\n input,\n { node: context },\n { parent, method: request.method },\n );\n const responseHeaders = new Headers();\n for (const [key, value] of Object.entries(headers ?? {})) {\n for (const item of [value].flat()) {\n responseHeaders.append(key, item);\n }\n }\n return Response.json(body ?? null, { status, headers: responseHeaders });\n}\n\nasync function callPageEndpoint(\n match: PageRoute & { params?: Record<string, string> },\n request: Request,\n url: URL,\n context: AnalogRequestContext,\n fetch: typeof $fetch,\n): Promise<Response> {\n const event = pageEndpointEvent(request, url, context);\n event.context.params = match.params ?? {};\n\n const endpoint = await match.importEndpoint();\n const handler = request.method === 'GET' ? endpoint.load : endpoint.action;\n const result = await handler?.({\n params: event.context.params,\n req: context.req,\n res: context.res,\n fetch,\n event,\n });\n return result instanceof Response\n ? result\n : Response.json(result ?? {}, { status: context.res.statusCode });\n}\n\n/**\n * Page endpoints receive an h3 event, backed by the `Request` so it is the\n * one body source: h3 v1 reads `event.web.request`, h3 v2 wraps the request.\n */\nfunction pageEndpointEvent(\n request: Request,\n url: URL,\n context: AnalogRequestContext,\n): h3.H3Event {\n if ('createEvent' in h3) {\n const event = h3.createEvent(context.req, context.res);\n event.web = { request, url };\n return event;\n }\n const { H3Event } = h3 as unknown as {\n H3Event: new (request: Request) => h3.H3Event;\n };\n return new H3Event(request);\n}\n\nasync function renderPage(\n manifest: AnalogServerManifest,\n request: Request,\n url: URL,\n context: AnalogRequestContext,\n fetch: typeof $fetch,\n): Promise<Response> {\n // Before any await, so a disconnect during setup isn't missed.\n const signal = renderSignal(request, context.res);\n const path = `${url.pathname}${url.search}`;\n const req = context.req as ServerContext['req'];\n req.originalUrl ??= path;\n const render = await manifest.render();\n const html = await render(path, await manifest.template(path), {\n req,\n res: context.res,\n fetch,\n signal,\n renderErrorsAsHtml: true,\n });\n const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' });\n // As on Nitro, so intermediaries don't cache or buffer partial HTML.\n if (typeof html !== 'string') {\n headers.set('content-encoding', 'identity');\n headers.set('cache-control', 'no-store, no-transform');\n }\n // The status carries anything the app set through RESPONSE before the\n // response started.\n return new Response(html, { status: context.res.statusCode, headers });\n}\n\n/**\n * Aborted when the client disconnects: fetch-native hosts abort the\n * `Request`, Node hosts close `res` before the response finishes.\n */\nfunction renderSignal(request: Request, res: ServerResponse): AbortSignal {\n const closed = new AbortController();\n const abortIfUnfinished = () => {\n if (!res.writableEnded) {\n closed.abort();\n }\n };\n // In dev the host app is created first, so the client may already be gone.\n if (res.closed) {\n abortIfUnfinished();\n } else {\n res.once('close', abortIfUnfinished);\n }\n return AbortSignal.any([request.signal, closed.signal]);\n}\n\n/**\n * A Node request/response pair for a bare `Request`, carrying what Analog\n * reads: method, URL, headers and protocol. The same approach as h3's web\n * adapter; it needs `node:http` (Node, Bun, Deno).\n */\nfunction nodeContext(request: Request, url: URL): AnalogRequestContext {\n const socket = new Socket();\n Object.defineProperty(socket, 'encrypted', {\n value: url.protocol === 'https:',\n });\n const req = new IncomingMessage(socket);\n const path = `${url.pathname}${url.search}`;\n req.method = request.method;\n req.url = path;\n Object.assign(req, { originalUrl: path });\n req.headers = { host: url.host, ...Object.fromEntries(request.headers) };\n return { req, res: new ServerResponse(req) };\n}\n\n/** Headers the app set on the created response, under Analog's own. */\nfunction withResponseHeaders(\n response: Response,\n res: ServerResponse,\n): Response {\n const headers = new Headers();\n for (const [key, value] of Object.entries(res.getHeaders())) {\n for (const item of [value ?? []].flat()) {\n headers.append(key, String(item));\n }\n }\n response.headers.forEach((value, key) => {\n if (key !== 'set-cookie') {\n headers.set(key, value);\n }\n });\n for (const cookie of response.headers.getSetCookie()) {\n headers.append('set-cookie', cookie);\n }\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport type { ReadableStream as NodeReadableStream } from 'node:stream/web';\nimport type { TLSSocket } from 'node:tls';\n\nimport {\n createAnalogRequestHandler,\n type AnalogRequestOptions,\n} from './request-handler';\n\nexport type AnalogNodeHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n) => void;\n\n/**\n * The Node adapter for `createAnalogRequestHandler()`: converts the request,\n * writes Analog's `Response`, and calls `next` when Analog returns `null`.\n */\nexport function createAnalogHandler(\n options: AnalogRequestOptions = {},\n): AnalogNodeHandler {\n const handleAnalogRequest = createAnalogRequestHandler(options);\n return (req, res, next) => {\n Promise.resolve(req)\n .then((req) => handleAnalogRequest(toRequest(req), { req, res }))\n .then((response) => (response ? writeResponse(response, res) : next()))\n .catch((error: Error) => {\n // A render the client walked away from isn't an error for the host.\n if (!(res.closed && error.name === 'AbortError')) {\n next(error);\n }\n });\n };\n}\n\nfunction toRequest(req: IncomingMessage): Request {\n const protocol = (req.socket as TLSSocket).encrypted ? 'https' : 'http';\n const path = (req as { originalUrl?: string }).originalUrl ?? req.url ?? '/';\n const url = new URL(path, `${protocol}://${req.headers.host ?? 'localhost'}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n for (const item of [value ?? []].flat()) {\n headers.append(key, item);\n }\n }\n const hasBody = req.method !== 'GET' && req.method !== 'HEAD';\n return new Request(url, {\n method: req.method,\n headers,\n body: hasBody ? requestBody(req) : undefined,\n duplex: 'half',\n } as RequestInit);\n}\n\n/**\n * Hosts whose body parsers run first keep the original bytes on `rawBody`\n * (NestJS with `rawBody: true`). Otherwise the stream is read lazily, so a\n * request passed on with `next()` keeps its body.\n */\nfunction requestBody(req: IncomingMessage): BodyInit {\n const rawBody = (req as { rawBody?: Buffer }).rawBody;\n if (rawBody) {\n return new Uint8Array(rawBody);\n }\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n // Checked on read, so requests Analog passes on still reach `next()`.\n if (!reader && req.readableEnded) {\n throw new Error(\n '[@analogjs/router] The request body was already read by another parser. Keep the raw body (NestJS: `rawBody: true`) or mount Analog before body parsers.',\n );\n }\n reader ??= (\n Readable.toWeb(req) as ReadableStream<Uint8Array>\n ).getReader();\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n },\n cancel: (reason) => reader?.cancel(reason),\n },\n { highWaterMark: 0 },\n );\n}\n\n/** Keeps headers the app already set on `res`; cookies are appended. */\nasync function writeResponse(\n response: Response,\n res: ServerResponse,\n): Promise<void> {\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n if (key !== 'set-cookie') {\n res.setHeader(key, value);\n }\n });\n const cookies = response.headers.getSetCookie();\n if (cookies.length) {\n res.appendHeader('set-cookie', cookies);\n }\n if (!response.body) {\n res.end();\n return;\n }\n // A client that disconnects mid-response isn't an error for the host.\n await pipeline(\n Readable.fromWeb(response.body as NodeReadableStream<Uint8Array>),\n res,\n ).catch((error: NodeJS.ErrnoException) => {\n if (error.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n throw error;\n }\n });\n}\n","import { createServerFnRef } from '@analogjs/router';\nimport type {\n ServerFn,\n ServerFnConfig,\n ServerFnHandler,\n ServerFnResult,\n StandardSchemaV1,\n} from '@analogjs/router';\n\nimport { serverFnRegistry } from './registry';\n\n/**\n * Define a server function. Authored in a `*.server.ts` module.\n *\n * Three call shapes, chosen for ergonomics — they all normalize to the same\n * `(config, handler)` form and the build transform derives the route id for each:\n *\n * ```ts\n * serverFn(() => inject(Svc).list()); // input-less GET\n * serverFn(schema, (input) => …); // schema ⇒ POST + input\n * serverFn({ method: 'POST' }, () => …); // explicit config\n * ```\n *\n * On the server the function self-registers and its handler runs via\n * `dispatchServerFn`. On the client the build transform replaces the body with a\n * proxy that calls `/_analog/fn/<id>`; the reference still carries\n * `id`/`url`/`method` so `injectServerFn`/`ServerFnClient` can dispatch.\n */\nexport function serverFn<Out>(\n handler: ServerFnHandler<void, Out>,\n): ServerFn<void, ServerFnResult<Out>>;\nexport function serverFn<In, Out>(\n input: StandardSchemaV1<In>,\n handler: ServerFnHandler<In, Out>,\n): ServerFn<In, ServerFnResult<Out>>;\nexport function serverFn<In, Out>(\n config: ServerFnConfig<In>,\n handler: ServerFnHandler<In, Out>,\n): ServerFn<In, ServerFnResult<Out>>;\nexport function serverFn(\n arg1: unknown,\n arg2?: ServerFnHandler<unknown, unknown>,\n): ServerFn<unknown, unknown> {\n const { config, handler } = normalizeArgs(arg1, arg2);\n\n // GET is reserved for input-less reads; an input schema requires POST (the\n // input travels in the body, not the query). Build transforms reject this too.\n if (config.method === 'GET' && config.input) {\n throw new Error(\n '[analog] a serverFn with `input` must use POST; GET is reserved for input-less reads.',\n );\n }\n\n // `createServerFnRef` throws if the build-derived id is missing, so `ref.id`\n // is the authoritative route key here.\n const ref = createServerFnRef<unknown, unknown>(config);\n\n serverFnRegistry.set(ref.id, {\n id: ref.id,\n method: ref.method,\n config,\n handler,\n });\n\n return ref;\n}\n\nfunction normalizeArgs(\n arg1: unknown,\n arg2?: ServerFnHandler<unknown, unknown>,\n): {\n config: ServerFnConfig<unknown>;\n handler: ServerFnHandler<unknown, unknown>;\n} {\n // serverFn(handler) — input-less GET.\n if (typeof arg1 === 'function') {\n return {\n config: {},\n handler: arg1 as ServerFnHandler<unknown, unknown>,\n };\n }\n // serverFn(schema, handler) — a Standard Schema ⇒ POST + input.\n if (isStandardSchema(arg1)) {\n return {\n config: { input: arg1 as StandardSchemaV1<unknown> },\n handler: arg2 as ServerFnHandler<unknown, unknown>,\n };\n }\n // serverFn(config, handler) — explicit config object.\n return {\n config: (arg1 as ServerFnConfig<unknown>) ?? {},\n handler: arg2 as ServerFnHandler<unknown, unknown>,\n };\n}\n\nfunction isStandardSchema(value: unknown): value is StandardSchemaV1<unknown> {\n return typeof value === 'object' && value !== null && '~standard' in value;\n}\n","import type { Injector } from '@angular/core';\nimport {\n eventHandler,\n getRouterParam,\n readBody,\n type EventHandler,\n type H3Event,\n} from 'h3';\n\nimport { dispatchServerFn } from './dispatch';\nimport { assertNodeContext } from './node-context';\n\n/**\n * The h3 request/response layer for the server-function dispatch route.\n *\n * `createServerFnAppInjector` bootstraps the parent injector once; this wraps\n * that in the `/_analog/fn/:id` handler the Nitro build registers. Kept as a\n * runtime function (rather than inlined into the generated module) so the\n * transport behaviour — body decoding, the malformed-body contract, and header\n * propagation — is unit-tested directly instead of by matching generated source.\n *\n * `appInjector` may be a promise: the generated module bootstraps the app at\n * import time and passes the pending injector, which is awaited on first request\n * and resolved instantly thereafter.\n */\nexport function createServerFnEventHandler(\n appInjector: Injector | Promise<Injector>,\n): EventHandler {\n return eventHandler((event) => handleServerFnRequest(event, appInjector));\n}\n\n/**\n * Decode a server-function request, dispatch it, and write the result to the\n * h3 response. Same-origin, method, content-type, validation, and interceptors\n * are enforced inside `dispatchServerFn`; this owns only the h3 I/O around it.\n */\nexport async function handleServerFnRequest(\n event: H3Event,\n appInjector: Injector | Promise<Injector>,\n): Promise<unknown> {\n const node = assertNodeContext(event);\n const id = getRouterParam(event, 'id') ?? '';\n\n // h3 parses the body before dispatch gets a say, and its parse error is an\n // HTML/500-shaped response rather than the JSON contract callers expect.\n let input: unknown;\n if (event.method !== 'GET') {\n try {\n input = await readBody(event);\n } catch {\n node.res.statusCode = 400;\n return { message: 'Malformed request body' };\n }\n }\n\n const { status, body, headers } = await dispatchServerFn(id, input, event, {\n parent: await appInjector,\n method: event.method,\n });\n\n node.res.statusCode = status;\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n node.res.setHeader(key, value);\n }\n }\n return body;\n}\n"],"x_google_ignoreList":[16,17],"mappings":";;;;;;;;;;;;;;;;;;;;;AAOA,IAAa,mCAA6C,IAAI,IAAG;;;;;;;;;ACQjE,SAAgB,kBACd,OAA4B;CAE5B,MAAM,OAAO,MAAM;CAEnB,IAAI,CAAC,MAAM,KACT,MAAM,IAAI,MACR,4DAA4D;CAIhE,OAAO;AACT;;;ACHA,IAAa,yBACX,IAAI,eAAwC,wBAAwB;;AAOtE,SAAgB,yBACd,cAAqC;CAErC,OAAO,EACL,WAAW,aAAa,KAAK,QAAQ;EACnC,SAAS;EACT,UAAU;EACV,OAAO;CACR,EAAC,EACH;AACH;;AAGA,SAAgB,iBAAiB,GAAG,UAA4B;CAC9D,OAAO,SAAS,SAAS,MAAM,EAAE,SAAS;AAC5C;AAEA,SAAS,QACP,OACA,SAAwB;CAExB,OAAO;EACL;EACA;EACA,KAAK,OAAK;GACR,OAAO,QAAQ,OAAO;IAAE,GAAG;IAAS,GAAG;GAAK,CAAqB;EACnE;CACD;AACH;;;;;;;;;;AAWA,eAAsB,gBACpB,cACA,OACA,SAIA,YAAmC,OAAO,GAAE,GAAE;CAE9C,IAAI,IAAI;CACR,MAAM,WAAyB,OAAO,QAAO;EAC3C,KAAK;EACL,IAAI,IAAI,aAAa,QACnB,OAAO,eAAe,aAAa,EAAE,CAAC,KAAK,QAAQ,CAAC;EAEtD,OAAO,eAAe,QAAQ,IAAI,OAAO,IAAI,OAAO,CAAC;CACvD;CACA,OAAO,SAAS,QAAQ,OAAO,CAAA,CAAqB,CAAC;AACvD;;;;;;;;;;;;;;;;;;;;;;AC9DA,IAAa,4BACX,IAAI,eAAyB,2BAA2B;;;;;;;AAQ1D,SAAgB,mBAAmB,SAAiB;CAClD,OAAO,EACL,WAAW,QAAQ,KAAK,YAAY;EAClC,SAAS;EACT,UAAU;EACV,OAAO;CACR,EAAC,EACH;AACH;AA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,KAAK,KAAK;CAGjC,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
- import { API_PREFIX, injectAPIPrefix, injectBaseURL, injectInternalServerFetch, injectRequest } from "./analogjs-router-tokens.mjs";
2
1
  import { a as ANALOG_META_KEY, i as injectRouteEndpointURL, n as ANALOG_ROUTE_FILES, o as updateMetaTagsOnRouteChange, r as createRoutes$1, s as updateJsonLdOnRouteChange, t as ANALOG_EXTRA_ROUTE_FILE_SOURCES } from "./route-files.mjs";
2
+ import { API_PREFIX, injectAPIPrefix, injectBaseURL, injectInternalServerFetch, injectRequest } from "./analogjs-router-tokens.mjs";
3
3
  import { n as createRoutes, t as injectDebugRoutes } from "./routes.mjs";
4
4
  import * as i1 from "@angular/router";
5
5
  import { ActivatedRoute, ROUTES, Router, RouterLink, provideRouter } from "@angular/router";