|
| 1 | +import { spawnSync } from 'node:child_process'; |
| 2 | +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; |
| 3 | +import { createRequire } from 'node:module'; |
| 4 | +import { tmpdir } from 'node:os'; |
| 5 | +import { dirname, join } from 'node:path'; |
| 6 | +import { expect, it } from 'vite-plus/test'; |
| 7 | +import { generateRouteTypes } from '../../src/codegen/route-types.ts'; |
| 8 | + |
| 9 | +it('preserves tuples and JSON omissions in generated typed fetch responses', () => { |
| 10 | + const root = mkdtempSync(join(tmpdir(), 'void-route-response-types-')); |
| 11 | + const voidDist = join(import.meta.dirname, '..', '..', 'dist'); |
| 12 | + const { dts } = generateRouteTypes( |
| 13 | + { |
| 14 | + routes: [ |
| 15 | + { |
| 16 | + pattern: '/api/serialization', |
| 17 | + methods: ['GET', 'POST'], |
| 18 | + params: [], |
| 19 | + catchAll: false, |
| 20 | + env: null, |
| 21 | + filePath: 'api/serialization.ts', |
| 22 | + }, |
| 23 | + ], |
| 24 | + middleware: [], |
| 25 | + jobs: [], |
| 26 | + queues: [], |
| 27 | + pages: { pages: [], layouts: [], namedLayouts: [] }, |
| 28 | + }, |
| 29 | + join(root, 'routes'), |
| 30 | + join(root, '.void'), |
| 31 | + ); |
| 32 | + const files = { |
| 33 | + 'package.json': JSON.stringify({ type: 'module' }), |
| 34 | + 'tsconfig.json': JSON.stringify({ |
| 35 | + compilerOptions: { |
| 36 | + target: 'ES2022', |
| 37 | + module: 'NodeNext', |
| 38 | + moduleResolution: 'NodeNext', |
| 39 | + lib: ['ES2022', 'DOM'], |
| 40 | + types: [], |
| 41 | + strict: true, |
| 42 | + exactOptionalPropertyTypes: true, |
| 43 | + noEmit: true, |
| 44 | + skipLibCheck: true, |
| 45 | + allowImportingTsExtensions: true, |
| 46 | + paths: { |
| 47 | + void: [join(voidDist, 'index.d.mts')], |
| 48 | + 'void/client': [join(voidDist, 'runtime/client.d.mts')], |
| 49 | + 'void/routes': [join(root, '.void/routes.d.ts')], |
| 50 | + zod: [ |
| 51 | + join( |
| 52 | + dirname(createRequire(import.meta.url).resolve('zod/package.json')), |
| 53 | + 'index.d.cts', |
| 54 | + ), |
| 55 | + ], |
| 56 | + }, |
| 57 | + }, |
| 58 | + files: ['.void/routes.d.ts', 'check.ts'], |
| 59 | + }), |
| 60 | + '.void/routes.d.ts': dts, |
| 61 | + 'routes/api/serialization.ts': ` |
| 62 | +import { defineHandler } from 'void'; |
| 63 | +import { z } from 'zod'; |
| 64 | +
|
| 65 | +const names = z.array(z.string()).brand<'Names'>().parse(['Alice']); |
| 66 | +const readonlyNames = z.array(z.string()).readonly().brand<'Names'>().parse(['Alice']); |
| 67 | +const datedPair = z.tuple([z.string(), z.date()]).brand<'DatedPair'>().parse(['Alice', new Date()]); |
| 68 | +
|
| 69 | +declare const hidden: unique symbol; |
| 70 | +declare const payload: { |
| 71 | + pairs: [number, number][]; |
| 72 | + readonlyTuple: readonly [string, Date]; |
| 73 | + empty: []; |
| 74 | + readonlyEmpty: readonly []; |
| 75 | + optionalTuple: [label: string, timestamp?: Date]; |
| 76 | + restTuple: [number, ...Date[]]; |
| 77 | + readonlyRestTuple: readonly [string, ...Date[]]; |
| 78 | + invalidTuple: [number, undefined, () => void, symbol, string | undefined]; |
| 79 | + invalidArray: Array<string | undefined | (() => void) | symbol>; |
| 80 | + dates: Date[]; |
| 81 | + readonlyDates: readonly Date[]; |
| 82 | + nested: Array<{ tuple: readonly [Date, { value: string | undefined }] }>; |
| 83 | + object: { |
| 84 | + readonly required: string; |
| 85 | + optional?: number; |
| 86 | + maybe: string | undefined; |
| 87 | + callback: () => void; |
| 88 | + optionalCallback?: () => void; |
| 89 | + mixed: string | (() => void); |
| 90 | + symbolValue: symbol; |
| 91 | + symbolUnion: number | symbol; |
| 92 | + omitted: undefined; |
| 93 | + [hidden]: number; |
| 94 | + nested: { value: Date | undefined; explicitNull: null }; |
| 95 | + }; |
| 96 | + union: { kind: 'a'; value: string | undefined } | { kind: 'b'; value: number }; |
| 97 | + primitives: [string, number, boolean, null]; |
| 98 | + neverArray: never[]; |
| 99 | +}; |
| 100 | +
|
| 101 | +export const GET = defineHandler(async () => ({ |
| 102 | + ...payload, |
| 103 | + names, |
| 104 | + readonlyNames, |
| 105 | + datedPair, |
| 106 | + decorated: Object.assign([new Date()], { total: 1 }), |
| 107 | +})); |
| 108 | +
|
| 109 | +declare const body: { |
| 110 | + readonly '~standard': { |
| 111 | + readonly version: 1; |
| 112 | + readonly vendor: string; |
| 113 | + readonly validate: (value: unknown) => { value: { name: string } }; |
| 114 | + readonly types?: { readonly input: { name: string }; readonly output: { name: string } }; |
| 115 | + }; |
| 116 | +}; |
| 117 | +export const POST = defineHandler.withValidator({ body })((_c, { body }) => ({ |
| 118 | + greeting: body.name, |
| 119 | + pair: [body.name, new Date()] as [string, Date], |
| 120 | +})); |
| 121 | +`, |
| 122 | + 'check.ts': ` |
| 123 | +import { fetch } from 'void/client'; |
| 124 | +
|
| 125 | +type Equal<X, Y> = |
| 126 | + (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false; |
| 127 | +declare function assert<T extends true>(): void; |
| 128 | +
|
| 129 | +const result = await fetch('/api/serialization'); |
| 130 | +assert<Equal<typeof result.pairs, [number, number][]>>(); |
| 131 | +assert<Equal<typeof result.readonlyTuple, readonly [string, string]>>(); |
| 132 | +assert<Equal<typeof result.empty, []>>(); |
| 133 | +assert<Equal<typeof result.readonlyEmpty, readonly []>>(); |
| 134 | +assert<Equal<typeof result.optionalTuple, [label: string, timestamp?: string | null]>>(); |
| 135 | +assert<Equal<typeof result.restTuple, [number, ...string[]]>>(); |
| 136 | +assert<Equal<typeof result.readonlyRestTuple, readonly [string, ...string[]]>>(); |
| 137 | +assert<Equal<typeof result.invalidTuple, [number, null, null, null, string | null]>>(); |
| 138 | +assert<Equal<typeof result.invalidArray, Array<string | null>>>(); |
| 139 | +assert<Equal<typeof result.dates, string[]>>(); |
| 140 | +assert<Equal<typeof result.readonlyDates, readonly string[]>>(); |
| 141 | +assert<Equal<typeof result.nested, Array<{ tuple: readonly [string, { value?: string }] }>>>(); |
| 142 | +assert<Equal<typeof result.object, { |
| 143 | + readonly required: string; |
| 144 | + optional?: number; |
| 145 | + maybe?: string; |
| 146 | + mixed?: string; |
| 147 | + symbolUnion?: number; |
| 148 | + nested: { value?: string; explicitNull: null }; |
| 149 | +}>>(); |
| 150 | +assert<Equal<typeof result.union, { kind: 'a'; value?: string } | { kind: 'b'; value: number }>>(); |
| 151 | +assert<Equal<typeof result.primitives, [string, number, boolean, null]>>(); |
| 152 | +assert<Equal<typeof result.neverArray, never[]>>(); |
| 153 | +assert<Equal<typeof result.names, string[]>>(); |
| 154 | +assert<Equal<typeof result.readonlyNames, readonly string[]>>(); |
| 155 | +assert<Equal<typeof result.datedPair, string[]>>(); |
| 156 | +assert<Equal<typeof result.decorated, string[]>>(); |
| 157 | +const names: string[] = result.names.map((name) => name.toUpperCase()); |
| 158 | +const dates: string[] = result.decorated.map((date) => date.toUpperCase()); |
| 159 | +// @ts-expect-error readonly arrays retain readonly methods |
| 160 | +result.readonlyNames.push('Bob'); |
| 161 | +// @ts-expect-error JSON omits additional array properties |
| 162 | +result.decorated.total; |
| 163 | +
|
| 164 | +const pairs: [number, number][] = result.pairs; |
| 165 | +// @ts-expect-error tuples retain their length |
| 166 | +pairs[0][2]; |
| 167 | +// @ts-expect-error serialized Dates are strings |
| 168 | +result.dates[0].getTime(); |
| 169 | +// @ts-expect-error function properties are omitted |
| 170 | +result.object.callback; |
| 171 | +// @ts-expect-error properties that can be omitted require a check |
| 172 | +result.object.maybe.toUpperCase(); |
| 173 | +
|
| 174 | +const posted = await fetch('/api/serialization', { method: 'POST', body: { name: 'Alice' } }); |
| 175 | +assert<Equal<typeof posted, { greeting: string; pair: [string, string] }>>(); |
| 176 | +// @ts-expect-error validators still constrain request bodies |
| 177 | +await fetch('/api/serialization', { method: 'POST', body: { name: 42 } }); |
| 178 | +`, |
| 179 | + }; |
| 180 | + |
| 181 | + try { |
| 182 | + for (const [path, content] of Object.entries(files)) { |
| 183 | + mkdirSync(dirname(join(root, path)), { recursive: true }); |
| 184 | + writeFileSync(join(root, path), content); |
| 185 | + } |
| 186 | + const tsc = join( |
| 187 | + dirname(createRequire(import.meta.url).resolve('typescript/package.json')), |
| 188 | + 'bin/tsc', |
| 189 | + ); |
| 190 | + const result = spawnSync(process.execPath, [tsc, '-p', join(root, 'tsconfig.json')], { |
| 191 | + encoding: 'utf8', |
| 192 | + timeout: 30_000, |
| 193 | + }); |
| 194 | + expect(result.error).toBeUndefined(); |
| 195 | + expect(result.status, result.stdout + result.stderr).toBe(0); |
| 196 | + } finally { |
| 197 | + rmSync(root, { recursive: true, force: true }); |
| 198 | + } |
| 199 | +}); |
0 commit comments