diff --git a/docs/guide/type-safety.md b/docs/guide/type-safety.md index 4f3de869e..824bf4829 100644 --- a/docs/guide/type-safety.md +++ b/docs/guide/type-safety.md @@ -149,6 +149,8 @@ const url = routeUrl('/users/[id]', { TypeScript checks the route and required parameter names. Patterns follow your filenames: `pages/users/[id].tsx`, `.vue`, or `.svelte` uses `/users/[id]`. +Type errors identify unknown route patterns and missing or invalid parameters. + Parameters accept strings or numbers and are URL-encoded for you. Query values can be strings, numbers, booleans, or arrays. Arrays become repeated keys; `null` and `undefined` values are omitted. The same bracket patterns work with typed `fetch()`, WebSocket `connect()`, page actions, and `useParams()`. diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 9ab870aec..5503ee14a 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -173,6 +173,11 @@ Vite/CLI dependency graph. `void/remote` stays exported only for semver. Generated code imports `#self/remote`. Remove the subpath in the next major version. +Generated `.void/routes.d.ts` files import `void/_route-url-types`. Keep this +types-only export and its legacy `typesVersions` mapping stable across compatible +SDK releases, including when an app has not regenerated its declarations. +Removing or renaming it requires an explicit breaking-change migration plan. + Build output uses `.mjs` / `.d.mts` extensions (`vp pack` / tsdown default). ### Route Filename Parsing Rules diff --git a/packages/void/package.json b/packages/void/package.json index f3106e33e..8d26b8d7d 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -26,6 +26,13 @@ "sandbox.Dockerfile" ], "type": "module", + "typesVersions": { + "*": { + "_route-url-types": [ + "./dist/runtime/routing/route-url.d.mts" + ] + } + }, "imports": { "#self/_env": "./dist/runtime/env/runtime.mjs", "#self/email": "./dist/runtime/email/index.mjs", @@ -313,6 +320,9 @@ "require": "./dist/runtime/env/public.mjs" } }, + "./_route-url-types": { + "types": "./dist/runtime/routing/route-url.d.mts" + }, "./_env": { "types": "./dist/runtime/env/runtime.d.mts", "import": "./dist/runtime/env/runtime.mjs", diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index 7578b4ccf..433ccac01 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -139,71 +139,26 @@ export function generateRouteTypes( lines.push(' export interface WebSocketRouteMap {}'); lines.push(' export interface PageActionMap {}'); lines.push(''); - // Projects resolve void/routes to this generated declaration through their - // tsconfig paths, so keep the standalone helper's declarations here as well. - lines.push(' export type RoutePath = keyof RoutePathMap & string;'); - lines.push(' export type RouteQueryValue = string | number | boolean | null | undefined;'); - lines.push( - ' export type RouteQuery = Record>;', - ); - lines.push(' export type RouteOptions

= {'); - lines.push(' query?: RouteQuery;'); - lines.push(' hash?: string;'); - lines.push(' } & ([RoutePathMap[P]] extends [never]'); - lines.push(' ? { params?: never }'); - lines.push(' : { params: { [K in RoutePathMap[P] & string]: string | number } });'); - lines.push( - ' export type RouteDestination

= P extends RoutePath', - ); - lines.push(' ? { pathname: P } & RouteOptions

'); - lines.push(' : never;'); - lines.push( - ' type RouteUrlSegment = S extends `:${string}` | `[${string}]` | "*" ? string : S;', - ); - lines.push( - ' type CheckedRoutePath

= P extends `/${infer Segment}/${infer Rest}`', - ); - lines.push(' ? Rest extends ""'); - lines.push(' ? string extends RouteUrlSegment ? never : P'); - lines.push(' : P'); - lines.push(' : P extends `/${infer Segment}`'); - lines.push(' ? string extends RouteUrlSegment ? never : P'); - lines.push(' : P;'); - lines.push( - ' type RouteSegmentsUrl

= P extends `${infer Segment}/${infer Rest}`', - ); - lines.push(' ? `${RouteUrlSegment}/${RouteSegmentsUrl}`'); - lines.push(' : RouteUrlSegment

;'); - lines.push( - ' type RoutePatternUrl

= P extends `${infer Prefix}/${"*" | "[...]"}/`', - ); - lines.push(' ? `${RouteSegmentsUrl}/` | `${RouteSegmentsUrl}/${string}/`'); - lines.push(' : P extends `${infer Prefix}/${"*" | "[...]"}`'); - lines.push( - ' ? (Prefix extends "" ? "/" : RouteSegmentsUrl) | `${RouteSegmentsUrl}/${string}`', - ); - lines.push(' : RouteSegmentsUrl

;'); - lines.push(' type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string;'); + // A bare types-only entry follows the installed SDK through upgrades. + // void/routes would be circular because this file augments that entry. + const sdkRoutesModule = JSON.stringify('void/_route-url-types'); + for (const name of [ + 'RoutePath', + 'RouteQueryValue', + 'RouteQuery', + 'RouteUrl', + 'Href', + 'RouteUrlInput', + ]) { + lines.push(` export type ${name} = import(${sdkRoutesModule}).${name};`); + } lines.push( - ' type RoutePathUrl = RoutePatternUrl>;', + ` export type RouteOptions

= import(${sdkRoutesModule}).RouteOptions

;`, ); - lines.push(' type BuiltRouteUrl = string & { readonly __voidRouteUrl: true };'); - lines.push(' type TypedRoutes = RouteTypesConfig extends { typedRoutes: true } ? true : false;'); - lines.push(' export type RouteUrl = TypedRoutes extends true'); - lines.push(' ? BuiltRouteUrl | RoutePathUrl | `${RoutePathUrl}${"?" | "#"}${string}`'); - lines.push(' : string;'); - lines.push(' export type Href = TypedRoutes extends true'); lines.push( - ' ? RouteUrl | `${"?" | "#"}${string}` | `${"http://" | "https://" | "mailto:" | "tel:"}${string}`', + ` export type RouteDestination

= import(${sdkRoutesModule}).RouteDestination

;`, ); - lines.push(' : string;'); - lines.push(' export type RouteUrlInput = Href | URL | RouteDestination;'); - lines.push(' export function routeUrl

('); - lines.push(' path: P,'); - lines.push(' ...args: [RoutePathMap[NoInfer

]] extends [never]'); - lines.push(' ? [options?: RouteOptions

]'); - lines.push(' : [options: RouteOptions

]'); - lines.push(' ): RouteUrl;'); + lines.push(` export const routeUrl: typeof import(${sdkRoutesModule}).routeUrl;`); lines.push(''); lines.push(' export interface RouteTypesConfig {'); if (options.typedRoutes) { diff --git a/packages/void/src/runtime/routing/route-url.ts b/packages/void/src/runtime/routing/route-url.ts index 75c631804..fdb1b1041 100644 --- a/packages/void/src/runtime/routing/route-url.ts +++ b/packages/void/src/runtime/routing/route-url.ts @@ -1,4 +1,5 @@ import type { EncodedRoutePathMap, RoutePathMap, RouteTypesConfig } from 'void/routes'; +import type { DiagnosticKeyName, InvalidValueKeys, UrlTypeError } from './url-diagnostics.ts'; /** * Encode one path segment of a route param. `encodeURIComponent` keeps dots, and @@ -157,14 +158,123 @@ type UrlOptions = { hash?: string; }; +// Diagnostics describe invalid calls; the valid-call overload below remains +// independent so generic helpers and structural objects retain their contract. +type RouteUrlArgs

= [RoutePathMap[P]] extends [never] + ? [options?: RouteOptions

] + : [options: RouteOptions

]; +type MissingRouteParam

= P extends RoutePath + ? K extends RoutePathMap[P] + ? `Missing param ${K} for route ${P}. Pass it in { params: { ... } }.` + : never + : never; +// An index signature permits a key without guaranteeing that it is present. +type RequiredParamKeys = keyof { + [K in keyof Params as string extends K ? never : {} extends Pick ? never : K]: unknown; +}; +type MissingRouteParamKeys

= Exclude< + RoutePathMap[P] & string, + RequiredParamKeys +>; +type InvalidRouteParamKeys

= { + [K in RoutePathMap[P] & string]: K extends keyof Params + ? [Params[K]] extends [string | number] + ? never + : K + : K; +}[RoutePathMap[P] & string]; +type RequiredRouteParamError

= [ + MissingRouteParamKeys, +] extends [never] + ? [InvalidRouteParamKeys] extends [never] + ? never + : `Param ${InvalidRouteParamKeys} for route ${P} must be a string or number.` + : MissingRouteParam>; +type RouteUrlParamError

= [RoutePathMap[P]] extends [never] + ? 'params' extends keyof O + ? [O['params']] extends [undefined] + ? never + : `Route ${P} has no path params. Remove params.` + : never + : O extends { params: infer Params } + ? Params extends object + ? string extends keyof Params + ? RequiredRouteParamError + : [Exclude] extends [never] + ? RequiredRouteParamError + : `Unknown param ${DiagnosticKeyName>} for route ${P}. Use the parameter names in the route pattern.` + : `Params for route ${P} must be an object with the route's parameter names.` + : MissingRouteParam; +type RouteUrlQueryError

= [Query] extends [RouteQuery | undefined] + ? never + : [ + InvalidValueKeys< + Exclude, + RouteQueryValue | ReadonlyArray + >, + ] extends [never] + ? `Query for route ${P} must be an object with supported query values.` + : `Invalid query param ${DiagnosticKeyName, RouteQueryValue | ReadonlyArray>>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`; +type RouteUrlOptionsError

= [P] extends [RoutePath] + ? O extends undefined + ? MissingRouteParam + : O extends object + ? | RouteUrlParamError + | ('query' extends keyof O ? RouteUrlQueryError : never) + | ('hash' extends keyof O + ? [O['hash']] extends [string | undefined] + ? never + : `Hash for route ${P} must be a string.` + : never) + | `Unknown routeUrl option: ${DiagnosticKeyName>}. Use params, query, or hash.` + : `Options for route ${P} must be an object with params, query, or hash.` + : never; +type RouteUrlCallError

= [P] extends [RoutePath] + ? [RouteUrlOptionsError] extends [never] + ? `Invalid options for route ${P}. Pass an object with params, query, or hash.` + : RouteUrlOptionsError + : string extends P + ? 'Pass a route pattern literal to routeUrl(); string is too broad.' + : `Unknown route: ${P}. Pass a registered route pattern as the first argument.`; +type UnknownRouteUrlOptions = { + [ + K in Exclude + ]: UrlTypeError<`Unknown routeUrl option: ${DiagnosticKeyName}. Use params, query, or hash.`>; +}; +// Keep the diagnostic branch uninhabitable, even for boxed strings or index signatures. +declare const invalid: unique symbol; /** Build a relative URL from a known route pattern. */ -export function routeUrl

( - path: P, - ...args: [RoutePathMap[NoInfer

]] extends [never] - ? [options?: RouteOptions

] - : [options: RouteOptions

] -): RouteUrl { - return buildRouteUrl(path, args[0]) as RouteUrl; +export function routeUrl

(path: P, ...args: RouteUrlArgs>): RouteUrl; +// Function helpers instantiate O as unknown and retain the native checked signature. +// Calls infer S and O independently, so diagnostics point at the incorrect argument. +// Requiring two type arguments keeps

and Parameters> native. +export function routeUrl

( + path: unknown extends O + ? S & P + : [O] extends [never] + ? { + readonly 'This route may require params. Pass its options as the second argument.': never; + readonly [invalid]: never; + } & UrlTypeError> + : S & + ([S] extends [RoutePath] + ? unknown + : UrlTypeError, undefined>>), + ...args: unknown extends O + ? RouteUrlArgs> + : [O] extends [never] + ? [options?: never] + : [ + options: [O] extends [object] + ? ([Exclude] extends [never] + ? RouteUrlCallError, NoInfer> + : UnknownRouteUrlOptions) & + O & { readonly [invalid]: never } + : UrlTypeError, NoInfer>>, + ] +): RouteUrl; +export function routeUrl(path: string, ...args: [options?: unknown]): RouteUrl { + return buildRouteUrl(path, args[0] as UrlOptions | undefined) as RouteUrl; } /** @internal Convert navigation inputs to URL strings without requiring an origin. */ diff --git a/packages/void/src/runtime/routing/url-diagnostics.ts b/packages/void/src/runtime/routing/url-diagnostics.ts new file mode 100644 index 000000000..b3ce144ab --- /dev/null +++ b/packages/void/src/runtime/routing/url-diagnostics.ts @@ -0,0 +1,16 @@ +/** An unsatisfied marker for diagnostic fallbacks, never an accepted input. */ +export type UrlTypeError = [Message] extends [never] + ? never + : { readonly [K in Message]: never }; + +/** Inspect every union member, including members with disjoint property names. */ +export type InvalidValueKeys = Values extends unknown + ? { [K in keyof Values]-?: [Values[K]] extends [Allowed] ? never : K }[keyof Values] + : never; + +/** Preserve numeric and symbol keys when explaining an invalid property. */ +export type DiagnosticKeyName = K extends string | number + ? `${K}` + : K extends symbol + ? 'symbol' + : never; diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index 07fb68e7b..c7e19f7a8 100644 --- a/packages/void/test/integration/route-url-builder.test.ts +++ b/packages/void/test/integration/route-url-builder.test.ts @@ -3,9 +3,10 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSyn import { createRequire } from 'node:module'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; +import { pathToFileURL } from 'node:url'; import { Miniflare, convertV4MiniflareOptions } from 'miniflare'; import { chromium } from 'playwright'; -import { build } from 'vite'; +import { build, transformWithOxc } from 'vite'; import { afterEach, describe, expect, it } from 'vite-plus/test'; import { analyzeApplication } from '../../src/application-routing.ts'; import { createProjectTsconfig } from '../../src/codegen/project-tsconfig.ts'; @@ -15,6 +16,16 @@ import { readConfig } from '../../src/config.ts'; const packageRoot = join(import.meta.dirname, '../..'); const adapterSource = (path: string) => JSON.stringify(join(packageRoot, '..', path)); const roots: Array = []; +const compilers = [ + createRequire(import.meta.url), + createRequire(join(packageRoot, '../../playground/analog/package.json')), +].map((require) => ({ + version: require('typescript/package.json').version as string, + tsc: join(dirname(require.resolve('typescript/package.json')), 'bin/tsc'), +})); +const declarationChecks = compilers.flatMap((compiler) => + (['generated', 'package'] as const).map((declarations) => ({ ...compiler, declarations })), +); afterEach(() => { for (const root of roots.splice(0)) { @@ -343,6 +354,17 @@ routeUrl('/wild/*', { params: { '*': 'a/b' } }); routeUrl('/users/[id]', { params: { id: 123 } }); routeUrl('/files/[...path]', { params: { path: 'docs/start' } }); routeUrl('/wild/[...]', { params: { '*': 'a/b' } }); +routeUrl<'/users/[id]'>('/users/[id]', { params: { id: 123 } }); +interface UserParams { id: number; } +const userParams: UserParams = { id: 123 }; +routeUrl('/users/[id]', { params: userParams }); +declare const either: '/about' | '/users/[id]'; +routeUrl(either, { params: { id: 123 } }); +// @ts-expect-error every possible route's params must be present +routeUrl(either); +declare const optional: [options?: RouteOptions<'/users/[id]'>]; +// @ts-expect-error an optional tuple cannot guarantee required params +routeUrl('/users/[id]', ...optional); // @ts-expect-error bracket patterns require params routeUrl('/users/[id]'); // @ts-expect-error bracket catch-all patterns require params @@ -436,6 +458,7 @@ function typecheck( declarations: 'generated' | 'package', include: Array, compilerOptions: Record = {}, + tsc = compilers[0].tsc, ) { const config = `tsconfig.${include.join('-')}.json`; writeFileSync( @@ -457,10 +480,6 @@ function typecheck( include, }), ); - const tsc = join( - dirname(createRequire(import.meta.url).resolve('typescript/package.json')), - 'bin/tsc', - ); const result = spawnSync(process.execPath, [tsc, '-p', join(root, config)], { encoding: 'utf8', }); @@ -468,6 +487,529 @@ function typecheck( } describe('standalone routeUrl utility', () => { + it.each(declarationChecks)( + 'preserves generic helpers and structural options through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-compatibility.ts': `import { routeUrl, type RouteDestination, type RouteOptions, type RoutePath } from 'void/routes'; +function userUrl(id: T) { + return routeUrl('/users/[id]', { params: { id } }); +} +function forwardOptions>(options: T) { + return routeUrl('/users/[id]', options); +} +function forwardStaticOptions>(options: T) { + return routeUrl('/about', options); +} +function forwardDestination>(destination: T) { + return routeUrl('/users/[id]', destination); +} +function forwardArgs(...args: Parameters>) { + return routeUrl(...args); +} +function forwardGenericArgs

(...args: Parameters>) { + return routeUrl(...args); +} +forwardArgs('/users/[id]', { params: { id: 42 } }); +const user = { id: 42, name: 'Alice' }; +routeUrl('/users/[id]', { params: user }); +const options = { params: user, trace: 'request' }; +routeUrl('/users/[id]', options); +const destination: RouteDestination<'/users/[id]'> = { + pathname: '/users/[id]', params: { id: 42 }, +}; +routeUrl('/users/[id]', destination); +const staticDestination: RouteDestination<'/about'> = { pathname: '/about' }; +routeUrl('/about', staticDestination); +declare const indexedParams: Record & { id: number }; +routeUrl('/users/[id]', { params: indexedParams }); +void [userUrl, forwardOptions, forwardStaticOptions, forwardDestination, forwardArgs, forwardGenericArgs]; +`, + }, + }); + expect(typecheck(root, declarations, ['check-compatibility.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + }, + ); + + it.each(declarationChecks)( + 'checks function helpers through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-function-helpers.ts': `import { routeUrl, type RouteOptions, type RoutePath } from 'void/routes'; +function forward(...args: Parameters) { + return routeUrl(...args); +} +declare const options: RouteOptions; +const userUrl = routeUrl.bind(undefined, '/users/[id]'); +userUrl(options); +routeUrl.call(undefined, '/users/[id]', options); +routeUrl.apply(undefined, ['/users/[id]', options]); +forward('/users/[id]', options); +const specificUserUrl = (routeUrl<'/users/[id]'>).bind(undefined, '/users/[id]'); +specificUserUrl({ params: { id: 42 } }); +// @ts-expect-error bound functions retain required params +userUrl(); +// @ts-expect-error bound functions retain param value checks +userUrl({ params: { id: true } }); +// @ts-expect-error bound functions retain query value checks +userUrl({ ...options, query: { nested: { id: 42 } } }); +// @ts-expect-error call retains required params +routeUrl.call(undefined, '/users/[id]'); +// @ts-expect-error call retains param value checks +routeUrl.call(undefined, '/users/[id]', { params: { id: true } }); +// @ts-expect-error call retains route checks +routeUrl.call(undefined, '/missing', options); +// @ts-expect-error apply retains required params +routeUrl.apply(undefined, ['/users/[id]']); +// @ts-expect-error apply retains param value checks +routeUrl.apply(undefined, ['/users/[id]', { params: { id: true } }]); +// @ts-expect-error apply retains hash checks +routeUrl.apply(undefined, ['/users/[id]', { ...options, hash: 42 }]); +// @ts-expect-error extracted arguments retain required params +forward('/users/[id]'); +// @ts-expect-error extracted arguments retain param value checks +forward('/users/[id]', { params: { id: true } }); +// @ts-expect-error widening a route type cannot bypass static-route checks +routeUrl('/about', options); +// @ts-expect-error widening a route type cannot bypass dynamic-route checks +routeUrl('/users/[id]', options); +// @ts-expect-error explicit diagnostic type arguments cannot widen the route type +routeUrl('/about', options); +`, + }, + }); + expect(typecheck(root, declarations, ['check-function-helpers.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + }, + ); + + it.each([false, true])( + 'retains legacy Node URL checks with skipLibCheck=%s', + async (skipLibCheck) => { + const root = await createFixture({ + typedRoutes: true, + extraFiles: { + 'check-legacy.ts': `import { routeUrl, type Href } from 'void/routes'; +routeUrl('/about'); +routeUrl('/users/[id]', { params: { id: 42 } }); +// @ts-expect-error unknown route patterns remain checked +routeUrl('/missing'); +// @ts-expect-error required params remain checked +routeUrl('/users/[id]'); +// @ts-expect-error raw URLs retain their existing checks +const unknown: Href = '/missing'; +void unknown; +`, + }, + }); + const { scan } = await analyzeApplication(root, { config: readConfig(root) }); + // Legacy resolution can consume generated routes without resolving SDK runtime imports. + scan.routes = scan.routes.map((route) => ({ ...route, methods: [] })); + writeFileSync( + join(root, '.void/routes.d.ts'), + generateRouteTypes(scan, join(root, 'routes'), join(root, '.void'), undefined, { + typedRoutes: true, + }).dts, + ); + expect( + typecheck( + root, + 'generated', + ['check-legacy.ts'], + { moduleResolution: 'node', ignoreDeprecations: '6.0', skipLibCheck }, + compilers[1].tsc, + ), + ).toEqual({ output: '', status: 0 }); + }, + ); + + it.each(['generated', 'package'] as const)( + 'retains URL checks after an SDK upgrade without regenerating the %s declarations', + async (declarations) => { + const root = mkdtempSync(join(tmpdir(), 'void-route-upgrade-')); + roots.push(root); + const outDir = join(root, '.void'); + const packageLink = join(root, 'node_modules/void'); + mkdirSync(outDir, { recursive: true }); + const manifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')); + const generatorCode = ( + await transformWithOxc( + readFileSync(join(packageRoot, 'src/codegen/route-types.ts'), 'utf8'), + 'route-types.ts', + ) + ).code; + function createSdkVersion(version: string, updateQueryTypes = false): string { + const directory = join(root, 'node_modules/.pnpm', `void@${version}/node_modules/void`); + mkdirSync(join(directory, 'src/codegen'), { recursive: true }); + const copied = new Set(); + function copyDeclaration(path: string): void { + if (copied.has(path)) { + return; + } + copied.add(path); + const content = readFileSync(join(packageRoot, path), 'utf8'); + mkdirSync(dirname(join(directory, path)), { recursive: true }); + writeFileSync(join(directory, path), content); + for (const [, specifier] of content.matchAll( + /(?:from\s*|import\()\s*["'](\.[^"']+)["']/g, + )) { + copyDeclaration(join(dirname(path), specifier.replace(/\.mjs$/, '.d.mts'))); + } + } + copyDeclaration(manifest.exports['./routes'].types); + copyDeclaration(manifest.exports['./_route-url-types'].types); + if (updateQueryTypes) { + // Give the second SDK a different contract, not just a different location. + const path = [...copied].find((path) => + readFileSync(join(directory, path), 'utf8').includes('type RouteQueryValue ='), + ); + expect(path).toBeDefined(); + const file = join(directory, path!); + const previous = readFileSync(file, 'utf8'); + const updated = previous.replace( + 'type RouteQueryValue = string | number | boolean | null | undefined;', + 'type RouteQueryValue = string | number | null | undefined;', + ); + expect(updated).not.toBe(previous); + writeFileSync(file, updated); + } + symlinkSync(join(packageRoot, 'node_modules'), join(directory, 'node_modules'), 'junction'); + writeFileSync(join(directory, 'src/codegen/route-types.mjs'), generatorCode); + writeFileSync(join(directory, 'package.json'), JSON.stringify({ ...manifest, version })); + return directory; + } + const oldSdk = createSdkVersion('1.9.1'); + const newSdk = createSdkVersion('1.9.2', true); + symlinkSync(oldSdk, packageLink, 'junction'); + writeFileSync(join(root, 'package.json'), '{"type":"module"}'); + const generator = pathToFileURL(join(oldSdk, 'src/codegen/route-types.mjs')).href; + const generation = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + `import { generateRouteTypes } from ${JSON.stringify(generator)}; +const scan = { routes: [ + { pattern: '/about', params: [], methods: [] }, + { pattern: '/users/:id', params: ['id'], methods: [] }, +], pages: { pages: [] } }; +process.stdout.write(generateRouteTypes(scan, ${JSON.stringify(join(root, 'routes'))}, ${JSON.stringify(outDir)}, undefined, { typedRoutes: true }).dts);`, + ], + { encoding: 'utf8' }, + ); + expect({ status: generation.status, errors: generation.stderr }).toEqual({ + status: 0, + errors: '', + }); + const routeTypesPath = join(outDir, 'routes.d.ts'); + writeFileSync(routeTypesPath, generation.stdout); + writeFileSync( + join(outDir, 'tsconfig.json'), + JSON.stringify(createProjectTsconfig(root, true)), + ); + const upgradeCheck = `import { routeUrl, type Href, type RouteQuery } from 'void/routes'; +const href: Href = routeUrl('/users/[id]', { params: { id: 42 } }); +routeUrl('/about'); +const query: RouteQuery = { enabled: true }; +routeUrl('/about', { query: { enabled: true } }); +// @ts-expect-error unknown route patterns remain checked +routeUrl('/missing'); +// @ts-expect-error required params remain checked +routeUrl('/users/[id]'); +// @ts-expect-error param values remain checked +routeUrl('/users/[id]', { params: { id: true } }); +// @ts-expect-error raw URLs retain their existing route checks +const unknown: Href = '/missing'; +void [href, unknown, query]; +`; + writeFileSync(join(root, 'check-upgrade.ts'), upgradeCheck); + expect(typecheck(root, declarations, ['check-upgrade.ts'])).toEqual({ + output: '', + status: 0, + }); + + rmSync(packageLink, { force: true, recursive: true }); + symlinkSync(newSdk, packageLink, 'junction'); + rmSync(oldSdk, { force: true, recursive: true }); + + expect(readFileSync(routeTypesPath, 'utf8')).toBe(generation.stdout); + writeFileSync( + join(root, 'check-upgrade.ts'), + upgradeCheck + .replace( + 'const query:', + '// @ts-expect-error the new SDK query type is used\nconst query:', + ) + .replace( + "routeUrl('/about', { query:", + "// @ts-expect-error the new SDK function signature is used\nrouteUrl('/about', { query:", + ), + ); + expect(typecheck(root, declarations, ['check-upgrade.ts'])).toEqual({ + output: '', + status: 0, + }); + }, + ); + + it.each(declarationChecks)( + 'rejects invalid unions and numeric keys through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-invalid-unions.ts': `import { routeUrl } from 'void/routes'; +declare const query: { q: string } | { filter: { id: number } }; +// @ts-expect-error every query union member must contain supported values +routeUrl('/about', { query }); +declare const optionalQuery: { q?: string } | { filter?: { id: number } }; +// @ts-expect-error optional query keys cannot hide invalid union members +routeUrl('/about', { query: optionalQuery }); +// @ts-expect-error numeric params do not supply the required id +routeUrl('/users/[id]', { params: { 0: 'missing-id' } }); +// @ts-expect-error fresh numeric extra params are still rejected +routeUrl('/users/[id]', { params: { id: 42, 0: 'extra' } }); +declare const params: { id: number } | { 0: string }; +// @ts-expect-error every params union member must supply id +routeUrl('/users/[id]', { params }); +declare const key: unique symbol; +// @ts-expect-error symbol keys cannot hide a missing id +routeUrl('/users/[id]', { params: { [key]: 42 } }); +// @ts-expect-error numeric option keys do not belong to RouteOptions +routeUrl('/about', { 0: 'unknown-option' }); +declare const options: { query: { q: string } } | { query: { filter: { id: number } } }; +// @ts-expect-error every options union member must be valid +routeUrl('/about', options); +// @ts-expect-error explicit type arguments retain fresh-object excess checks +routeUrl<'/users/[id]'>('/users/[id]', { params: { id: 42, extra: 'x' } }); +// @ts-expect-error widening the type argument cannot omit required params +routeUrl('/users/[id]'); +declare const uncheckedOptions: Record; +// @ts-expect-error index signatures cannot satisfy the diagnostic rejection guard +routeUrl('/users/[id]', uncheckedOptions); +const boxed = Object.assign('Param id for route /users/[id] must be a string or number.' as const, { params: { id: true } }); +// @ts-expect-error a boxed diagnostic message is still invalid options +routeUrl('/users/[id]', boxed); +// @ts-expect-error diagnostic message strings cannot act as options +routeUrl('/about', 'Invalid options for route /about. Pass an object with params, query, or hash.'); +// @ts-expect-error diagnostic message values cannot turn unknown options into valid ones +routeUrl('/about', { search: 'Unknown routeUrl option: search. Use params, query, or hash.' }); +const fakePath = { + get 'This route may require params. Pass its options as the second argument.'(): never { throw new Error(); }, + get 'Pass a route pattern literal to routeUrl(); string is too broad.'(): never { throw new Error(); }, +}; +// @ts-expect-error diagnostic objects cannot act as route patterns +routeUrl(fakePath); +`, + }, + }); + expect(typecheck(root, declarations, ['check-invalid-unions.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + }, + ); + + it.each(declarationChecks)( + 'explains invalid routeUrl calls through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { + const cases = [ + ["routeUrl('/missing');", 'Unknown route: /missing.'], + ["routeUrl('/missing', {});", 'Unknown route: /missing.'], + ["routeUrl('/users/42');", 'Unknown route: /users/42.'], + ["routeUrl('/users/[id]');", 'Missing param id for route /users/[id].'], + ["routeUrl('/users/[id]', {});", 'Missing param id for route /users/[id].'], + [ + "routeUrl('/users/[id]', { query: { page: 1 } });", + 'Missing param id for route /users/[id].', + ], + ["routeUrl('/users/[id]', { params: {} });", 'Missing param id for route /users/[id].'], + [ + "routeUrl('/users/[id]', { params: { userId: 42 } });", + 'Unknown param userId for route /users/[id].', + ], + [ + "routeUrl('/users/[id]', { params: { id: 42, extra: 'x' } });", + 'Unknown param extra for route /users/[id].', + ], + [ + "routeUrl('/users/[id]', { params: { id: true } });", + 'Param id for route /users/[id] must be a string or number.', + ], + ["routeUrl('/about', { params: {} });", 'Route /about has no path params.'], + ["routeUrl('/about', { hash: 123 });", 'Hash for route /about must be a string.'], + [ + "routeUrl('/users/[id]', { params: {} as Record });", + 'Missing param id for route /users/[id].', + ], + [ + "routeUrl('/users/[id]', { params: {} as { id?: string } });", + 'Missing param id for route /users/[id].', + ], + [ + "routeUrl('/users/[id]', { params: {} as Record & { id: boolean } });", + 'Param id for route /users/[id] must be a string or number.', + ], + [ + "routeUrl('/users/[id]', { params: {} as Record & { id: string }, query: { nested: {} } });", + 'Invalid query param nested for route /users/[id].', + ], + [ + "routeUrl('/about', { query: () => 'x' });", + 'Query for route /about must be an object with supported query values.', + ], + [ + "routeUrl('/about', { query: null });", + 'Query for route /about must be an object with supported query values.', + ], + [ + "routeUrl('/about', () => 'x');", + 'Invalid options for route /about. Pass an object with params, query, or hash.', + ], + [ + "routeUrl('/about', { query: { nested: { value: 'x' } } });", + 'Invalid query param nested for route /about.', + ], + [ + "routeUrl('/about', { query: null as unknown as { q: string } | { filter: { id: number } } });", + 'Invalid query param filter for route /about.', + ], + [ + "routeUrl('/users/[id]', { params: { 0: 'missing-id' } });", + 'Unknown param 0 for route /users/[id].', + ], + ["routeUrl('/about', { 0: 'unknown' });", 'Unknown routeUrl option: 0.'], + ["routeUrl('/about', { search: 'x' });", 'Unknown routeUrl option: search.'], + ["routeUrl('/users/[id]', undefined);", 'Missing param id for route /users/[id].'], + ["routeUrl('' as '/about' | '/users/[id]');", 'Missing param id for route /users/[id].'], + [ + "routeUrl('' as string);", + 'Pass a route pattern literal to routeUrl(); string is too broad.', + ], + ]; + const root = await createFixture({ + extraFiles: { + 'check-diagnostics.ts': [ + "import { routeUrl } from 'void/routes';", + ...cases.map(([call]) => call), + ].join('\n'), + }, + }); + const { output, status } = typecheck(root, declarations, ['check-diagnostics.ts'], {}, tsc); + expect(status).not.toBe(0); + const diagnostics = output + .split(/.*check-diagnostics\.ts\(\d+,\d+\): error TS\d+: /) + .slice(1); + expect(diagnostics).toHaveLength(cases.length); + cases.forEach(([, message], index) => expect(diagnostics[index]).toContain(message)); + expect(output).not.toContain('TS2554'); + expect(output).not.toContain('UrlTypeError'); + expect(output).not.toContain('Unknown param ${string}'); + expect(output).not.toContain('RouteUrlOptionsInput'); + expect(output).not.toContain('__voidUrlError'); + expect(diagnostics[7]).toContain( + `parameter of type '"Unknown param userId for route /users/[id].`, + ); + expect(diagnostics[7]).not.toContain('Argument of type \'["/users/[id]"'); + }, + ); + + it.each(declarationChecks)( + 'explains missing options for generic routes through $declarations declarations with TS $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-generic-diagnostic.ts': `import { routeUrl, type RoutePath } from 'void/routes'; +function bare

(path: P) { + return routeUrl(path); +} +void bare; +`, + }, + }); + const { output, status } = typecheck( + root, + declarations, + ['check-generic-diagnostic.ts'], + {}, + tsc, + ); + expect(status).not.toBe(0); + expect(output).toContain( + 'This route may require params. Pass its options as the second argument.', + ); + }, + ); + + it.each(['generated', 'package'] as const)( + 'keeps diagnostic details out of completions through the %s declarations', + async (declarations) => { + const root = await createFixture(); + const check = join(root, 'check-completions.ts'); + writeFileSync( + check, + `import { routeUrl } from 'void/routes'; +routeUrl('/*route*/'); +routeUrl('/users/[id]', { /*options*/ }); +routeUrl('/users/[id]', { params: { /*params*/ } }); +`, + ); + const tsModule = createRequire(compilers[1].tsc).resolve('typescript'); + const options = { + target: 'ES2022', + module: declarations === 'generated' ? 'ESNext' : 'NodeNext', + moduleResolution: declarations === 'generated' ? 'Bundler' : 'NodeNext', + strict: true, + skipLibCheck: true, + types: [], + paths: + declarations === 'generated' ? { 'void/routes': [join(root, '.void/routes.d.ts')] } : {}, + }; + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + `import ts from ${JSON.stringify(pathToFileURL(tsModule).href)}; +const root = ${JSON.stringify(root)}; +const file = ${JSON.stringify(check)}; +const content = ts.sys.readFile(file); +const options = ts.convertCompilerOptionsFromJson(${JSON.stringify(options)}, root).options; +const service = ts.createLanguageService({ + getScriptFileNames: () => [file, ${JSON.stringify(join(root, '.void/routes.d.ts'))}], + getScriptVersion: () => '0', + getScriptSnapshot: (path) => ts.sys.fileExists(path) ? ts.ScriptSnapshot.fromString(ts.sys.readFile(path)) : undefined, + getCurrentDirectory: () => root, + getCompilationSettings: () => options, + getDefaultLibFileName: (settings) => ts.getDefaultLibFilePath(settings), + fileExists: ts.sys.fileExists, + readFile: ts.sys.readFile, + readDirectory: ts.sys.readDirectory, +}); +const completions = Object.fromEntries(['route', 'options', 'params'].map((marker) => [ + marker, + (service.getCompletionsAtPosition(file, content.indexOf('/*' + marker + '*/'), {})?.entries ?? []).map((entry) => entry.name).sort(), +])); +service.dispose(); +process.stdout.write(JSON.stringify(completions));`, + ], + { encoding: 'utf8' }, + ); + expect({ status: result.status, errors: result.stderr }).toEqual({ status: 0, errors: '' }); + const completions = JSON.parse(result.stdout); + expect(completions.route).toEqual(expect.arrayContaining(['/about', '/users/[id]'])); + expect(completions.route.every((name: string) => name.startsWith('/'))).toBe(true); + expect(completions.options).toEqual(['hash', 'params', 'query']); + expect(completions.params).toEqual(['id']); + }, + ); + it.each(['generated', 'package'] as const)( 'preserves HTTP, WebSocket and page action contracts for both syntaxes through %s declarations', async (declarations) => { diff --git a/packages/void/test/unit/route-types.test.ts b/packages/void/test/unit/route-types.test.ts index afe1b4aff..8aec37f67 100644 --- a/packages/void/test/unit/route-types.test.ts +++ b/packages/void/test/unit/route-types.test.ts @@ -298,9 +298,6 @@ describe('generateRouteTypes', () => { ' "/café/[id]": "/caf%C3%A9/[id]";', ' "/café/:id": "/caf%C3%A9/:id";', ]); - expect(dts).toContain( - 'type RoutePathUrl = RoutePatternUrl>;', - ); }); it('turns on typed route URLs only when routing.typedRoutes is set', () => { @@ -327,8 +324,8 @@ describe('generateRouteTypes', () => { expect(typesConfig(off).trim()).toBe(''); expect(typesConfig(on).trim()).toBe('typedRoutes: true;'); expect(on.replace(' typedRoutes: true;\n', '')).toBe(off); - expect(off).toContain('export type RouteUrlInput = Href | URL | RouteDestination;'); - expect(off).toContain(' ): RouteUrl;'); + expect(off).toMatch(/export type RouteUrlInput = import\("[^"]+"\)\.RouteUrlInput;/); + expect(off).toMatch(/export const routeUrl: typeof import\("[^"]+"\)\.routeUrl;/); }); it('generates PageActionMap for pages with actions', () => { diff --git a/packages/void/test/unit/route-url-builder.typecheck.ts b/packages/void/test/unit/route-url-builder.typecheck.ts index e6f3da4bf..384115f23 100644 --- a/packages/void/test/unit/route-url-builder.typecheck.ts +++ b/packages/void/test/unit/route-url-builder.typecheck.ts @@ -22,6 +22,13 @@ describe('routeUrl types', () => { routeUrl('/route-types/files/*', { params: { '*': 'a/b' } }); const options: RouteOptions<'/route-types/:id'> = { params: { id: '123' } }; routeUrl('/route-types/:id', options); + routeUrl<'/route-types/:id'>('/route-types/:id', options); + interface Params { + id: number; + } + const params: Params = { id: 123 }; + routeUrl('/route-types/:id', { params }); + routeUrl('/route-types', undefined); }); it('rejects unknown paths and incorrect params', () => { @@ -31,6 +38,8 @@ describe('routeUrl types', () => { routeUrl('/route-types/123'); // @ts-expect-error params are required routeUrl('/route-types/:id'); + // @ts-expect-error undefined options cannot bypass required params + routeUrl('/route-types/:id', undefined); // @ts-expect-error params are required even when other options are provided routeUrl('/route-types/:id', { query: { page: 1 } }); // @ts-expect-error param names must match @@ -57,5 +66,8 @@ describe('routeUrl types', () => { // @ts-expect-error one of the possible routes requires params routeUrl(path); routeUrl(path, { params: { id: '123' } }); + const optional: [options?: RouteOptions<'/route-types/:id'>] = []; + // @ts-expect-error an optional tuple cannot guarantee required params + routeUrl('/route-types/:id', ...optional); }); });