Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions docs/guide/type-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>`:

| Source type | Serialized type |
| --------------------------------- | ------------------------------------------------------ |
| `string`, `number`, `boolean` | unchanged |
| `Date` | `string` |
| `Response` | excluded (passed through at runtime) |
| `bigint`, `Function`, `undefined` | excluded |
| `Array<T>` / `{ 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

Expand Down
28 changes: 24 additions & 4 deletions packages/void/src/codegen/route-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,35 @@ 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> = T extends JsonOmitted ? null : Serialize<T>;');
// 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<T extends readonly unknown[]> =');
lines.push(' { [K in keyof T]: SerializeArrayElement<T[K]> } extends infer A');
lines.push(' ? A extends readonly unknown[] ? A');
lines.push(' : T extends unknown[] ? Array<SerializeArrayElement<T[number]>>');
lines.push(' : ReadonlyArray<SerializeArrayElement<T[number]>>');
lines.push(' : never;');
lines.push('type JsonOptionalKeys<T> = {');
lines.push(' [K in keyof T]-?: Extract<T[K], JsonOmitted> extends never ? never : K;');
lines.push('}[keyof T];');
lines.push('type SerializeObject<T> = {');
lines.push(
' [K in keyof T as K extends symbol ? never : T[K] extends JsonOmitted ? never : K]: Serialize<T[K]>;',
);
lines.push('};');
lines.push('');
lines.push('type Serialize<T> =');
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<infer U> ? Array<Serialize<U>> :');
lines.push(' T extends JsonOmitted ? never :');
lines.push(' T extends readonly unknown[] ? SerializeArray<T> :');
lines.push(
' T extends object ? { [K in keyof T as T[K] extends Function ? never : K]: Serialize<T[K]> } :',
' T extends object ? SerializeObject<Omit<T, JsonOptionalKeys<T>> & Partial<Pick<T, JsonOptionalKeys<T>>>> :',
);
lines.push(' T;');
lines.push('');
Expand Down
199 changes: 199 additions & 0 deletions packages/void/test/integration/route-response-types-typecheck.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
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')],
zod: [
join(
dirname(createRequire(import.meta.url).resolve('zod/package.json')),
'index.d.cts',
),
],
},
},
files: ['.void/routes.d.ts', 'check.ts'],
}),
'.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: {
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<string | undefined | (() => 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,
names,
readonlyNames,
datedPair,
decorated: Object.assign([new Date()], { total: 1 }),
}));

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<X, Y> =
(<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
declare function assert<T extends true>(): void;

const result = await fetch('/api/serialization');
assert<Equal<typeof result.pairs, [number, number][]>>();
assert<Equal<typeof result.readonlyTuple, readonly [string, string]>>();
assert<Equal<typeof result.empty, []>>();
assert<Equal<typeof result.readonlyEmpty, readonly []>>();
assert<Equal<typeof result.optionalTuple, [label: string, timestamp?: string | null]>>();
assert<Equal<typeof result.restTuple, [number, ...string[]]>>();
assert<Equal<typeof result.readonlyRestTuple, readonly [string, ...string[]]>>();
assert<Equal<typeof result.invalidTuple, [number, null, null, null, string | null]>>();
assert<Equal<typeof result.invalidArray, Array<string | null>>>();
assert<Equal<typeof result.dates, string[]>>();
assert<Equal<typeof result.readonlyDates, readonly string[]>>();
assert<Equal<typeof result.nested, Array<{ tuple: readonly [string, { value?: string }] }>>>();
assert<Equal<typeof result.object, {
readonly required: string;
optional?: number;
maybe?: string;
mixed?: string;
symbolUnion?: number;
nested: { value?: string; explicitNull: null };
}>>();
assert<Equal<typeof result.union, { kind: 'a'; value?: string } | { kind: 'b'; value: number }>>();
assert<Equal<typeof result.primitives, [string, number, boolean, null]>>();
assert<Equal<typeof result.neverArray, never[]>>();
assert<Equal<typeof result.names, string[]>>();
assert<Equal<typeof result.readonlyNames, readonly string[]>>();
assert<Equal<typeof result.datedPair, string[]>>();
assert<Equal<typeof result.decorated, string[]>>();
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
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<Equal<typeof posted, { greeting: string; pair: [string, string] }>>();
// @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 });
}
});
26 changes: 3 additions & 23 deletions packages/void/test/unit/route-type-extraction.typecheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,6 @@ 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> = T extends Response
? never
: T extends Date
? string
: T extends bigint
? never
: T extends Function
? never
: T extends undefined
? never
: T extends Array<infer U>
? Array<Serialize<U>>
: T extends object
? { [K in keyof T as T[K] extends Function ? never : K]: Serialize<T[K]> }
: T;

type ExtractInput<V> = {
[K in keyof V as V[K] extends StandardSchemaV1 ? K : never]: V[K] extends StandardSchemaV1
? StandardSchemaV1.InferInput<V[K]>
Expand All @@ -33,12 +13,12 @@ type ExtractInput<V> = {

// ─── Output extraction ──────────────────────────────────────────────────────

describe('Serialize<Awaited<handler.__output>>', () => {
describe('Awaited<handler.__output>', () => {
it('extracts plain object return type', () => {
const handler = defineHandler((_c) => {
return { name: 'Alice' as string, age: 30 as number };
});
type Output = Serialize<Awaited<(typeof handler)['__output']>>;
type Output = Awaited<(typeof handler)['__output']>;

expectTypeOf<Output>().toEqualTypeOf<{ name: string; age: number }>();

Expand All @@ -52,7 +32,7 @@ describe('Serialize<Awaited<handler.__output>>', () => {
})((_c, { body }) => {
return { greeting: `Hello ${body.name}` as string };
});
type Output = Serialize<Awaited<(typeof handler)['__output']>>;
type Output = Awaited<(typeof handler)['__output']>;

expectTypeOf<Output>().toEqualTypeOf<{ greeting: string }>();
});
Expand Down
Loading