From 0683b032db3b827df9478882e62600086828af62 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Mon, 16 Nov 2026 07:13:52 +0800 Subject: [PATCH 1/3] Preserve tuple types in typed fetch responses. --- docs/guide/type-safety.md | 23 ++- packages/void/src/codegen/route-types.ts | 20 +- .../route-response-types-typecheck.test.ts | 172 ++++++++++++++++++ .../unit/route-type-extraction.typecheck.ts | 27 +-- 4 files changed, 206 insertions(+), 36 deletions(-) create mode 100644 packages/void/test/integration/route-response-types-typecheck.test.ts diff --git a/docs/guide/type-safety.md b/docs/guide/type-safety.md index 33f814b9e..c66e33f3e 100644 --- a/docs/guide/type-safety.md +++ b/docs/guide/type-safety.md @@ -439,15 +439,20 @@ The dev server keeps route types up to date. After changing `routing.typedRoutes ## Serialization -The client types reflect JSON serialization through `Serialize`: - -| Source type | Serialized type | -| --------------------------------- | ------------------------------------------------------ | -| `string`, `number`, `boolean` | unchanged | -| `Date` | `string` | -| `Response` | excluded (passed through at runtime) | -| `bigint`, `Function`, `undefined` | excluded | -| `Array` / `{ key: T }` | recursively serialized (function-valued keys stripped) | +The typed fetch client reflects JSON serialization: + +| Source type or value | Client type or behavior | +| --------------------------------------------------- | --------------------------------------------------------------- | +| `string`, `number`, `boolean`, `null` | unchanged | +| `Date` | `string` | +| Arrays and tuples, including readonly types | recursively serialized, preserving tuple shape and readonly | +| `undefined`, functions, or symbols in an array | `null` | +| `undefined`, functions, or symbols as object values | property omitted | +| Symbol-keyed object properties | omitted | +| `Response` | excluded from the inferred JSON type; passed through at runtime | +| `bigint` | unsupported by JSON | + +Object properties whose values may be omitted become optional in the client type. For example, a handler returning `{ label: string | undefined }` produces `{ label?: string }`. ## Context Variables diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index 682b8b897..489f91281 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -88,15 +88,27 @@ export function generateRouteTypes( lines.push(' >["output"];'); lines.push('}'); lines.push(''); + // JSON keeps invalid array positions as null, but omits the same values in objects. + // Find optional object keys before Serialize removes their omitted-value union members. + lines.push('type JsonOmitted = undefined | Function | symbol;'); + lines.push('type SerializeArrayElement = T extends JsonOmitted ? null : Serialize;'); + lines.push('type JsonOptionalKeys = {'); + lines.push(' [K in keyof T]-?: Extract extends never ? never : K;'); + lines.push('}[keyof T];'); + lines.push('type SerializeObject = {'); + lines.push( + ' [K in keyof T as K extends symbol ? never : T[K] extends JsonOmitted ? never : K]: Serialize;', + ); + lines.push('};'); + lines.push(''); lines.push('type Serialize ='); lines.push(' T extends Response ? never :'); lines.push(' T extends Date ? string :'); lines.push(' T extends bigint ? never :'); - lines.push(' T extends Function ? never :'); - lines.push(' T extends undefined ? never :'); - lines.push(' T extends Array ? Array> :'); + lines.push(' T extends JsonOmitted ? never :'); + lines.push(' T extends readonly unknown[] ? { [K in keyof T]: SerializeArrayElement } :'); lines.push( - ' T extends object ? { [K in keyof T as T[K] extends Function ? never : K]: Serialize } :', + ' T extends object ? SerializeObject> & Partial>>> :', ); lines.push(' T;'); lines.push(''); diff --git a/packages/void/test/integration/route-response-types-typecheck.test.ts b/packages/void/test/integration/route-response-types-typecheck.test.ts new file mode 100644 index 000000000..8a3c00a52 --- /dev/null +++ b/packages/void/test/integration/route-response-types-typecheck.test.ts @@ -0,0 +1,172 @@ +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { expect, it } from 'vite-plus/test'; +import { generateRouteTypes } from '../../src/codegen/route-types.ts'; + +it('preserves tuples and JSON omissions in generated typed fetch responses', () => { + const root = mkdtempSync(join(tmpdir(), 'void-route-response-types-')); + const voidDist = join(import.meta.dirname, '..', '..', 'dist'); + const { dts } = generateRouteTypes( + { + routes: [ + { + pattern: '/api/serialization', + methods: ['GET', 'POST'], + params: [], + catchAll: false, + env: null, + filePath: 'api/serialization.ts', + }, + ], + middleware: [], + jobs: [], + queues: [], + pages: { pages: [], layouts: [], namedLayouts: [] }, + }, + join(root, 'routes'), + join(root, '.void'), + ); + const files = { + 'package.json': JSON.stringify({ type: 'module' }), + 'tsconfig.json': JSON.stringify({ + compilerOptions: { + target: 'ES2022', + module: 'NodeNext', + moduleResolution: 'NodeNext', + lib: ['ES2022', 'DOM'], + types: [], + strict: true, + exactOptionalPropertyTypes: true, + noEmit: true, + skipLibCheck: true, + allowImportingTsExtensions: true, + paths: { + void: [join(voidDist, 'index.d.mts')], + 'void/client': [join(voidDist, 'runtime/client.d.mts')], + 'void/routes': [join(root, '.void/routes.d.ts')], + }, + }, + files: ['.void/routes.d.ts', 'check.ts'], + }), + '.void/routes.d.ts': dts, + 'routes/api/serialization.ts': ` +import { defineHandler } from 'void'; + +declare const hidden: unique symbol; +declare const payload: { + pairs: [number, number][]; + readonlyTuple: readonly [string, Date]; + empty: []; + readonlyEmpty: readonly []; + optionalTuple: [label: string, timestamp?: Date]; + restTuple: [number, ...Date[]]; + readonlyRestTuple: readonly [string, ...Date[]]; + invalidTuple: [number, undefined, () => void, symbol, string | undefined]; + invalidArray: Array void) | symbol>; + dates: Date[]; + readonlyDates: readonly Date[]; + nested: Array<{ tuple: readonly [Date, { value: string | undefined }] }>; + object: { + readonly required: string; + optional?: number; + maybe: string | undefined; + callback: () => void; + optionalCallback?: () => void; + mixed: string | (() => void); + symbolValue: symbol; + symbolUnion: number | symbol; + omitted: undefined; + [hidden]: number; + nested: { value: Date | undefined; explicitNull: null }; + }; + union: { kind: 'a'; value: string | undefined } | { kind: 'b'; value: number }; + primitives: [string, number, boolean, null]; + neverArray: never[]; +}; + +export const GET = defineHandler(async () => payload); + +declare const body: { + readonly '~standard': { + readonly version: 1; + readonly vendor: string; + readonly validate: (value: unknown) => { value: { name: string } }; + readonly types?: { readonly input: { name: string }; readonly output: { name: string } }; + }; +}; +export const POST = defineHandler.withValidator({ body })((_c, { body }) => ({ + greeting: body.name, + pair: [body.name, new Date()] as [string, Date], +})); +`, + 'check.ts': ` +import { fetch } from 'void/client'; + +type Equal = + (() => T extends X ? 1 : 2) extends (() => T extends Y ? 1 : 2) ? true : false; +declare function assert(): void; + +const result = await fetch('/api/serialization'); +assert>(); +assert>(); +assert>(); +assert>(); +assert>(); +assert>(); +assert>(); +assert>(); +assert>>(); +assert>(); +assert>(); +assert>>(); +assert>(); +assert>(); +assert>(); +assert>(); + +const pairs: [number, number][] = result.pairs; +// @ts-expect-error tuples retain their length +pairs[0][2]; +// @ts-expect-error serialized Dates are strings +result.dates[0].getTime(); +// @ts-expect-error function properties are omitted +result.object.callback; +// @ts-expect-error properties that can be omitted require a check +result.object.maybe.toUpperCase(); + +const posted = await fetch('/api/serialization', { method: 'POST', body: { name: 'Alice' } }); +assert>(); +// @ts-expect-error validators still constrain request bodies +await fetch('/api/serialization', { method: 'POST', body: { name: 42 } }); +`, + }; + + try { + for (const [path, content] of Object.entries(files)) { + mkdirSync(dirname(join(root, path)), { recursive: true }); + writeFileSync(join(root, path), content); + } + const tsc = join( + dirname(createRequire(import.meta.url).resolve('typescript/package.json')), + 'bin/tsc', + ); + const result = spawnSync(process.execPath, [tsc, '-p', join(root, 'tsconfig.json')], { + encoding: 'utf8', + timeout: 30_000, + }); + expect(result.error).toBeUndefined(); + expect(result.status, result.stdout + result.stderr).toBe(0); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/packages/void/test/unit/route-type-extraction.typecheck.ts b/packages/void/test/unit/route-type-extraction.typecheck.ts index 8b8bbfc47..a6332ed07 100644 --- a/packages/void/test/unit/route-type-extraction.typecheck.ts +++ b/packages/void/test/unit/route-type-extraction.typecheck.ts @@ -5,26 +5,7 @@ import { z } from 'zod'; import { defineHandler, defineMiddleware } from '../../src/runtime/handler.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; -/** - * Copies of the helpers generateRouteTypes() emits into .void/routes.d.ts, applied to - * `typeof handler` in place of `typeof import("../routes/...")["METHOD"]`. - */ -type Serialize = T extends Response - ? never - : T extends Date - ? string - : T extends bigint - ? never - : T extends Function - ? never - : T extends undefined - ? never - : T extends Array - ? Array> - : T extends object - ? { [K in keyof T as T[K] extends Function ? never : K]: Serialize } - : T; - +/** Input extraction helper emitted by generateRouteTypes(). */ type ExtractInput = { [K in keyof V as V[K] extends StandardSchemaV1 ? K : never]: V[K] extends StandardSchemaV1 ? StandardSchemaV1.InferInput @@ -33,12 +14,12 @@ type ExtractInput = { // ─── Output extraction ────────────────────────────────────────────────────── -describe('Serialize>', () => { +describe('Awaited', () => { it('extracts plain object return type', () => { const handler = defineHandler((_c) => { return { name: 'Alice' as string, age: 30 as number }; }); - type Output = Serialize>; + type Output = Awaited<(typeof handler)['__output']>; expectTypeOf().toEqualTypeOf<{ name: string; age: number }>(); @@ -52,7 +33,7 @@ describe('Serialize>', () => { })((_c, { body }) => { return { greeting: `Hello ${body.name}` as string }; }); - type Output = Serialize>; + type Output = Awaited<(typeof handler)['__output']>; expectTypeOf().toEqualTypeOf<{ greeting: string }>(); }); From 27a0fdf029ecb1d28d15bea88dba742fd6a0c5b9 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Mon, 16 Nov 2026 08:56:38 +0900 Subject: [PATCH 2/3] Preserve array methods in branded fetch responses. --- packages/void/src/codegen/route-types.ts | 10 ++++++- .../route-response-types-typecheck.test.ts | 29 ++++++++++++++++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index 489f91281..2d0ef798f 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -92,6 +92,14 @@ export function generateRouteTypes( // Find optional object keys before Serialize removes their omitted-value union members. lines.push('type JsonOmitted = undefined | Function | symbol;'); lines.push('type SerializeArrayElement = T extends JsonOmitted ? null : Serialize;'); + // A homomorphic map preserves ordinary arrays and tuples, but maps methods too + // on array intersections (e.g. Zod brands). Rebuild those as JSON arrays. + lines.push('type SerializeArray ='); + lines.push(' { [K in keyof T]: SerializeArrayElement } extends infer A'); + lines.push(' ? A extends readonly unknown[] ? A'); + lines.push(' : T extends unknown[] ? Array>'); + lines.push(' : ReadonlyArray>'); + lines.push(' : never;'); lines.push('type JsonOptionalKeys = {'); lines.push(' [K in keyof T]-?: Extract extends never ? never : K;'); lines.push('}[keyof T];'); @@ -106,7 +114,7 @@ export function generateRouteTypes( lines.push(' T extends Date ? string :'); lines.push(' T extends bigint ? never :'); lines.push(' T extends JsonOmitted ? never :'); - lines.push(' T extends readonly unknown[] ? { [K in keyof T]: SerializeArrayElement } :'); + lines.push(' T extends readonly unknown[] ? SerializeArray :'); lines.push( ' T extends object ? SerializeObject> & Partial>>> :', ); diff --git a/packages/void/test/integration/route-response-types-typecheck.test.ts b/packages/void/test/integration/route-response-types-typecheck.test.ts index 8a3c00a52..740d15492 100644 --- a/packages/void/test/integration/route-response-types-typecheck.test.ts +++ b/packages/void/test/integration/route-response-types-typecheck.test.ts @@ -47,6 +47,12 @@ it('preserves tuples and JSON omissions in generated typed fetch responses', () void: [join(voidDist, 'index.d.mts')], 'void/client': [join(voidDist, 'runtime/client.d.mts')], 'void/routes': [join(root, '.void/routes.d.ts')], + zod: [ + join( + dirname(createRequire(import.meta.url).resolve('zod/package.json')), + 'index.d.cts', + ), + ], }, }, files: ['.void/routes.d.ts', 'check.ts'], @@ -54,6 +60,11 @@ it('preserves tuples and JSON omissions in generated typed fetch responses', () '.void/routes.d.ts': dts, 'routes/api/serialization.ts': ` import { defineHandler } from 'void'; +import { z } from 'zod'; + +const names = z.array(z.string()).brand<'Names'>().parse(['Alice']); +const readonlyNames = z.array(z.string()).readonly().brand<'Names'>().parse(['Alice']); +const datedPair = z.tuple([z.string(), z.date()]).brand<'DatedPair'>().parse(['Alice', new Date()]); declare const hidden: unique symbol; declare const payload: { @@ -87,7 +98,13 @@ declare const payload: { neverArray: never[]; }; -export const GET = defineHandler(async () => payload); +export const GET = defineHandler(async () => ({ + ...payload, + names, + readonlyNames, + datedPair, + decorated: Object.assign([new Date()], { total: 1 }), +})); declare const body: { readonly '~standard': { @@ -133,6 +150,16 @@ assert>(); assert>(); assert>(); +assert>(); +assert>(); +assert>(); +assert>(); +const names: string[] = result.names.map((name) => name.toUpperCase()); +const dates: string[] = result.decorated.map((date) => date.toUpperCase()); +// @ts-expect-error readonly arrays retain readonly methods +result.readonlyNames.push('Bob'); +// @ts-expect-error JSON omits additional array properties +result.decorated.total; const pairs: [number, number][] = result.pairs; // @ts-expect-error tuples retain their length From dc5e3a604f2dcf0a7e0b55256853287148659544 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Mon, 16 Nov 2026 09:02:22 +0900 Subject: [PATCH 3/3] Remove redundant type helper comment. --- packages/void/test/unit/route-type-extraction.typecheck.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/void/test/unit/route-type-extraction.typecheck.ts b/packages/void/test/unit/route-type-extraction.typecheck.ts index a6332ed07..ec62a72f1 100644 --- a/packages/void/test/unit/route-type-extraction.typecheck.ts +++ b/packages/void/test/unit/route-type-extraction.typecheck.ts @@ -5,7 +5,6 @@ import { z } from 'zod'; import { defineHandler, defineMiddleware } from '../../src/runtime/handler.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; -/** Input extraction helper emitted by generateRouteTypes(). */ type ExtractInput = { [K in keyof V as V[K] extends StandardSchemaV1 ? K : never]: V[K] extends StandardSchemaV1 ? StandardSchemaV1.InferInput