@analogjs/router 3.0.0-alpha.90 → 3.0.0-alpha.92

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":"src.mjs","names":[],"sources":["../../server/actions/src/actions.ts","../../server/actions/src/parse-request-data.ts","../../server/actions/src/validate.ts","../../server/actions/src/define-action.ts","../../server/actions/src/define-server-route.ts","../../server/actions/src/define-page-load.ts"],"sourcesContent":["import type { H3Event, H3EventContext } from 'nitro/h3';\nimport type { $Fetch } from 'ofetch';\nimport type { NodeContext } from '../../../src/lib/route-types.js';\n\nexport type PageServerAction = {\n params: H3EventContext['params'];\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n};\n\nexport function fail<T = object>(status: number, errors: T): Response {\n return new Response(JSON.stringify(errors), {\n status,\n headers: {\n 'X-Analog-Errors': 'true',\n },\n });\n}\n\nexport function json<T = object>(data: T, config?: ResponseInit): Response {\n return new Response(JSON.stringify(data), {\n headers: {\n 'Content-Type': 'application/json; charset=utf-8',\n },\n ...config,\n });\n}\n\nexport function redirect(\n url: string,\n config: number | ResponseInit = 302,\n): Response {\n if (typeof config === 'number') {\n return new Response(null, {\n status: config,\n headers: {\n Location: `${url}`,\n },\n });\n }\n\n return new Response(null, {\n headers: {\n Location: `${url}`,\n },\n ...config,\n });\n}\n","import { readBody, readFormData, toRequest as h3ToRequest } from 'nitro/h3';\n\ntype RequestEntryValue = string | File;\ntype ParsedRequestValue = RequestEntryValue | RequestEntryValue[];\n\nfunction appendEntry(\n target: Record<string, ParsedRequestValue>,\n key: string,\n value: RequestEntryValue,\n) {\n const existingValue = target[key];\n\n if (existingValue === undefined) {\n target[key] = value;\n return;\n }\n\n if (Array.isArray(existingValue)) {\n existingValue.push(value);\n return;\n }\n\n target[key] = [existingValue, value];\n}\n\nfunction getRequest(event: { method: string; headers: Headers }): Request {\n const maybeRequest = (event as unknown as { request?: Request }).request;\n if (maybeRequest) {\n return maybeRequest;\n }\n return h3ToRequest(event as Parameters<typeof h3ToRequest>[0]);\n}\n\nfunction getContentType(event: { method: string; headers: Headers }): string {\n const request = getRequest(event);\n\n return (\n request.headers.get('content-type') ??\n event.headers.get('content-type') ??\n event.headers.get('Content-Type') ??\n ''\n );\n}\n\nfunction isJsonContentType(contentType: string): boolean {\n const mimeType = contentType.split(';', 1)[0]?.trim().toLowerCase() ?? '';\n return mimeType === 'application/json' || mimeType.endsWith('+json');\n}\n\nfunction isFormContentType(contentType: string): boolean {\n return (\n contentType.includes('multipart/form-data') ||\n contentType.includes('application/x-www-form-urlencoded')\n );\n}\n\nexport function parseSearchParams(\n searchParams: URLSearchParams,\n): Record<string, ParsedRequestValue> {\n const result: Record<string, ParsedRequestValue> = {};\n searchParams.forEach((value, key) => {\n appendEntry(result, key, value);\n });\n return result;\n}\n\nexport function parseFormData(\n formData: FormData,\n): Record<string, ParsedRequestValue> {\n const result: Record<string, ParsedRequestValue> = {};\n formData.forEach((value, key) => {\n appendEntry(result, key, value as RequestEntryValue);\n });\n return result;\n}\n\nexport async function parseRequestData(event: {\n method: string;\n headers: Headers;\n}): Promise<unknown> {\n const request = getRequest(event);\n const httpEvent = event as unknown as Parameters<typeof readBody>[0];\n const h3Event = event as unknown as Parameters<typeof readFormData>[0];\n const method = event.method.toUpperCase();\n\n if (method === 'GET' || method === 'HEAD') {\n const url = new URL(request.url, 'http://localhost');\n return parseSearchParams(url.searchParams);\n }\n\n const contentType = getContentType(event);\n\n if (isJsonContentType(contentType)) {\n try {\n return (await readBody(httpEvent)) ?? {};\n } catch {\n try {\n return await request.json();\n } catch {\n return {};\n }\n }\n }\n\n if (isFormContentType(contentType)) {\n try {\n return parseFormData(await readFormData(h3Event));\n } catch {\n if (typeof request.formData === 'function') {\n return parseFormData(await request.formData());\n }\n\n return {};\n }\n }\n\n try {\n return (await readBody(httpEvent)) ?? {};\n } catch {\n try {\n return await request.json();\n } catch {\n return {};\n }\n }\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\n\n/**\n * Validates unknown input against a Standard Schema.\n *\n * Handles both sync and async `validate` implementations — the Standard\n * Schema spec allows either return shape.\n */\nexport async function validateWithSchema<T extends StandardSchemaV1>(\n schema: T,\n data: unknown,\n): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<T>>> {\n return schema['~standard'].validate(data);\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { H3Event, H3EventContext } from 'nitro/h3';\nimport type { $Fetch } from 'ofetch';\nimport { fail } from './actions';\nimport { parseRequestData } from './parse-request-data';\nimport { validateWithSchema } from './validate';\n\ntype NodeContext = NonNullable<H3Event['node']>;\ntype OptionalSchema = StandardSchemaV1 | undefined;\ntype InferSchema<\n TSchema extends OptionalSchema,\n TFallback,\n> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : TFallback;\n\nexport interface DefineActionContext<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n> {\n data: InferSchema<TSchema, Record<string, unknown>>;\n params: InferSchema<TParamsSchema, H3EventContext['params']>;\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n}\n\nexport interface DefineActionOptions<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n> {\n schema?: TSchema;\n params?: TParamsSchema;\n handler: (\n context: DefineActionContext<TSchema, TParamsSchema>,\n ) => Promise<Response> | Response;\n}\n\n/**\n * Creates a server action handler with Standard Schema input validation.\n *\n * Parses the request body (JSON or FormData) and validates it against the\n * provided schema before invoking the handler. On validation failure,\n * returns `fail(422, issues)` with `StandardSchemaV1.Issue[]`.\n * Repeated form fields are preserved as arrays instead of being collapsed\n * to the last value.\n *\n * @example\n * ```typescript\n * import { defineAction, json } from '@analogjs/router/server/actions';\n * import * as v from 'valibot';\n *\n * const Schema = v.object({\n * email: v.pipe(v.string(), v.email()),\n * });\n *\n * export const action = defineAction({\n * schema: Schema,\n * handler: async ({ data }) => {\n * // data is typed as { email: string }\n * return json({ ok: true });\n * },\n * });\n * ```\n */\nexport function defineAction<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n>(options: DefineActionOptions<TSchema, TParamsSchema>) {\n type Params = InferSchema<TParamsSchema, H3EventContext['params']>;\n\n function getParams(\n params: H3EventContext['params'],\n ): Params | Record<string, never> {\n return (params ?? {}) as Params | Record<string, never>;\n }\n\n return async (ctx: {\n params: H3EventContext['params'];\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n }): Promise<Response> => {\n const rawParams = getParams(ctx.params);\n\n if (options.params) {\n const paramsResult = await validateWithSchema(options.params, rawParams);\n if (paramsResult.issues) {\n return fail(422, paramsResult.issues);\n }\n return handleValidatedRequest(ctx, options, paramsResult.value as Params);\n }\n\n return handleValidatedRequest(ctx, options, rawParams as Params);\n };\n}\n\nasync function handleValidatedRequest<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n>(\n ctx: {\n params: H3EventContext['params'];\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n },\n options: DefineActionOptions<TSchema, TParamsSchema>,\n params: InferSchema<TParamsSchema, H3EventContext['params']>,\n) {\n type Data = InferSchema<TSchema, Record<string, unknown>>;\n const body = await parseRequestData(ctx.event);\n\n let data: unknown = body;\n\n if (options.schema) {\n const result = await validateWithSchema(options.schema, body);\n if (result.issues) {\n return fail(422, result.issues);\n }\n data = result.value;\n }\n\n return options.handler({\n data: data as Data,\n params,\n req: ctx.req,\n res: ctx.res,\n fetch: ctx.fetch,\n event: ctx.event,\n });\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { H3Event } from 'nitro/h3';\nimport { getRequestURL } from 'nitro/h3';\nimport { fail, json } from './actions';\nimport { parseRequestData, parseSearchParams } from './parse-request-data';\nimport { validateWithSchema } from './validate';\n\nexport type DefineServerRouteResult = Response | unknown;\n\nexport interface ServerRouteHandler<\n TQuery = unknown,\n TBody = unknown,\n TResult = unknown,\n> {\n (event: H3Event): Promise<Response>;\n readonly _types: {\n readonly query: TQuery;\n readonly body: TBody;\n readonly result: TResult;\n };\n}\n\nexport type InferRouteQuery<T> =\n T extends ServerRouteHandler<infer Q, any, any> ? Q : never;\nexport type InferRouteBody<T> =\n T extends ServerRouteHandler<any, infer B, any> ? B : never;\nexport type InferRouteResult<T> =\n T extends ServerRouteHandler<any, any, infer R>\n ? Exclude<R, Response>\n : never;\n\ntype OptionalSchema = StandardSchemaV1 | undefined;\ntype InferSchema<\n TSchema extends OptionalSchema,\n TFallback = unknown,\n> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : TFallback;\ntype ResolveDataSchema<\n TInput extends OptionalSchema,\n TQuery extends OptionalSchema,\n TBody extends OptionalSchema,\n> = TInput extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TInput>\n : TQuery extends StandardSchemaV1\n ? TBody extends StandardSchemaV1\n ?\n | StandardSchemaV1.InferOutput<TQuery>\n | StandardSchemaV1.InferOutput<TBody>\n : StandardSchemaV1.InferOutput<TQuery>\n : TBody extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TBody>\n : unknown;\n\nexport interface DefineServerRouteContext<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n> {\n data: ResolveDataSchema<TInput, TQuery, TBody>;\n query: InferSchema<TQuery, undefined>;\n body: InferSchema<TBody, undefined>;\n params: InferSchema<TParams, H3Event['context']['params']>;\n event: H3Event;\n}\n\nexport interface DefineServerRouteOptions<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TOutput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n TResult extends DefineServerRouteResult = DefineServerRouteResult,\n> {\n input?: TInput;\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n output?: TOutput;\n handler: (\n context: DefineServerRouteContext<TInput, TQuery, TBody, TParams>,\n ) => Promise<TResult> | TResult;\n}\n\nfunction isDevEnvironment() {\n return (\n typeof process !== 'undefined' &&\n (process.env['NODE_ENV'] === 'development' ||\n process.env['NODE_ENV'] === 'test')\n );\n}\n\nfunction warnOnOutputIssues(issues: ReadonlyArray<StandardSchemaV1.Issue>) {\n console.warn(\n `[analog] Server route output validation failed:\\n` +\n issues\n .map((i) => {\n const path = i.path\n ? ` at \"${i.path.map((p) => (typeof p === 'object' ? (p as { key: string }).key : p)).join('.')}\"`\n : '';\n return ` - ${i.message}${path}`;\n })\n .join('\\n'),\n );\n}\n\nfunction getRequestUrl(event: H3Event): string {\n try {\n return getRequestURL(event).href;\n } catch {\n return (event as H3Event & { request: Request }).request.url;\n }\n}\n\n/**\n * Creates an h3-compatible event handler with Standard Schema validation.\n *\n * - `input` schema validates the request body (POST/PUT/PATCH) or query\n * params (GET). Returns 422 with `StandardSchemaV1.Issue[]` on failure.\n * - `output` schema validates the response in development only (stripped\n * in production for zero overhead). Logs a warning on mismatch.\n * - Plain return values are serialized with `json(...)`; raw `Response`\n * objects are returned unchanged.\n *\n * @example\n * ```typescript\n * import { defineServerRoute } from '@analogjs/router/server/actions';\n * import * as v from 'valibot';\n *\n * const Input = v.object({\n * name: v.pipe(v.string(), v.minLength(1)),\n * email: v.pipe(v.string(), v.email()),\n * });\n * const Output = v.object({\n * id: v.string(),\n * name: v.string(),\n * });\n *\n * export default defineServerRoute({\n * input: Input,\n * output: Output,\n * handler: async ({ data }) => {\n * const user = await db.users.create(data);\n * return user;\n * },\n * });\n * ```\n */\nexport function defineServerRoute<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TOutput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n TResult extends DefineServerRouteResult = DefineServerRouteResult,\n>(\n options: DefineServerRouteOptions<\n TInput,\n TOutput,\n TQuery,\n TBody,\n TParams,\n TResult\n >,\n): ServerRouteHandler<\n InferSchema<TQuery, undefined>,\n InferSchema<TBody, undefined>,\n TResult\n> {\n return (async (event: H3Event): Promise<Response> => {\n const method = event.method.toUpperCase();\n let data: unknown;\n let query: unknown;\n let body: unknown;\n let params: unknown = event.context?.params ?? {};\n\n if (options.params) {\n const paramsResult = await validateWithSchema(options.params, params);\n if (paramsResult.issues) {\n return fail(422, paramsResult.issues);\n }\n params = paramsResult.value;\n }\n\n if (options.input) {\n data = await parseRequestData(event);\n\n const inputResult = await validateWithSchema(options.input, data);\n if (inputResult.issues) {\n return fail(422, inputResult.issues);\n }\n data = inputResult.value;\n } else {\n if (options.query) {\n const url = new URL(getRequestUrl(event), 'http://localhost');\n const queryResult = await validateWithSchema(\n options.query,\n parseSearchParams(url.searchParams),\n );\n if (queryResult.issues) {\n return fail(422, queryResult.issues);\n }\n query = queryResult.value;\n }\n\n if (options.body && method !== 'GET' && method !== 'HEAD') {\n body = await parseRequestData(event);\n const bodyResult = await validateWithSchema(options.body, body);\n if (bodyResult.issues) {\n return fail(422, bodyResult.issues);\n }\n body = bodyResult.value;\n }\n\n if (method === 'GET' || method === 'HEAD') {\n data = query;\n } else if (body !== undefined) {\n data = body;\n } else {\n data = query;\n }\n }\n\n const result = await options.handler({\n data: data as ResolveDataSchema<TInput, TQuery, TBody>,\n query: query as InferSchema<TQuery, undefined>,\n body: body as InferSchema<TBody, undefined>,\n params: params as InferSchema<TParams, H3Event['context']['params']>,\n event,\n });\n\n if (result instanceof Response) {\n return result;\n }\n\n if (options.output && isDevEnvironment()) {\n const outputResult = await validateWithSchema(options.output, result);\n if (outputResult.issues) {\n warnOnOutputIssues(outputResult.issues);\n }\n }\n\n return json(result);\n }) as ServerRouteHandler<\n InferSchema<TQuery, undefined>,\n InferSchema<TBody, undefined>,\n TResult\n >;\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { H3Event, H3EventContext } from 'nitro/h3';\nimport { getRequestURL } from 'nitro/h3';\nimport type { $Fetch } from 'ofetch';\nimport { fail } from './actions';\nimport { parseSearchParams } from './parse-request-data';\nimport { validateWithSchema } from './validate';\n\ntype NodeContext = NonNullable<H3Event['node']>;\ntype OptionalSchema = StandardSchemaV1 | undefined;\ntype InferSchema<\n TSchema extends OptionalSchema,\n TFallback,\n> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : TFallback;\n\nexport interface PageLoadContext<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n> {\n params: InferSchema<TParamsSchema, H3EventContext['params']>;\n query: InferSchema<\n TQuerySchema,\n Record<string, string | string[] | undefined>\n >;\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n}\n\nexport interface DefinePageLoadOptions<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n TResult = unknown,\n> {\n params?: TParamsSchema;\n query?: TQuerySchema;\n handler: (\n context: PageLoadContext<TParamsSchema, TQuerySchema>,\n ) => Promise<TResult> | TResult;\n}\n\n/**\n * Creates a typed page server load function with optional\n * Standard Schema validation for route params and query.\n *\n * Follows the same validation patterns as `defineAction` and\n * `defineServerRoute`: validates before invoking the handler,\n * returns `fail(422, issues)` on validation failure.\n *\n * @example\n * ```typescript\n * // src/app/pages/users/[id].server.ts\n * import { definePageLoad } from '@analogjs/router/server/actions';\n * import * as v from 'valibot';\n *\n * export const routeParamsSchema = v.object({\n * id: v.pipe(v.string(), v.regex(/^\\d+$/)),\n * });\n *\n * export const load = definePageLoad({\n * params: routeParamsSchema,\n * handler: async ({ params, fetch }) => {\n * // params.id is typed as string (validated)\n * const user = await fetch(`/api/users/${params.id}`);\n * return user;\n * },\n * });\n * ```\n */\nexport function definePageLoad<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n TResult = unknown,\n>(\n options: DefinePageLoadOptions<TParamsSchema, TQuerySchema, TResult>,\n): (ctx: {\n params: H3EventContext['params'];\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n}) => Promise<TResult | Response> {\n type Params = InferSchema<TParamsSchema, H3EventContext['params']>;\n type Query = InferSchema<\n TQuerySchema,\n Record<string, string | string[] | undefined>\n >;\n\n return async (ctx: {\n params: H3EventContext['params'];\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n }) => {\n let params: unknown = ctx.params ?? {};\n\n let requestUrl: string;\n try {\n requestUrl = getRequestURL(ctx.event).href;\n } catch {\n requestUrl = (ctx.event as H3Event & { request: Request }).request.url;\n }\n const url = new URL(requestUrl, 'http://localhost');\n let query: unknown = parseSearchParams(url.searchParams);\n\n // Validate params\n if (options.params) {\n const result = await validateWithSchema(options.params, params);\n if (result.issues) {\n return fail(422, result.issues);\n }\n params = result.value;\n }\n\n // Validate query\n if (options.query) {\n const result = await validateWithSchema(options.query, query);\n if (result.issues) {\n return fail(422, result.issues);\n }\n query = result.value;\n }\n\n return options.handler({\n params: params as Params,\n query: query as Query,\n req: ctx.req,\n res: ctx.res,\n fetch: ctx.fetch,\n event: ctx.event,\n });\n };\n}\n"],"mappings":";;AAYA,SAAgB,KAAiB,QAAgB,QAAS;AACxD,QAAO,IAAI,SAAS,KAAK,UAAU,OAAO,EAAE;EAC1C;EACA,SAAS,EACP,mBAAmB,QACpB;EACF,CAAC;;AAGJ,SAAgB,KAAiB,MAAS,QAAqB;AAC7D,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC,SAAS,EAC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AY,mBAAmB,CACR,aAAa;AAGxD,MAAI,QAAQ,QAAQ;GAClB,MAAM,SAAS,MAAM,mBAAmB,QAAQ,QAAQ,OAAO;AAC/D,OAAI,OAAO,OACT,QAAO,KAAK,KAAK,OAAO,OAAO;AAEjC,YAAS,OAAO;;AAIlB,MAAI,QAAQ,OAAO;GACjB,MAAM,SAAS,MAAM,mBAAmB,QAAQ,OAAO,MAAM;AAC7D,OAAI,OAAO,OACT,QAAO,KAAK,KAAK,OAAO,OAAO;AAEjC,WAAQ,OAAO;;AAGjB,SAAO,QAAQ,QAAQ;GACb;GACD;GACP,KAAK,IAAI;GACT,KAAK,IAAI;GACT,OAAO,IAAI;GACX,OAAO,IAAI;GACZ,CAAC"}
1
+ {"version":3,"file":"src.mjs","names":[],"sources":["../../server/actions/src/actions.ts","../../server/actions/src/parse-request-data.ts","../../server/actions/src/validate.ts","../../server/actions/src/define-action.ts","../../server/actions/src/define-server-route.ts","../../server/actions/src/define-page-load.ts"],"sourcesContent":["import type { H3Event, H3EventContext } from 'h3';\nimport type { $Fetch } from 'ofetch';\nimport type { NodeContext } from '../../../src/lib/route-types.js';\n\nexport type PageServerAction = {\n params: H3EventContext['params'];\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n};\n\nexport function fail<T = object>(status: number, errors: T): Response {\n return new Response(JSON.stringify(errors), {\n status,\n headers: {\n 'X-Analog-Errors': 'true',\n },\n });\n}\n\nexport function json<T = object>(data: T, config?: ResponseInit): Response {\n return new Response(JSON.stringify(data), {\n headers: {\n 'Content-Type': 'application/json; charset=utf-8',\n },\n ...config,\n });\n}\n\nexport function redirect(\n url: string,\n config: number | ResponseInit = 302,\n): Response {\n if (typeof config === 'number') {\n return new Response(null, {\n status: config,\n headers: {\n Location: `${url}`,\n },\n });\n }\n\n return new Response(null, {\n headers: {\n Location: `${url}`,\n },\n ...config,\n });\n}\n","import { getRequestURL, readBody, readFormData } from 'h3';\n\ntype RequestEntryValue = string | File;\ntype ParsedRequestValue = RequestEntryValue | RequestEntryValue[];\n\nfunction appendEntry(\n target: Record<string, ParsedRequestValue>,\n key: string,\n value: RequestEntryValue,\n) {\n const existingValue = target[key];\n\n if (existingValue === undefined) {\n target[key] = value;\n return;\n }\n\n if (Array.isArray(existingValue)) {\n existingValue.push(value);\n return;\n }\n\n target[key] = [existingValue, value];\n}\n\n// h3 v2 exposes the web Request as `event.req`; h3 v1 has no web Request on\n// Node, so callers fall back to the h3 helpers shared by both versions.\nfunction getRequest(event: {\n method: string;\n headers: Headers;\n}): Request | undefined {\n const { request, req } = event as unknown as {\n request?: Request;\n req?: unknown;\n };\n return request ?? (req instanceof Request ? req : undefined);\n}\n\nfunction getContentType(event: { method: string; headers: Headers }): string {\n const request = getRequest(event);\n\n return (\n request?.headers.get('content-type') ??\n event.headers?.get('content-type') ??\n ''\n );\n}\n\nfunction isJsonContentType(contentType: string): boolean {\n const mimeType = contentType.split(';', 1)[0]?.trim().toLowerCase() ?? '';\n return mimeType === 'application/json' || mimeType.endsWith('+json');\n}\n\nfunction isFormContentType(contentType: string): boolean {\n return (\n contentType.includes('multipart/form-data') ||\n contentType.includes('application/x-www-form-urlencoded')\n );\n}\n\nexport function parseSearchParams(\n searchParams: URLSearchParams,\n): Record<string, ParsedRequestValue> {\n const result: Record<string, ParsedRequestValue> = {};\n searchParams.forEach((value, key) => {\n appendEntry(result, key, value);\n });\n return result;\n}\n\nexport function parseFormData(\n formData: FormData,\n): Record<string, ParsedRequestValue> {\n const result: Record<string, ParsedRequestValue> = {};\n formData.forEach((value, key) => {\n appendEntry(result, key, value as RequestEntryValue);\n });\n return result;\n}\n\nexport async function parseRequestData(event: {\n method: string;\n headers: Headers;\n}): Promise<unknown> {\n const request = getRequest(event);\n const httpEvent = event as unknown as Parameters<typeof readBody>[0];\n const h3Event = event as unknown as Parameters<typeof readFormData>[0];\n const method = event.method.toUpperCase();\n\n if (method === 'GET' || method === 'HEAD') {\n const url = new URL(\n request?.url ?? getRequestURL(httpEvent).href,\n 'http://localhost',\n );\n return parseSearchParams(url.searchParams);\n }\n\n const contentType = getContentType(event);\n\n if (isJsonContentType(contentType)) {\n try {\n return (await readBody(httpEvent)) ?? {};\n } catch {\n try {\n return (await request?.json()) ?? {};\n } catch {\n return {};\n }\n }\n }\n\n if (isFormContentType(contentType)) {\n try {\n return parseFormData(await readFormData(h3Event));\n } catch {\n if (request) {\n return parseFormData(await request.formData());\n }\n\n return {};\n }\n }\n\n try {\n return (await readBody(httpEvent)) ?? {};\n } catch {\n try {\n return (await request?.json()) ?? {};\n } catch {\n return {};\n }\n }\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\n\n/**\n * Validates unknown input against a Standard Schema.\n *\n * Handles both sync and async `validate` implementations — the Standard\n * Schema spec allows either return shape.\n */\nexport async function validateWithSchema<T extends StandardSchemaV1>(\n schema: T,\n data: unknown,\n): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<T>>> {\n return schema['~standard'].validate(data);\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { H3Event, H3EventContext } from 'h3';\nimport type { $Fetch } from 'ofetch';\nimport { fail } from './actions';\nimport { parseRequestData } from './parse-request-data';\nimport { validateWithSchema } from './validate';\n\ntype NodeContext = NonNullable<H3Event['node']>;\ntype OptionalSchema = StandardSchemaV1 | undefined;\ntype InferSchema<\n TSchema extends OptionalSchema,\n TFallback,\n> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : TFallback;\n\nexport interface DefineActionContext<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n> {\n data: InferSchema<TSchema, Record<string, unknown>>;\n params: InferSchema<TParamsSchema, H3EventContext['params']>;\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n}\n\nexport interface DefineActionOptions<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n> {\n schema?: TSchema;\n params?: TParamsSchema;\n handler: (\n context: DefineActionContext<TSchema, TParamsSchema>,\n ) => Promise<Response> | Response;\n}\n\n/**\n * Creates a server action handler with Standard Schema input validation.\n *\n * Parses the request body (JSON or FormData) and validates it against the\n * provided schema before invoking the handler. On validation failure,\n * returns `fail(422, issues)` with `StandardSchemaV1.Issue[]`.\n * Repeated form fields are preserved as arrays instead of being collapsed\n * to the last value.\n *\n * @example\n * ```typescript\n * import { defineAction, json } from '@analogjs/router/server/actions';\n * import * as v from 'valibot';\n *\n * const Schema = v.object({\n * email: v.pipe(v.string(), v.email()),\n * });\n *\n * export const action = defineAction({\n * schema: Schema,\n * handler: async ({ data }) => {\n * // data is typed as { email: string }\n * return json({ ok: true });\n * },\n * });\n * ```\n */\nexport function defineAction<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n>(options: DefineActionOptions<TSchema, TParamsSchema>) {\n type Params = InferSchema<TParamsSchema, H3EventContext['params']>;\n\n function getParams(\n params: H3EventContext['params'],\n ): Params | Record<string, never> {\n return (params ?? {}) as Params | Record<string, never>;\n }\n\n return async (ctx: {\n params: H3EventContext['params'];\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n }): Promise<Response> => {\n const rawParams = getParams(ctx.params);\n\n if (options.params) {\n const paramsResult = await validateWithSchema(options.params, rawParams);\n if (paramsResult.issues) {\n return fail(422, paramsResult.issues);\n }\n return handleValidatedRequest(ctx, options, paramsResult.value as Params);\n }\n\n return handleValidatedRequest(ctx, options, rawParams as Params);\n };\n}\n\nasync function handleValidatedRequest<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n>(\n ctx: {\n params: H3EventContext['params'];\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n },\n options: DefineActionOptions<TSchema, TParamsSchema>,\n params: InferSchema<TParamsSchema, H3EventContext['params']>,\n) {\n type Data = InferSchema<TSchema, Record<string, unknown>>;\n const body = await parseRequestData(ctx.event);\n\n let data: unknown = body;\n\n if (options.schema) {\n const result = await validateWithSchema(options.schema, body);\n if (result.issues) {\n return fail(422, result.issues);\n }\n data = result.value;\n }\n\n return options.handler({\n data: data as Data,\n params,\n req: ctx.req,\n res: ctx.res,\n fetch: ctx.fetch,\n event: ctx.event,\n });\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { H3Event } from 'h3';\nimport { getRequestURL } from 'h3';\nimport { fail, json } from './actions';\nimport { parseRequestData, parseSearchParams } from './parse-request-data';\nimport { validateWithSchema } from './validate';\n\nexport type DefineServerRouteResult = Response | unknown;\n\nexport interface ServerRouteHandler<\n TQuery = unknown,\n TBody = unknown,\n TResult = unknown,\n> {\n (event: H3Event): Promise<Response>;\n readonly _types: {\n readonly query: TQuery;\n readonly body: TBody;\n readonly result: TResult;\n };\n}\n\nexport type InferRouteQuery<T> =\n T extends ServerRouteHandler<infer Q, any, any> ? Q : never;\nexport type InferRouteBody<T> =\n T extends ServerRouteHandler<any, infer B, any> ? B : never;\nexport type InferRouteResult<T> =\n T extends ServerRouteHandler<any, any, infer R>\n ? Exclude<R, Response>\n : never;\n\ntype OptionalSchema = StandardSchemaV1 | undefined;\ntype InferSchema<\n TSchema extends OptionalSchema,\n TFallback = unknown,\n> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : TFallback;\ntype ResolveDataSchema<\n TInput extends OptionalSchema,\n TQuery extends OptionalSchema,\n TBody extends OptionalSchema,\n> = TInput extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TInput>\n : TQuery extends StandardSchemaV1\n ? TBody extends StandardSchemaV1\n ?\n | StandardSchemaV1.InferOutput<TQuery>\n | StandardSchemaV1.InferOutput<TBody>\n : StandardSchemaV1.InferOutput<TQuery>\n : TBody extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TBody>\n : unknown;\n\nexport interface DefineServerRouteContext<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n> {\n data: ResolveDataSchema<TInput, TQuery, TBody>;\n query: InferSchema<TQuery, undefined>;\n body: InferSchema<TBody, undefined>;\n params: InferSchema<TParams, H3Event['context']['params']>;\n event: H3Event;\n}\n\nexport interface DefineServerRouteOptions<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TOutput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n TResult extends DefineServerRouteResult = DefineServerRouteResult,\n> {\n input?: TInput;\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n output?: TOutput;\n handler: (\n context: DefineServerRouteContext<TInput, TQuery, TBody, TParams>,\n ) => Promise<TResult> | TResult;\n}\n\nfunction isDevEnvironment() {\n return (\n typeof process !== 'undefined' &&\n (process.env['NODE_ENV'] === 'development' ||\n process.env['NODE_ENV'] === 'test')\n );\n}\n\nfunction warnOnOutputIssues(issues: ReadonlyArray<StandardSchemaV1.Issue>) {\n console.warn(\n `[analog] Server route output validation failed:\\n` +\n issues\n .map((i) => {\n const path = i.path\n ? ` at \"${i.path.map((p) => (typeof p === 'object' ? (p as { key: string }).key : p)).join('.')}\"`\n : '';\n return ` - ${i.message}${path}`;\n })\n .join('\\n'),\n );\n}\n\nfunction getRequestUrl(event: H3Event): string {\n try {\n return getRequestURL(event).href;\n } catch {\n return (event as H3Event & { request: Request }).request.url;\n }\n}\n\n/**\n * Creates an h3-compatible event handler with Standard Schema validation.\n *\n * - `input` schema validates the request body (POST/PUT/PATCH) or query\n * params (GET). Returns 422 with `StandardSchemaV1.Issue[]` on failure.\n * - `output` schema validates the response in development only (stripped\n * in production for zero overhead). Logs a warning on mismatch.\n * - Plain return values are serialized with `json(...)`; raw `Response`\n * objects are returned unchanged.\n *\n * @example\n * ```typescript\n * import { defineServerRoute } from '@analogjs/router/server/actions';\n * import * as v from 'valibot';\n *\n * const Input = v.object({\n * name: v.pipe(v.string(), v.minLength(1)),\n * email: v.pipe(v.string(), v.email()),\n * });\n * const Output = v.object({\n * id: v.string(),\n * name: v.string(),\n * });\n *\n * export default defineServerRoute({\n * input: Input,\n * output: Output,\n * handler: async ({ data }) => {\n * const user = await db.users.create(data);\n * return user;\n * },\n * });\n * ```\n */\nexport function defineServerRoute<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TOutput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n TResult extends DefineServerRouteResult = DefineServerRouteResult,\n>(\n options: DefineServerRouteOptions<\n TInput,\n TOutput,\n TQuery,\n TBody,\n TParams,\n TResult\n >,\n): ServerRouteHandler<\n InferSchema<TQuery, undefined>,\n InferSchema<TBody, undefined>,\n TResult\n> {\n return (async (event: H3Event): Promise<Response> => {\n const method = event.method.toUpperCase();\n let data: unknown;\n let query: unknown;\n let body: unknown;\n let params: unknown = event.context?.params ?? {};\n\n if (options.params) {\n const paramsResult = await validateWithSchema(options.params, params);\n if (paramsResult.issues) {\n return fail(422, paramsResult.issues);\n }\n params = paramsResult.value;\n }\n\n if (options.input) {\n data = await parseRequestData(event);\n\n const inputResult = await validateWithSchema(options.input, data);\n if (inputResult.issues) {\n return fail(422, inputResult.issues);\n }\n data = inputResult.value;\n } else {\n if (options.query) {\n const url = new URL(getRequestUrl(event), 'http://localhost');\n const queryResult = await validateWithSchema(\n options.query,\n parseSearchParams(url.searchParams),\n );\n if (queryResult.issues) {\n return fail(422, queryResult.issues);\n }\n query = queryResult.value;\n }\n\n if (options.body && method !== 'GET' && method !== 'HEAD') {\n body = await parseRequestData(event);\n const bodyResult = await validateWithSchema(options.body, body);\n if (bodyResult.issues) {\n return fail(422, bodyResult.issues);\n }\n body = bodyResult.value;\n }\n\n if (method === 'GET' || method === 'HEAD') {\n data = query;\n } else if (body !== undefined) {\n data = body;\n } else {\n data = query;\n }\n }\n\n const result = await options.handler({\n data: data as ResolveDataSchema<TInput, TQuery, TBody>,\n query: query as InferSchema<TQuery, undefined>,\n body: body as InferSchema<TBody, undefined>,\n params: params as InferSchema<TParams, H3Event['context']['params']>,\n event,\n });\n\n if (result instanceof Response) {\n return result;\n }\n\n if (options.output && isDevEnvironment()) {\n const outputResult = await validateWithSchema(options.output, result);\n if (outputResult.issues) {\n warnOnOutputIssues(outputResult.issues);\n }\n }\n\n return json(result);\n }) as ServerRouteHandler<\n InferSchema<TQuery, undefined>,\n InferSchema<TBody, undefined>,\n TResult\n >;\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { H3Event, H3EventContext } from 'h3';\nimport { getRequestURL } from 'h3';\nimport type { $Fetch } from 'ofetch';\nimport { fail } from './actions';\nimport { parseSearchParams } from './parse-request-data';\nimport { validateWithSchema } from './validate';\n\ntype NodeContext = NonNullable<H3Event['node']>;\ntype OptionalSchema = StandardSchemaV1 | undefined;\ntype InferSchema<\n TSchema extends OptionalSchema,\n TFallback,\n> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : TFallback;\n\nexport interface PageLoadContext<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n> {\n params: InferSchema<TParamsSchema, H3EventContext['params']>;\n query: InferSchema<\n TQuerySchema,\n Record<string, string | string[] | undefined>\n >;\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n}\n\nexport interface DefinePageLoadOptions<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n TResult = unknown,\n> {\n params?: TParamsSchema;\n query?: TQuerySchema;\n handler: (\n context: PageLoadContext<TParamsSchema, TQuerySchema>,\n ) => Promise<TResult> | TResult;\n}\n\n/**\n * Creates a typed page server load function with optional\n * Standard Schema validation for route params and query.\n *\n * Follows the same validation patterns as `defineAction` and\n * `defineServerRoute`: validates before invoking the handler,\n * returns `fail(422, issues)` on validation failure.\n *\n * @example\n * ```typescript\n * // src/app/pages/users/[id].server.ts\n * import { definePageLoad } from '@analogjs/router/server/actions';\n * import * as v from 'valibot';\n *\n * export const routeParamsSchema = v.object({\n * id: v.pipe(v.string(), v.regex(/^\\d+$/)),\n * });\n *\n * export const load = definePageLoad({\n * params: routeParamsSchema,\n * handler: async ({ params, fetch }) => {\n * // params.id is typed as string (validated)\n * const user = await fetch(`/api/users/${params.id}`);\n * return user;\n * },\n * });\n * ```\n */\nexport function definePageLoad<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n TResult = unknown,\n>(\n options: DefinePageLoadOptions<TParamsSchema, TQuerySchema, TResult>,\n): (ctx: {\n params: H3EventContext['params'];\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n}) => Promise<TResult | Response> {\n type Params = InferSchema<TParamsSchema, H3EventContext['params']>;\n type Query = InferSchema<\n TQuerySchema,\n Record<string, string | string[] | undefined>\n >;\n\n return async (ctx: {\n params: H3EventContext['params'];\n req: NodeContext['req'];\n res: NonNullable<NodeContext['res']>;\n fetch: $Fetch;\n event: H3Event;\n }) => {\n let params: unknown = ctx.params ?? {};\n\n let requestUrl: string;\n try {\n requestUrl = getRequestURL(ctx.event).href;\n } catch {\n requestUrl = (ctx.event as H3Event & { request: Request }).request.url;\n }\n const url = new URL(requestUrl, 'http://localhost');\n let query: unknown = parseSearchParams(url.searchParams);\n\n // Validate params\n if (options.params) {\n const result = await validateWithSchema(options.params, params);\n if (result.issues) {\n return fail(422, result.issues);\n }\n params = result.value;\n }\n\n // Validate query\n if (options.query) {\n const result = await validateWithSchema(options.query, query);\n if (result.issues) {\n return fail(422, result.issues);\n }\n query = result.value;\n }\n\n return options.handler({\n params: params as Params,\n query: query as Query,\n req: ctx.req,\n res: ctx.res,\n fetch: ctx.fetch,\n event: ctx.event,\n });\n };\n}\n"],"mappings":";;AAYA,SAAgB,KAAiB,QAAgB,QAAS;AACxD,QAAO,IAAI,SAAS,KAAK,UAAU,OAAO,EAAE;EAC1C;EACA,SAAS,EACP,mBAAmB,QACpB;EACF,CAAC;;AAGJ,SAAgB,KAAiB,MAAS,QAAqB;AAC7D,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC,SAAS,EACP,gBAAgB,mCACjB;EACD,GAAG;EACJ,CAAC;;AAGJ,SAAgB,SACd,KACA,SAAgC,KAAG;AAEnC,KAAI,OAAO,WAAW,SACpB,QAAO,IAAI,SAAS,MAAM;EACxB,QAAQ;EACR,SAAS,EACP,UAAU,GAAG,OACd;EACF,CAAC;AAGJ,QAAO,IAAI,SAAS,MAAM;EACxB,SAAS,EACP,UAAU,GAAG,OACd;EACD,GAAG;EACJ,CAAC;;;;AC3CJ,SAAS,YACP,QACA,KACA,OAAwB;CAExB,MAAM,gBAAgB,OAAO;AAE7B,KAAI,kBAAkB,KAAA,GAAW;AAC/B,SAAO,OAAO;AACd;;AAGF,KAAI,MAAM,QAAQ,cAAc,EAAE;AAChC,gBAAc,KAAK,MAAM;AACzB;;AAGF,QAAO,OAAO,CAAC,eAAe,MAAM;;AAKtC,SAAS,WAAW,OAGnB;CACC,MAAM,EAAE,SAAS,QAAQ;AAIzB,QAAO,YAAY,eAAe,UAAU,MAAM,KAAA;;AAGpD,SAAS,eAAe,OAA2C;AAGjE,QAFgB,WAAW,MAAM,EAGtB,QAAQ,IAAI,eAAe,IACpC,MAAM,SAAS,IAAI,eAAe,IAClC;;AAIJ,SAAS,kBAAkB,aAAmB;CAC5C,MAAM,WAAW,YAAY,MAAM,KAAK,EAAE,CAAC,IAAI,MAAM,CAAC,aAAa,IAAI;AACvE,QAAO,aAAa,sBAAsB,SAAS,SAAS,QAAQ;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O;AACrE,OAAI,aAAa,OACf,oBAAmB,aAAa,OAAO;;AAI3C,SAAO,KAAK,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC3KvB,SAAgB,eAKd,SAAoE;AAcpE,QAAO,OAAO,QAMT;EACH,IAAI,SAAkB,IAAI,UAAU,EAAE;EAEtC,IAAI;AACJ,MAAI;AACF,gBAAa,cAAc,IAAI,MAAM,CAAC;UAChC;AACN,gBAAc,IAAI,MAAyC,QAAQ;;EAGrE,IAAI,QAAiB,kBADT,IAAI,IAAI,YAAY,mBAAmB,CACR,aAAa;AAGxD,MAAI,QAAQ,QAAQ;GAClB,MAAM,SAAS,MAAM,mBAAmB,QAAQ,QAAQ,OAAO;AAC/D,OAAI,OAAO,OACT,QAAO,KAAK,KAAK,OAAO,OAAO;AAEjC,YAAS,OAAO;;AAIlB,MAAI,QAAQ,OAAO;GACjB,MAAM,SAAS,MAAM,mBAAmB,QAAQ,OAAO,MAAM;AAC7D,OAAI,OAAO,OACT,QAAO,KAAK,KAAK,OAAO,OAAO;AAEjC,WAAQ,OAAO;;AAGjB,SAAO,QAAQ,QAAQ;GACb;GACD;GACP,KAAK,IAAI;GACT,KAAK,IAAI;GACT,OAAO,IAAI;GACX,OAAO,IAAI;GACZ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@analogjs/router",
3
- "version": "3.0.0-alpha.90",
3
+ "version": "3.0.0-alpha.92",
4
4
  "description": "Filesystem-based routing for Angular",
5
5
  "type": "module",
6
6
  "author": "Brandon Roberts <robertsbt@gmail.com>",
@@ -69,27 +69,31 @@
69
69
  "url": "https://github.com/sponsors/brandonroberts"
70
70
  },
71
71
  "peerDependencies": {
72
- "@analogjs/content": "3.0.0-alpha.90",
73
- "@standard-schema/spec": "^1.1.0",
72
+ "@analogjs/content": "3.0.0-alpha.92",
74
73
  "@angular/core": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^20.0.0 || ^21.0.0 || ^22.0.0",
75
74
  "@angular/platform-server": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^20.0.0 || ^21.0.0 || ^22.0.0",
76
75
  "@angular/router": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^20.0.0 || ^21.0.0 || ^22.0.0",
76
+ "@standard-schema/spec": "^1.1.0",
77
77
  "@tanstack/angular-query-experimental": ">=5.95.0",
78
+ "h3": "^1.13.0 || ^2.0.0-rc.0",
78
79
  "schema-dts": "^2.0.0"
79
80
  },
80
81
  "peerDependenciesMeta": {
81
82
  "@analogjs/content": {
82
83
  "optional": true
83
84
  },
84
- "@standard-schema/spec": {
85
+ "@angular/platform-server": {
85
86
  "optional": true
86
87
  },
87
- "@angular/platform-server": {
88
+ "@standard-schema/spec": {
88
89
  "optional": true
89
90
  },
90
91
  "@tanstack/angular-query-experimental": {
91
92
  "optional": true
92
93
  },
94
+ "h3": {
95
+ "optional": true
96
+ },
93
97
  "schema-dts": {
94
98
  "optional": true
95
99
  }
@@ -101,8 +105,8 @@
101
105
  "tslib": "^2.3.0"
102
106
  },
103
107
  "devDependencies": {
104
- "@analogjs/vite-plugin-angular": "3.0.0-alpha.90",
105
- "@analogjs/vitest-angular": "3.0.0-alpha.90"
108
+ "@analogjs/vite-plugin-angular": "3.0.0-alpha.92",
109
+ "@analogjs/vitest-angular": "3.0.0-alpha.92"
106
110
  },
107
111
  "ng-update": {
108
112
  "packageGroup": [
@@ -1,4 +1,4 @@
1
- import type { H3Event, H3EventContext } from 'nitro/h3';
1
+ import type { H3Event, H3EventContext } from 'h3';
2
2
  import type { $Fetch } from 'ofetch';
3
3
  import type { NodeContext } from '../../../src/lib/route-types.js';
4
4
  export type PageServerAction = {
@@ -1,5 +1,5 @@
1
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
- import type { H3Event, H3EventContext } from 'nitro/h3';
2
+ import type { H3Event, H3EventContext } from 'h3';
3
3
  import type { $Fetch } from 'ofetch';
4
4
  type NodeContext = NonNullable<H3Event['node']>;
5
5
  type OptionalSchema = StandardSchemaV1 | undefined;
@@ -1,5 +1,5 @@
1
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
- import type { H3Event } from 'nitro/h3';
2
+ import type { H3Event } from 'h3';
3
3
  export type DefineApiRouteResult = Response | unknown;
4
4
  type OptionalSchema = StandardSchemaV1 | undefined;
5
5
  type InferSchema<TSchema extends OptionalSchema, TFallback = unknown> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TFallback;
@@ -1,5 +1,5 @@
1
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
- import type { H3Event, H3EventContext } from 'nitro/h3';
2
+ import type { H3Event, H3EventContext } from 'h3';
3
3
  import type { $Fetch } from 'ofetch';
4
4
  type NodeContext = NonNullable<H3Event['node']>;
5
5
  type OptionalSchema = StandardSchemaV1 | undefined;
@@ -1,5 +1,5 @@
1
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
- import type { H3Event } from 'nitro/h3';
2
+ import type { H3Event } from 'h3';
3
3
  export type DefineServerRouteResult = Response | unknown;
4
4
  export interface ServerRouteHandler<TQuery = unknown, TBody = unknown, TResult = unknown> {
5
5
  (event: H3Event): Promise<Response>;
@@ -1,5 +1,5 @@
1
1
  import { Injector, type StaticProvider } from '@angular/core';
2
- import type { H3Event } from 'nitro/h3';
2
+ import type { H3Event } from 'h3';
3
3
  export interface DispatchResult {
4
4
  status: number;
5
5
  body: unknown;
@@ -1,5 +1,5 @@
1
1
  import type { Injector } from '@angular/core';
2
- import { type EventHandler, type H3Event } from 'nitro/h3';
2
+ import { type EventHandler, type H3Event } from 'h3';
3
3
  /**
4
4
  * The h3 request/response layer for the server-function dispatch route.
5
5
  *
@@ -1,5 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
- import type { H3Event } from 'nitro/h3';
2
+ import type { H3Event } from 'h3';
3
3
  type NodeContext = NonNullable<H3Event['node']>;
4
4
  type NodeRuntimeContext = NodeContext & {
5
5
  req: IncomingMessage;
@@ -8,7 +8,8 @@ type NodeRuntimeContext = NodeContext & {
8
8
  /**
9
9
  * Dispatch provides the Node request and response through `REQUEST` and
10
10
  * `RESPONSE`, which are typed as Node primitives, so server functions only run
11
- * on a Node runtime. h3 leaves `node` undefined on other runtimes.
11
+ * on a Node runtime. h3 leaves `node` undefined on other runtimes. Calls made
12
+ * in-process while rendering may have no response.
12
13
  */
13
14
  export declare function assertNodeContext(event: Pick<H3Event, 'node'>): NodeRuntimeContext;
14
15
  export {};
@@ -19,6 +19,7 @@ export declare function isLikelyBot(serverContext: ServerContext): boolean;
19
19
  * rule. The platform plugin translates that rule into an `x-analog-no-streaming`
20
20
  * response header (mirroring how `ssr: false` becomes `x-analog-no-ssr`); when
21
21
  * present, `renderStream` produces the buffered `render()` output for this
22
- * route instead of streaming.
22
+ * route instead of streaming. On Nitro v3, which renders without a Node
23
+ * response, the header is forwarded on the request instead.
23
24
  */
24
25
  export declare function streamingDisabledByRoute(serverContext: ServerContext): boolean;
@@ -21,10 +21,8 @@ export { injectServerFn, injectServerFnMutation, provideServerFnClient, ServerFn
21
21
  export { createServerFnRef, type ServerFnRefConfig, } from './lib/server-fn/server-fn-ref';
22
22
  export { SERVER_FN_DISPATCHER, type ServerFnDispatcher, } from './lib/server-fn/dispatcher';
23
23
  export type { ServerFn, ServerFnConfig, ServerFnContext, ServerFnDef, ServerFnHandler, ServerFnMethod, StandardSchemaV1, } from './lib/server-fn/types';
24
- export type { AnalogRouteTable, AnalogRoutePath, RoutePathOptions, RoutePathArgs, RoutePathOptionsBase, RouteParamsOutput, RouteQueryOutput, RouteLinkResult, } from './lib/route-path';
25
- export { routePath } from './lib/route-path';
24
+ export { toRoute } from './lib/to-route';
25
+ export { LinkTo, type LinkToInput } from './lib/link-to.directive';
26
+ export type { AnalogRouteTable, AnalogRoutePath, RouteDataOutput, RouteLoadOutput, RoutePathOptions, RouteResourcesOutput, } from './lib/to-route';
26
27
  export { injectNavigate } from './lib/inject-navigate';
27
- export { withTypedRouter, withRouteContext, withLoaderCaching, EXPERIMENTAL_TYPED_ROUTER, EXPERIMENTAL_ROUTE_CONTEXT, EXPERIMENTAL_LOADER_CACHE, } from './lib/experimental';
28
- export type { TypedRouterOptions, LoaderCacheOptions, } from './lib/experimental';
29
- export { injectParams, injectQuery } from './lib/inject-typed-params';
30
- export { injectRouteContext } from './lib/inject-route-context';
28
+ export { injectParams, injectQuery, injectResources, injectRouteData, injectRouteResources, } from './lib/inject-typed-params';
@@ -1,7 +1,12 @@
1
1
  import { Injector } from '@angular/core';
2
2
  import { Observable } from 'rxjs';
3
3
  import { LoadDataResult, PageServerLoad } from './route-types';
4
- export declare function injectLoad<T extends (pageServerLoad: PageServerLoad) => Promise<unknown>>(options?: {
4
+ import type { AnalogRouteWithLoad, RouteLoadOutput } from './to-route';
5
+ /** Reads the result of the page's server `load` function, typed by route path. */
6
+ export declare function injectLoad<P extends AnalogRouteWithLoad>(path: P, options?: {
7
+ injector?: Injector;
8
+ }): Observable<RouteLoadOutput<P>>;
9
+ export declare function injectLoad<T extends (pageServerLoad: PageServerLoad) => Promise<any>>(options?: {
5
10
  injector?: Injector;
6
11
  }): Observable<Awaited<ReturnType<T>>>;
7
12
  export declare function injectLoadData<T extends (pageServerLoad: PageServerLoad) => Promise<unknown>>(options?: {
@@ -1,9 +1,20 @@
1
- import { type NavigationBehaviorOptions } from '@angular/router';
2
- import type { AnalogRoutePath, RoutePathArgs } from './route-path';
3
- type NavigateWithExtrasArgs<P extends AnalogRoutePath> = RoutePathArgs<P> extends [options?: infer Options] ? [extras: NavigationBehaviorOptions] | [options: Options | undefined, extras: NavigationBehaviorOptions] : [options: RoutePathArgs<P>[0], extras: NavigationBehaviorOptions];
1
+ import { Injector } from '@angular/core';
2
+ import { type NavigationBehaviorOptions, type UrlCreationOptions } from '@angular/router';
3
+ import type { AnalogRoutePath, ResolveRoutePath, RouteParamsOutput, RoutePathArgs, RouteQueryOutput, ScopedRoutePathOptions, ScopedRouteTarget } from './to-route';
4
+ /** Angular navigation extras; `query` and `hash` replace `queryParams` and `fragment`. */
5
+ type NavigateExtras = NavigationBehaviorOptions & Pick<UrlCreationOptions, 'queryParamsHandling' | 'preserveFragment'>;
6
+ type WithExtrasArgs<Args extends [options?: unknown]> = [] extends Args ? [extras: NavigateExtras] | [options: Args[0] | undefined, extras: NavigateExtras] : [options: Args[0], extras: NavigateExtras];
4
7
  type TypedNavigate = {
5
8
  <P extends AnalogRoutePath>(path: P, ...args: RoutePathArgs<P>): Promise<boolean>;
6
- <P extends AnalogRoutePath>(path: P, ...args: NavigateWithExtrasArgs<P>): Promise<boolean>;
9
+ <P extends AnalogRoutePath>(path: P, ...args: WithExtrasArgs<RoutePathArgs<P>>): Promise<boolean>;
10
+ };
11
+ type WithUpdaters<From extends string, O> = {
12
+ [K in keyof O]: K extends 'params' ? O[K] | ((prev: RouteParamsOutput<From>) => Exclude<O[K], undefined>) : K extends 'query' ? O[K] | ((prev: RouteQueryOutput<From>) => Exclude<O[K], undefined>) : O[K];
13
+ };
14
+ type ScopedNavigateArgs<From extends string, T extends string> = WithUpdaters<From, ScopedRoutePathOptions<From, ResolveRoutePath<From, T>>> extends infer O ? Record<never, never> extends O ? [options?: O] : [options: O] : never;
15
+ type ScopedNavigate<From extends AnalogRoutePath> = {
16
+ <T extends ScopedRouteTarget<From>>(target: T, ...args: ScopedNavigateArgs<From, T>): Promise<boolean>;
17
+ <T extends ScopedRouteTarget<From>>(target: T, ...args: WithExtrasArgs<ScopedNavigateArgs<From, T>>): Promise<boolean>;
7
18
  };
8
19
  /**
9
20
  * Injects a typed navigate function.
@@ -13,11 +24,33 @@ type TypedNavigate = {
13
24
  * const navigate = injectNavigate();
14
25
  *
15
26
  * navigate('/users/[id]', { params: { id: '42' } }); // ✅
16
- * navigate('/users/[id]', { params: { id: 42 } }); // ❌ type error
27
+ * navigate('/users/[id]', { params: { id: 42 } }); // ✅
17
28
  *
18
29
  * // With navigation extras
19
30
  * navigate('/users/[id]', { params: { id: '42' } }, { replaceUrl: true });
31
+ * navigate('/search', { query: { page: 2 } }, { queryParamsHandling: 'merge' });
20
32
  * ```
21
33
  */
22
34
  export declare function injectNavigate(): TypedNavigate;
35
+ /**
36
+ * Injects a navigate function scoped to the current route, `from`.
37
+ *
38
+ * Targets may be relative (`.`, `./child`, `..`, `../sibling`). Params in the
39
+ * leading segments the target shares with `from` default to current values.
40
+ * `params` and `query` may be functions of the current values.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * // In the component for /users/[id]
45
+ * const navigate = injectNavigate('/users/[id]');
46
+ *
47
+ * navigate('./posts'); // /users/42/posts
48
+ * navigate('.', { params: { id: 43 } }); // /users/43
49
+ * navigate('..'); // /users
50
+ * navigate('.', { params: (prev) => ({ id: Number(prev.id) + 1 }) });
51
+ * ```
52
+ */
53
+ export declare function injectNavigate<From extends AnalogRoutePath>(from: From, options?: {
54
+ injector?: Injector;
55
+ }): ScopedNavigate<From>;
23
56
  export {};
@@ -1,63 +1,33 @@
1
1
  import { Injector, Signal } from '@angular/core';
2
- import type { AnalogRoutePath, RouteParamsOutput, RouteQueryOutput } from './route-path';
2
+ import { ActivatedRoute } from '@angular/router';
3
+ import { Observable } from 'rxjs';
4
+ import type { AnalogRoutePath, RouteDataOutput, RouteParamsOutput, RouteQueryOutput, RouteResourcesOutput } from './to-route';
5
+ /** Internal: params for `route` and its ancestors, with catch-alls as arrays. */
6
+ export declare function observeRouteParams(route: ActivatedRoute, routePath: string): Observable<Record<string, unknown>>;
7
+ type InjectOptions = {
8
+ injector?: Injector;
9
+ };
10
+ /** Read raw route params; catch-all segments are returned as arrays. */
11
+ export declare function injectParams<P extends AnalogRoutePath>(from: P, options?: InjectOptions): Signal<RouteParamsOutput<P>>;
12
+ /** Read untyped route params. Catch-all segments require a route path. */
13
+ export declare function injectParams(options?: InjectOptions): Signal<Record<string, string | undefined>>;
14
+ /** Read raw query params as a signal. No schema coercion is performed. */
15
+ export declare function injectQuery<P extends AnalogRoutePath>(from: P, options?: InjectOptions): Signal<RouteQueryOutput<P>>;
16
+ /** Read raw query params as a signal. */
17
+ export declare function injectQuery(options?: InjectOptions): Signal<Record<string, string | string[] | undefined>>;
3
18
  /**
4
- * Injects typed route params as a signal, constrained by the route table.
5
- *
6
- * Inspired by TanStack Router's `useParams({ from: '/users/$userId' })`
7
- * pattern where the `from` parameter narrows the return type to only
8
- * the params defined for that route.
9
- *
10
- * The `from` parameter is used purely for TypeScript type inference —
11
- * at runtime, params are read from the current `ActivatedRoute`. This
12
- * means it works correctly when used inside a component rendered by
13
- * the specified route.
14
- *
15
- * When `withTypedRouter({ strictRouteParams: true })` is configured,
16
- * a dev-mode assertion checks that the expected params from `from`
17
- * exist in the active route and warns on mismatch.
18
- *
19
- * @example
20
- * ```ts
21
- * // In a component rendered at /users/[id]
22
- * const params = injectParams('/users/[id]');
23
- * // params() → { id: string }
24
- *
25
- * // With schema validation output types
26
- * const params = injectParams('/products/[slug]');
27
- * // params() → validated output type from routeParamsSchema
28
- * ```
29
- *
30
- * @experimental
19
+ * Read route data as a signal: static `routeMeta.data` and `routeMeta.resolve`
20
+ * results from the page and its layouts, and the page's server `load` result
21
+ * under `load`.
31
22
  */
32
- export declare function injectParams<P extends AnalogRoutePath>(_from: P, options?: {
33
- injector?: Injector;
34
- }): Signal<RouteParamsOutput<P>>;
23
+ export declare function injectRouteData<P extends AnalogRoutePath>(from: P, options?: InjectOptions): Signal<RouteDataOutput<P>>;
24
+ /** Read untyped route data as a signal. */
25
+ export declare function injectRouteData(options?: InjectOptions): Signal<Record<string, unknown>>;
35
26
  /**
36
- * Injects typed route query params as a signal, constrained by the
37
- * route table.
38
- *
39
- * Inspired by TanStack Router's `useSearch({ from: '/issues' })` pattern
40
- * where search params are validated and typed per-route via
41
- * `validateSearch` schemas.
42
- *
43
- * In Analog, the typing comes from `routeQuerySchema` exports that are
44
- * detected at build time and recorded in the generated route table.
45
- *
46
- * The `from` parameter is used purely for TypeScript type inference.
47
- * When `withTypedRouter({ strictRouteParams: true })` is configured,
48
- * a dev-mode assertion checks that the expected params from `from`
49
- * exist in the active route and warns on mismatch.
50
- *
51
- * @example
52
- * ```ts
53
- * // In a component rendered at /issues
54
- * // (where routeQuerySchema validates { page: number, status: string })
55
- * const query = injectQuery('/issues');
56
- * // query() → { page: number; status: string }
57
- * ```
58
- *
59
- * @experimental
27
+ * Access route resources: returns resources defined on the route and its
28
+ * ancestor layouts via `routeMeta.resources`. Requires `withRouterResources()`.
60
29
  */
61
- export declare function injectQuery<P extends AnalogRoutePath>(_from: P, options?: {
62
- injector?: Injector;
63
- }): Signal<RouteQueryOutput<P>>;
30
+ export declare function injectResources<P extends AnalogRoutePath>(from: P, options?: InjectOptions): RouteResourcesOutput<P>;
31
+ /** Access untyped route resources. */
32
+ export declare function injectResources(options?: InjectOptions): RouteResourcesOutput<string>;
33
+ export { injectResources as injectRouteResources };
@@ -0,0 +1,38 @@
1
+ import { InputSignal, OnChanges, OnDestroy } from '@angular/core';
2
+ import { AnalogRoutePath, ResolveRoutePath, RouteParamsOutput, RoutePathOptions, ScopedRoutePathArgs, ScopedRoutePathOptions, ScopedRouteTarget } from './to-route';
3
+ import * as i0 from "@angular/core";
4
+ import * as i1 from "@angular/router";
5
+ type LinkToDestination = {
6
+ [P in AnalogRoutePath]: {
7
+ path: P;
8
+ } & RoutePathOptions<P>;
9
+ }[AnalogRoutePath];
10
+ type StaticRoutePath = {
11
+ [P in AnalogRoutePath]: RouteParamsOutput<P> extends Record<string, never> ? P : never;
12
+ }[AnalogRoutePath];
13
+ type ScopedDestination<From extends AnalogRoutePath> = {
14
+ [T in ScopedRouteTarget<From>]: {
15
+ path: T;
16
+ } & ScopedRoutePathOptions<From, ResolveRoutePath<From, T>>;
17
+ }[ScopedRouteTarget<From>];
18
+ type ScopedStaticTarget<From extends AnalogRoutePath> = {
19
+ [T in ScopedRouteTarget<From>]: [] extends ScopedRoutePathArgs<From, T> ? T : never;
20
+ }[ScopedRouteTarget<From>];
21
+ /** Destinations accepted by `[linkTo]`, relative to `From` when provided. */
22
+ export type LinkToInput<From = undefined> = (unknown extends From ? StaticRoutePath | LinkToDestination : From extends AnalogRoutePath ? ScopedStaticTarget<From> | ScopedDestination<From> : StaticRoutePath | LinkToDestination) | null | undefined;
23
+ export declare class LinkTo<From = undefined> implements OnChanges, OnDestroy {
24
+ readonly linkTo: InputSignal<LinkToInput<From>>;
25
+ /** The current route's path. Enables relative destinations and param inheritance. */
26
+ readonly from: InputSignal<(From & AnalogRoutePath) | undefined>;
27
+ private readonly routerLink;
28
+ private readonly route;
29
+ private currentParams;
30
+ private paramsFrom?;
31
+ private paramsSubscription?;
32
+ ngOnChanges(): void;
33
+ ngOnDestroy(): void;
34
+ private update;
35
+ static ɵfac: i0.ɵɵFactoryDeclaration<LinkTo<any>, never>;
36
+ static ɵdir: i0.ɵɵDirectiveDeclaration<LinkTo<any>, "[linkTo]", never, { "linkTo": { "alias": "linkTo"; "required": true; "isSignal": true; }; "from": { "alias": "from"; "required": false; "isSignal": true; }; }, {}, never, never, true, [{ directive: typeof i1.RouterLink; inputs: { "target": "target"; "queryParamsHandling": "queryParamsHandling"; "preserveFragment": "preserveFragment"; "skipLocationChange": "skipLocationChange"; "replaceUrl": "replaceUrl"; "state": "state"; }; outputs: {}; }]>;
37
+ }
38
+ export {};
@@ -1,4 +1,4 @@
1
- import type { H3Event, H3EventContext } from 'nitro/h3';
1
+ import type { H3Event, H3EventContext } from 'h3';
2
2
  import type { $Fetch } from 'ofetch';
3
3
  export type NodeContext = NonNullable<H3Event['node']>;
4
4
  export type PageServerLoad = {