@analogjs/router 2.6.4-beta.4 → 2.7.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/fesm2022/analogjs-router-server.mjs +460 -11
- package/fesm2022/analogjs-router-server.mjs.map +1 -1
- package/fesm2022/analogjs-router.mjs +130 -2
- package/fesm2022/analogjs-router.mjs.map +1 -1
- package/package.json +2 -2
- package/types/analogjs-router-server.d.ts +216 -2
- package/types/analogjs-router.d.ts +147 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analogjs-router-server.mjs","sources":["../../../../packages/router/server/src/provide-server-context.ts","../../../../packages/router/server/src/tokens.ts","../../../../packages/router/server/src/server-component-render.ts","../../../../packages/router/server/src/render.ts","../../../../packages/router/server/src/analogjs-router-server.ts"],"sourcesContent":["import { StaticProvider, ɵresetCompiledComponents } from '@angular/core';\nimport { ɵSERVER_CONTEXT as SERVER_CONTEXT } from '@angular/platform-server';\n\nimport {\n BASE_URL,\n LOCALE,\n REQUEST,\n RESPONSE,\n ServerRequest,\n ServerResponse,\n} from '@analogjs/router/tokens';\n\nexport function provideServerContext({\n req,\n res,\n}: {\n req: ServerRequest;\n res: ServerResponse;\n}): StaticProvider[] {\n const baseUrl = getBaseUrl(req);\n const locale = detectLocale(req);\n\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 ...(locale ? [{ provide: LOCALE, useValue: locale }] : []),\n ];\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(req.headers['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 // e.g. 'en', 'en-US', 'zh-Hans', 'zh-Hans-CN'\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\nexport function getBaseUrl(req: ServerRequest) {\n const protocol = getRequestProtocol(req);\n const { originalUrl, headers } = req;\n const parsedUrl = new URL(\n '',\n `${protocol}://${headers.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) {\n if (\n opts.xForwardedProto !== false &&\n req.headers['x-forwarded-proto'] === 'https'\n ) {\n return 'https';\n }\n\n return (req.connection as any)?.encrypted ? 'https' : 'http';\n}\n","import {\n assertInInjectionContext,\n inject,\n InjectionToken,\n makeStateKey,\n Provider,\n TransferState,\n} from '@angular/core';\n\nexport const STATIC_PROPS = new InjectionToken<Record<string, any>>(\n 'Static Props',\n);\n\nexport function provideStaticProps<T = Record<string, any>>(\n props: T,\n): Provider {\n return {\n provide: STATIC_PROPS,\n useFactory() {\n return props;\n },\n };\n}\n\nexport function injectStaticProps() {\n assertInInjectionContext(injectStaticProps);\n\n return inject(STATIC_PROPS);\n}\n\nexport function injectStaticOutputs<T>() {\n const transferState = inject(TransferState);\n const outputsKey = makeStateKey<T>('_analog_output');\n\n return {\n set(data: T) {\n transferState.set(outputsKey, data);\n },\n };\n}\n","import { ApplicationConfig, Type } from '@angular/core';\nimport {\n bootstrapApplication,\n type BootstrapContext,\n} from '@angular/platform-browser';\nimport {\n reflectComponentType,\n ɵConsole as Console,\n APP_ID,\n} from '@angular/core';\nimport {\n provideServerRendering,\n renderApplication,\n ɵSERVER_CONTEXT as SERVER_CONTEXT,\n} from '@angular/platform-server';\nimport { ServerContext } from '@analogjs/router/tokens';\nimport { createEvent, readBody, getHeader } from 'h3';\n\nimport { provideStaticProps } from './tokens';\n\ntype ComponentLoader = () => Promise<Type<unknown>>;\n\nexport function serverComponentRequest(serverContext: ServerContext) {\n const serverComponentId = getHeader(\n createEvent(serverContext.req, serverContext.res),\n 'X-Analog-Component',\n );\n\n if (\n !serverComponentId &&\n serverContext.req.url &&\n serverContext.req.url.startsWith('/_analog/components')\n ) {\n const componentId = serverContext.req.url.split('/')?.[3];\n\n return componentId;\n }\n\n return serverComponentId;\n}\n\nconst components = import.meta.glob([\n '/src/server/components/**/*.{ts,analog,ag}',\n]);\n\nexport async function renderServerComponent(\n url: string,\n serverContext: ServerContext,\n config?: ApplicationConfig,\n) {\n const componentReqId = serverComponentRequest(serverContext) as string;\n const { componentLoader, componentId } = getComponentLoader(componentReqId);\n\n if (!componentLoader) {\n return new Response(`Server Component Not Found ${componentId}`, {\n status: 404,\n });\n }\n\n const component = ((await componentLoader()) as any)[\n 'default'\n ] as Type<unknown>;\n\n if (!component) {\n return new Response(`No default export for ${componentId}`, {\n status: 422,\n });\n }\n\n const mirror = reflectComponentType(component);\n const selector = mirror?.selector.split(',')?.[0] || 'server-component';\n const event = createEvent(serverContext.req, serverContext.res);\n const body = (await readBody(event)) || {};\n const appId = `analog-server-${selector.toLowerCase()}-${new Date().getTime()}`;\n\n const bootstrap = (context?: BootstrapContext) =>\n bootstrapApplication(\n component,\n {\n providers: [\n provideServerRendering(),\n provideStaticProps(body),\n { provide: SERVER_CONTEXT, useValue: 'analog-server-component' },\n {\n provide: APP_ID,\n useFactory() {\n return appId;\n },\n },\n ...(config?.providers || []),\n ],\n },\n context,\n );\n\n const html = await renderApplication(bootstrap, {\n url,\n document: `<${selector}></${selector}>`,\n platformProviders: [\n {\n provide: Console,\n useFactory() {\n return {\n warn: () => {},\n log: () => {},\n };\n },\n },\n ],\n });\n\n const outputs = retrieveTransferredState(html, appId);\n const responseData: { html: string; outputs: Record<string, any> } = {\n html,\n outputs,\n };\n\n return new Response(JSON.stringify(responseData), {\n headers: {\n 'X-Analog-Component': 'true',\n },\n });\n}\n\nfunction getComponentLoader(componentReqId: string): {\n componentLoader: ComponentLoader | undefined;\n componentId: string;\n} {\n let _componentId = `/src/server/components/${componentReqId.toLowerCase()}`;\n let componentLoader: ComponentLoader | undefined = undefined;\n let componentId = _componentId;\n\n if (components[`${_componentId}.ts`]) {\n componentId = `${_componentId}.ts`;\n componentLoader = components[componentId] as ComponentLoader;\n }\n\n return { componentLoader, componentId };\n}\n\nfunction retrieveTransferredState(\n html: string,\n appId: string,\n): Record<string, unknown | undefined> {\n const regex = new RegExp(\n `<script id=\"${appId}-state\" type=\"application/json\">(.*?)<\\/script>`,\n );\n const match = html.match(regex);\n\n if (match) {\n const scriptContent = match[1];\n\n if (scriptContent) {\n try {\n const parsedContent: {\n _analog_output: Record<string, unknown | undefined>;\n } = JSON.parse(scriptContent);\n return parsedContent._analog_output || {};\n } catch (e) {\n console.warn('Exception while parsing static outputs for ' + appId, e);\n }\n }\n\n return {};\n } else {\n return {};\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 '@analogjs/router/tokens';\n\nimport { provideServerContext } from './provide-server-context';\nimport {\n serverComponentRequest,\n renderServerComponent,\n} from './server-component-render';\n\nif (import.meta.env.PROD) {\n enableProdMode();\n}\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 */\nfunction resetComponentDefTViews(): void {\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\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 | Reponse>\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 ) {\n if (serverComponentRequest(serverContext)) {\n return await renderServerComponent(url, serverContext);\n }\n\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 * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":["ɵresetCompiledComponents","SERVER_CONTEXT","Console"],"mappings":";;;;;;SAYgB,oBAAoB,CAAC,EACnC,GAAG,EACH,GAAG,GAIJ,EAAA;AACC,IAAA,MAAM,OA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AAkB,CAAC,iBAAyC;AAC1E,IAAA,IAAI,CAAC,IAAI;QAAE;AACX,IAAA,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE;AACtB,QAAA,GAAG,CAAC,KAAK,GAAG,IAAI;IAClB;AACF;AAEA;;;;;;;;AAQG;AACG,SAAU,MAAM,CACpB,aAA4B,EAC5B,MAAyB,EACzB,oBAAgC,EAAE,EAAA;IAElC,SAAS,SAAS,CAAC,OAA0B,EAAA;QAC3C,OAAO,oBAAoB,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC;IAC7D;IAEA,OAAO,eAAe,MAAM,CAC1B,GAAW,EACX,QAAgB,EAChB,aAA4B,EAAA;AAE5B,QAAA,IAAI,sBAAsB,CAAC,aAAa,CAAC,EAAE;AACzC,YAAA,OAAO,MAAM,qBAAqB,CAAC,GAAG,EAAE,aAAa,CAAC;QACxD;AAEA,QAAA,uBAAuB,EAAE;AAEzB,QAAA,MAAM,IAAI,GAAG,MAAM,iBAAiB,CAAC,SAAS,EAAE;YAC9C,QAAQ;YACR,GAAG;AACH,YAAA,iBAAiB,EAAE;gBACjB,oBAAoB,CAAC,aAAa,CAAC;gBACnC,iBAAiB;AAClB,aAAA;AACF,SAAA,CAAC;AAEF,QAAA,OAAO,IAAI;AACb,IAAA,CAAC;AACH;;ACpFA;;AAEG;;;;"}
|
|
1
|
+
{"version":3,"file":"analogjs-router-server.mjs","sources":["../../../../packages/router/server/src/server-fn/registry.ts","../../../../packages/router/server/src/server-fn/interceptors.ts","../../../../packages/router/server/src/server-fn/same-origin.ts","../../../../packages/router/server/src/server-fn/dispatch.ts","../../../../packages/router/server/src/server-fn/ssr-dispatcher.ts","../../../../packages/router/server/src/provide-server-context.ts","../../../../packages/router/server/src/tokens.ts","../../../../packages/router/server/src/server-component-render.ts","../../../../packages/router/server/src/render.ts","../../../../packages/router/server/src/server-fn/server-fn.ts","../../../../packages/router/server/src/server-fn/app-injector.ts","../../../../packages/router/server/src/server-fn/event-handler.ts","../../../../packages/router/server/src/analogjs-router-server.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 = new Map<string, ServerFnDef>();\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 = new InjectionToken<\n ServerFnInterceptorFn[]\n>('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 = new InjectionToken<string[]>(\n 'SERVER_FN_ALLOWED_ORIGINS',\n);\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 { 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 headers = (event.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 = event.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: event.node.req },\n { provide: RESPONSE, useValue: event.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 LOCALE,\n REQUEST,\n RESPONSE,\n ServerRequest,\n ServerResponse,\n} from '@analogjs/router/tokens';\nimport { SERVER_FN_DISPATCHER } from '@analogjs/router';\n\nimport { createServerFnDispatcher } from './server-fn/ssr-dispatcher';\n\nexport function provideServerContext({\n req,\n res,\n}: {\n req: ServerRequest;\n res: ServerResponse;\n}): StaticProvider[] {\n const baseUrl = getBaseUrl(req);\n const locale = 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 // 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\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(req.headers['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 // e.g. 'en', 'en-US', 'zh-Hans', 'zh-Hans-CN'\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\nexport function getBaseUrl(req: ServerRequest) {\n const protocol = getRequestProtocol(req);\n const { headers } = req;\n // Node's `IncomingMessage` has no `originalUrl`, and a server function\n // endpoint is reached with a plain request, so fall back before dereferencing.\n const originalUrl = req.originalUrl || req.url || '/';\n const parsedUrl = new URL(\n '',\n `${protocol}://${headers.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) {\n if (\n opts.xForwardedProto !== false &&\n req.headers['x-forwarded-proto'] === 'https'\n ) {\n return 'https';\n }\n\n return (req.connection as any)?.encrypted ? 'https' : 'http';\n}\n","import {\n assertInInjectionContext,\n inject,\n InjectionToken,\n makeStateKey,\n Provider,\n TransferState,\n} from '@angular/core';\n\nexport const STATIC_PROPS = new InjectionToken<Record<string, any>>(\n 'Static Props',\n);\n\nexport function provideStaticProps<T = Record<string, any>>(\n props: T,\n): Provider {\n return {\n provide: STATIC_PROPS,\n useFactory() {\n return props;\n },\n };\n}\n\nexport function injectStaticProps() {\n assertInInjectionContext(injectStaticProps);\n\n return inject(STATIC_PROPS);\n}\n\nexport function injectStaticOutputs<T>() {\n const transferState = inject(TransferState);\n const outputsKey = makeStateKey<T>('_analog_output');\n\n return {\n set(data: T) {\n transferState.set(outputsKey, data);\n },\n };\n}\n","import { ApplicationConfig, Type } from '@angular/core';\nimport {\n bootstrapApplication,\n type BootstrapContext,\n} from '@angular/platform-browser';\nimport {\n reflectComponentType,\n ɵConsole as Console,\n APP_ID,\n} from '@angular/core';\nimport {\n provideServerRendering,\n renderApplication,\n ɵSERVER_CONTEXT as SERVER_CONTEXT,\n} from '@angular/platform-server';\nimport { ServerContext } from '@analogjs/router/tokens';\nimport { createEvent, readBody, getHeader } from 'h3';\n\nimport { provideStaticProps } from './tokens';\n\ntype ComponentLoader = () => Promise<Type<unknown>>;\n\nexport function serverComponentRequest(serverContext: ServerContext) {\n const serverComponentId = getHeader(\n createEvent(serverContext.req, serverContext.res),\n 'X-Analog-Component',\n );\n\n if (\n !serverComponentId &&\n serverContext.req.url &&\n serverContext.req.url.startsWith('/_analog/components')\n ) {\n const componentId = serverContext.req.url.split('/')?.[3];\n\n return componentId;\n }\n\n return serverComponentId;\n}\n\n// Deferred so the module can be imported outside a Vite context (e.g. by the\n// Nitro server-function dispatch path, or tooling) without eagerly evaluating\n// the Vite-only `import.meta.glob` macro at load time. Vite still statically\n// rewrites the macro; it is just invoked lazily on first server-component render.\nlet _components: Record<string, () => Promise<unknown>> | undefined;\nfunction serverComponents(): Record<string, () => Promise<unknown>> {\n return (_components ??= import.meta.glob([\n '/src/server/components/**/*.{ts,analog,ag}',\n ]));\n}\n\nexport async function renderServerComponent(\n url: string,\n serverContext: ServerContext,\n config?: ApplicationConfig,\n) {\n const componentReqId = serverComponentRequest(serverContext) as string;\n const { componentLoader, componentId } = getComponentLoader(componentReqId);\n\n if (!componentLoader) {\n return new Response(`Server Component Not Found ${componentId}`, {\n status: 404,\n });\n }\n\n const component = ((await componentLoader()) as any)[\n 'default'\n ] as Type<unknown>;\n\n if (!component) {\n return new Response(`No default export for ${componentId}`, {\n status: 422,\n });\n }\n\n const mirror = reflectComponentType(component);\n const selector = mirror?.selector.split(',')?.[0] || 'server-component';\n const event = createEvent(serverContext.req, serverContext.res);\n const body = (await readBody(event)) || {};\n const appId = `analog-server-${selector.toLowerCase()}-${new Date().getTime()}`;\n\n const bootstrap = (context?: BootstrapContext) =>\n bootstrapApplication(\n component,\n {\n providers: [\n provideServerRendering(),\n provideStaticProps(body),\n { provide: SERVER_CONTEXT, useValue: 'analog-server-component' },\n {\n provide: APP_ID,\n useFactory() {\n return appId;\n },\n },\n ...(config?.providers || []),\n ],\n },\n context,\n );\n\n const html = await renderApplication(bootstrap, {\n url,\n document: `<${selector}></${selector}>`,\n platformProviders: [\n {\n provide: Console,\n useFactory() {\n return {\n warn: () => {},\n log: () => {},\n };\n },\n },\n ],\n });\n\n const outputs = retrieveTransferredState(html, appId);\n const responseData: { html: string; outputs: Record<string, any> } = {\n html,\n outputs,\n };\n\n return new Response(JSON.stringify(responseData), {\n headers: {\n 'X-Analog-Component': 'true',\n },\n });\n}\n\nfunction getComponentLoader(componentReqId: string): {\n componentLoader: ComponentLoader | undefined;\n componentId: string;\n} {\n let _componentId = `/src/server/components/${componentReqId.toLowerCase()}`;\n let componentLoader: ComponentLoader | undefined = undefined;\n let componentId = _componentId;\n\n const components = serverComponents();\n if (components[`${_componentId}.ts`]) {\n componentId = `${_componentId}.ts`;\n componentLoader = components[componentId] as ComponentLoader;\n }\n\n return { componentLoader, componentId };\n}\n\nfunction retrieveTransferredState(\n html: string,\n appId: string,\n): Record<string, unknown | undefined> {\n const regex = new RegExp(\n `<script id=\"${appId}-state\" type=\"application/json\">(.*?)<\\/script>`,\n );\n const match = html.match(regex);\n\n if (match) {\n const scriptContent = match[1];\n\n if (scriptContent) {\n try {\n const parsedContent: {\n _analog_output: Record<string, unknown | undefined>;\n } = JSON.parse(scriptContent);\n return parsedContent._analog_output || {};\n } catch (e) {\n console.warn('Exception while parsing static outputs for ' + appId, e);\n }\n }\n\n return {};\n } else {\n return {};\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 '@analogjs/router/tokens';\n\nimport { provideServerContext } from './provide-server-context';\nimport {\n serverComponentRequest,\n renderServerComponent,\n} from './server-component-render';\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 * 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 */\nfunction resetComponentDefTViews(): void {\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\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 | Reponse>\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 ) {\n if (serverComponentRequest(serverContext)) {\n return await renderServerComponent(url, serverContext);\n }\n\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","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 { eventHandler, getRouterParam, readBody, type H3Event } from 'h3';\n\nimport { dispatchServerFn } from './dispatch';\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) {\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 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 event.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 event.node.res.statusCode = status;\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n event.node.res.setHeader(key, value);\n }\n }\n return body;\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":["ɵresetCompiledComponents","SERVER_CONTEXT","Console"],"mappings":";;;;;;;;AAEA;;;;AAIG;AACI,MAAM,gBAAgB,GAAG,IAAI,GAAG;;MCiB1B,sBAAsB,GAAG,IAAI,cAAc,CAEtD,wBAAwB;AAM1B;AACM,SAAU,wBAAwB,CACtC,YAAqC,EAAA;IAErC,OAAO;QACL,SAAS,EAAE,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM;AACnC,YAAA,OAAO,EAAE,sBAAsB;AAC/B,YAAA,QAAQ,EAAE,EAAE;AACZ,YAAA,KAAK,EAAE,IAAI;AACZ,SAAA,CAAC,CAAC;KACJ;AACH;AAEA;AACM,SAAU,gBAAgB,CAAC,GAAG,QAA4B,EAAA;AAC9D,IAAA,OAAO,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC;AAC7C;AAEA,SAAS,OAAO,CACd,KAAc,EACd,OAAwB,EAAA;IAExB,OAAO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A,OAAO,YAAY,CAAC,CAAC,KAAK,KAAK,qBAAqB,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;AAC3E;AAEA;;;;AAIG;AACI,eAAe,qBAAqB,CACzC,KAAc,EACd,WAAyC,EAAA;IAEzC,MAAM,EAAE,GAAG,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE;;;AAI5C,IAAA,IAAI,KAAc;AAClB,IAAA,IAAI,KAAK,CAAC,MAAM,KAAK,KAAK,EAAE;AAC1B,QAAA,IAAI;AACF,YAAA,KAAK,GAAG,MAAM,QAAQ,CAAC,KAAK,CAAC;QAC/B;AAAE,QAAA,MAAM;YACN,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,GAAG,GAAG;AAC/B,YAAA,OAAO,EAAE,OAAO,EAAE,wBAAwB,EAAE;QAC9C;IACF;AAEA,IAAA,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,MAAM,gBAAgB,CAAC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE;QACzE,MAAM,EAAE,MAAM,WAAW;QACzB,MAAM,EAAE,KAAK,CAAC,MAAM;AACrB,KAAA,CAAC;IAEF,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,GAAG,MAAM;IAClC,IAAI,OAAO,EAAE;AACX,QAAA,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;YAClD,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC;QACtC;IACF;AACA,IAAA,OAAO,IAAI;AACb;;AC3DA;;AAEG;;;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Router, NavigationEnd, UrlSegment, ActivatedRoute, provideRouter, ROUTES } from '@angular/router';
|
|
2
2
|
import * as i0 from '@angular/core';
|
|
3
|
-
import { inject, PLATFORM_ID, makeEnvironmentProviders, ENVIRONMENT_INITIALIZER, Injector, makeStateKey, TransferState, input, output, Directive, InjectionToken, signal, effect, ChangeDetectionStrategy, Component } from '@angular/core';
|
|
3
|
+
import { inject, PLATFORM_ID, makeEnvironmentProviders, ENVIRONMENT_INITIALIZER, Injector, makeStateKey, TransferState, input, output, Directive, InjectionToken, signal, effect, ChangeDetectionStrategy, Component, Injectable, assertInInjectionContext, resource } from '@angular/core';
|
|
4
4
|
import { HttpClient, HttpHeaders, ɵHTTP_ROOT_INTERCEPTOR_FNS as _HTTP_ROOT_INTERCEPTOR_FNS, HttpResponse, HttpRequest } from '@angular/common/http';
|
|
5
5
|
import { firstValueFrom, map, from, of, throwError, catchError } from 'rxjs';
|
|
6
6
|
import { Meta, DomSanitizer } from '@angular/platform-browser';
|
|
@@ -842,9 +842,137 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImpor
|
|
|
842
842
|
}]
|
|
843
843
|
}], ctorParameters: () => [], propDecorators: { component: [{ type: i0.Input, args: [{ isSignal: true, alias: "component", required: true }] }], props: [{ type: i0.Input, args: [{ isSignal: true, alias: "props", required: false }] }], outputs: [{ type: i0.Output, args: ["outputs"] }] } });
|
|
844
844
|
|
|
845
|
+
const SERVER_FN_DISPATCHER = new InjectionToken('@analogjs/router Server Function Dispatcher');
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* Client transport for server functions. In the browser it goes through Angular
|
|
849
|
+
* `HttpClient`, so client `HttpInterceptorFn`s apply. During SSR the dispatcher
|
|
850
|
+
* token is provided, and the call short-circuits the HTTP round-trip: the
|
|
851
|
+
* handler runs in-process in the current request injector. Lives in the client
|
|
852
|
+
* entry (client-safe).
|
|
853
|
+
*/
|
|
854
|
+
class ServerFnClient {
|
|
855
|
+
constructor() {
|
|
856
|
+
this.http = inject(HttpClient);
|
|
857
|
+
this.transferState = inject(TransferState);
|
|
858
|
+
this.injector = inject(Injector);
|
|
859
|
+
this.dispatcher = inject(SERVER_FN_DISPATCHER, {
|
|
860
|
+
optional: true,
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
/** True while rendering on the server (the in-process dispatcher is provided). */
|
|
864
|
+
get isServer() {
|
|
865
|
+
return !!this.dispatcher;
|
|
866
|
+
}
|
|
867
|
+
async call(fn, input) {
|
|
868
|
+
if (this.dispatcher) {
|
|
869
|
+
return this.dispatcher(fn, input, this.injector);
|
|
870
|
+
}
|
|
871
|
+
const request$ = fn.method === 'GET'
|
|
872
|
+
? this.http.get(fn.url)
|
|
873
|
+
: this.http.post(fn.url, input ?? {});
|
|
874
|
+
return firstValueFrom(request$);
|
|
875
|
+
}
|
|
876
|
+
/** Key a read's value for TransferState hydration (fn id + input). */
|
|
877
|
+
stateKey(fn, input) {
|
|
878
|
+
return makeStateKey(`__analog_fn_${fn.id}_${stableInput(input)}`);
|
|
879
|
+
}
|
|
880
|
+
readSeed(fn, input) {
|
|
881
|
+
const key = this.stateKey(fn, input);
|
|
882
|
+
if (this.transferState.hasKey(key)) {
|
|
883
|
+
const value = this.transferState.get(key, undefined);
|
|
884
|
+
this.transferState.remove(key); // single-use
|
|
885
|
+
return value;
|
|
886
|
+
}
|
|
887
|
+
return undefined;
|
|
888
|
+
}
|
|
889
|
+
writeSeed(fn, input, value) {
|
|
890
|
+
this.transferState.set(this.stateKey(fn, input), value);
|
|
891
|
+
}
|
|
892
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: ServerFnClient, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
893
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: ServerFnClient, providedIn: 'root' }); }
|
|
894
|
+
}
|
|
895
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: ServerFnClient, decorators: [{
|
|
896
|
+
type: Injectable,
|
|
897
|
+
args: [{ providedIn: 'root' }]
|
|
898
|
+
}] });
|
|
899
|
+
/** No-op provider hook; ServerFnClient is `providedIn: 'root'`. */
|
|
900
|
+
function provideServerFnClient() {
|
|
901
|
+
return [];
|
|
902
|
+
}
|
|
903
|
+
// Stable sentinel for the input-less read: `resource()` treats an `undefined`
|
|
904
|
+
// params value as "idle, don't load", so an input-less read must yield a
|
|
905
|
+
// defined-but-ignored params. It is never sent — the call uses `undefined`.
|
|
906
|
+
const NO_INPUT = Symbol('analog.serverFn.noInput');
|
|
907
|
+
function injectServerFn(fn, args) {
|
|
908
|
+
assertInInjectionContext(injectServerFn);
|
|
909
|
+
const client = inject(ServerFnClient);
|
|
910
|
+
return resource({
|
|
911
|
+
params: () => (args ? args() : NO_INPUT),
|
|
912
|
+
loader: async ({ params }) => {
|
|
913
|
+
const input = (params === NO_INPUT ? undefined : params);
|
|
914
|
+
// Hydrate from the SSR seed on first client render; else fetch and (on
|
|
915
|
+
// the server) seed for the client.
|
|
916
|
+
const seeded = client.readSeed(fn, input);
|
|
917
|
+
if (seeded !== undefined)
|
|
918
|
+
return seeded;
|
|
919
|
+
const value = await client.call(fn, input);
|
|
920
|
+
if (client.isServer) {
|
|
921
|
+
client.writeSeed(fn, input, value);
|
|
922
|
+
}
|
|
923
|
+
return value;
|
|
924
|
+
},
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Imperative binding of a server function: returns a callable that dispatches
|
|
929
|
+
* the call through `HttpClient` (so client interceptors apply) and resolves the
|
|
930
|
+
* result. Use for mutations and event-driven calls; use `injectServerFn` for
|
|
931
|
+
* reactive reads.
|
|
932
|
+
*/
|
|
933
|
+
function injectServerFnMutation(fn) {
|
|
934
|
+
assertInInjectionContext(injectServerFnMutation);
|
|
935
|
+
const client = inject(ServerFnClient);
|
|
936
|
+
return (input) => client.call(fn, input);
|
|
937
|
+
}
|
|
938
|
+
function stableInput(input) {
|
|
939
|
+
if (input === undefined || input === null)
|
|
940
|
+
return '_';
|
|
941
|
+
return JSON.stringify(input);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* Builds a server-function reference: the client-safe `{ __serverFn, id, url,
|
|
946
|
+
* method }` metadata that `injectServerFn`/`ServerFnClient` dispatch through.
|
|
947
|
+
*
|
|
948
|
+
* Shared by both sides so they produce identical refs: the server `serverFn`
|
|
949
|
+
* wraps this with registration + the handler, and the client build's scrub
|
|
950
|
+
* transform emits a call to this factory in place of the server module so the
|
|
951
|
+
* browser bundle carries only the ref, never the handler or its server imports.
|
|
952
|
+
*
|
|
953
|
+
* The returned value is callable-typed but throws if invoked directly — it is
|
|
954
|
+
* always dispatched via `injectServerFn`/`ServerFnClient`, never called.
|
|
955
|
+
*/
|
|
956
|
+
function createServerFnRef(config) {
|
|
957
|
+
if (!config.id) {
|
|
958
|
+
throw new Error('[analog] serverFn is missing its build-derived id. Server functions require the Analog build transform (@analogjs/platform / @analogjs/vite-plugin-nitro); a raw import without it is not supported.');
|
|
959
|
+
}
|
|
960
|
+
const method = config.method ?? (config.input ? 'POST' : 'GET');
|
|
961
|
+
const url = `/_analog/fn/${config.id}`;
|
|
962
|
+
const ref = (() => {
|
|
963
|
+
throw new Error(`serverFn "${config.id}" must be called via injectServerFn/ServerFnClient`);
|
|
964
|
+
});
|
|
965
|
+
return Object.assign(ref, {
|
|
966
|
+
__serverFn: true,
|
|
967
|
+
id: config.id,
|
|
968
|
+
url,
|
|
969
|
+
method,
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
|
|
845
973
|
/**
|
|
846
974
|
* Generated bundle index. Do not edit.
|
|
847
975
|
*/
|
|
848
976
|
|
|
849
|
-
export { FormAction, ServerOnly, createRoutes, defineRouteMeta, getLoadResolver, injectActivatedRoute, injectDebugRoutes, injectLoad, injectRouteEndpointURL, injectRouter, provideFileRouter, requestContextInterceptor, routes, withDebugRoutes, withExtraRoutes };
|
|
977
|
+
export { FormAction, SERVER_FN_DISPATCHER, ServerFnClient, ServerOnly, createRoutes, createServerFnRef, defineRouteMeta, getLoadResolver, injectActivatedRoute, injectDebugRoutes, injectLoad, injectRouteEndpointURL, injectRouter, injectServerFn, injectServerFnMutation, provideFileRouter, provideServerFnClient, requestContextInterceptor, routes, withDebugRoutes, withExtraRoutes };
|
|
850
978
|
//# sourceMappingURL=analogjs-router.mjs.map
|