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 af742cf73..bfcc35555 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -174,6 +174,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 e504ba55d..53b7afba5 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/runtime/db-session": "./dist/runtime/db/session.mjs", @@ -314,6 +321,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..f89954840 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -139,71 +139,40 @@ 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;'); - lines.push( - ' type RoutePathUrl = RoutePatternUrl>;', - ); - 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'); + // A bare types-only entry follows the installed SDK through upgrades. + // void/routes would be circular because this file augments that entry. + // Resolve the SDK's ESM declarations from CommonJS projects as well. + const sdkRouteTypes = + 'import("void/_route-url-types", { with: { "resolution-mode": "import" } })'; + // Earlier generated files declared the URL helpers here, which exported them from + // void/routes too, so keep every one of those names importable. + for (const name of [ + 'RoutePath', + 'RouteQueryValue', + 'RouteQuery', + 'RouteUrl', + 'Href', + 'RouteUrlInput', + 'TypedRoutes', + 'BuiltRouteUrl', + 'EncodedRoutePath', + 'RoutePathUrl', + ]) { + lines.push(` export type ${name} = ${sdkRouteTypes}.${name};`); + } + for (const name of [ + 'RouteUrlSegment', + 'CheckedRoutePath', + 'RouteSegmentsUrl', + 'RoutePatternUrl', + ]) { + lines.push(` export type ${name}

= ${sdkRouteTypes}.${name}

;`); + } + lines.push(` export type RouteOptions

= ${sdkRouteTypes}.RouteOptions

;`); lines.push( - ' ? RouteUrl | `${"?" | "#"}${string}` | `${"http://" | "https://" | "mailto:" | "tel:"}${string}`', + ` export type RouteDestination

= ${sdkRouteTypes}.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 ${sdkRouteTypes}.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..9f0f03084 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 { UrlErrorToken } from './url-diagnostics.ts'; /** * Encode one path segment of a route param. `encodeURIComponent` keeps dots, and @@ -80,13 +81,18 @@ export function interpolateRouteParams( /** Known page, HTTP and WebSocket route patterns. */ export type RoutePath = keyof RoutePathMap & string; +// The helpers below are exported because generated route declarations re-export them: +// earlier generated files declared them, so apps can import them from `void/routes`. + // Dynamic segments in either public or legacy patterns match any text, // so `/users/[id]` accepts `/users/${string}`. Template // literal types cannot exclude empty or `/`-leading text without per-character unions. -type RouteUrlSegment = S extends `:${string}` | `[${string}]` | '*' ? string : S; +export type RouteUrlSegment = S extends `:${string}` | `[${string}]` | '*' + ? string + : S; // Root params and catch-alls would accept every absolute path. Keep those // patterns available to routeUrl(), but require explicit construction for them. -type CheckedRoutePath

= P extends `/${infer Segment}/${infer Rest}` +export type CheckedRoutePath

= P extends `/${infer Segment}/${infer Rest}` ? Rest extends '' ? string extends RouteUrlSegment ? never @@ -97,21 +103,21 @@ type CheckedRoutePath

= P extends `/${infer Segment}/${infer R ? never : P : P; -type RouteSegmentsUrl

= P extends `${infer Segment}/${infer Rest}` +export type RouteSegmentsUrl

= P extends `${infer Segment}/${infer Rest}` ? `${RouteUrlSegment}/${RouteSegmentsUrl}` : RouteUrlSegment

; // A trailing `/*` also matches the bare prefix, as in Hono: `/docs/*` matches `/docs`. -type RoutePatternUrl

= P extends `${infer Prefix}/${'*' | '[...]'}/` +export type RoutePatternUrl

= P extends `${infer Prefix}/${'*' | '[...]'}/` ? `${RouteSegmentsUrl}/` | `${RouteSegmentsUrl}/${string}/` : P extends `${infer Prefix}/${'*' | '[...]'}` ? (Prefix extends '' ? '/' : RouteSegmentsUrl) | `${RouteSegmentsUrl}/${string}` : RouteSegmentsUrl

; // Fixed segments are also accepted percent-encoded, as `routeUrl()` returns them. -type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string; -type RoutePathUrl = RoutePatternUrl>; +export type EncodedRoutePath = EncodedRoutePathMap[keyof EncodedRoutePathMap] & string; +export type RoutePathUrl = RoutePatternUrl>; // Use a structural marker so package and generated declarations agree when a // helper-built URL crosses into a navigation, form, or stream client. -type BuiltRouteUrl = string & { readonly __voidRouteUrl: true }; +export type BuiltRouteUrl = string & { readonly __voidRouteUrl: true }; /** Whether `routing.typedRoutes` is on in the generated route types. */ export type TypedRoutes = RouteTypesConfig extends { typedRoutes: true } ? true : false; @@ -157,14 +163,65 @@ type UrlOptions = { hash?: string; }; +// An unknown pattern has no matching route params, so TypeScript can report +// the path error even if the options argument is absent. In static-only apps, +// keep P alone so an unchecked path doesn't affect the optional options tuple. +// A broad candidate must also keep P so it cannot widen the checked pattern. Candidate +// holds only the string literals in the path, so narrow P by it only when one of them +// is unknown: a path such as `P | '/about'` has other members that P must keep. +type MatchingRoute

= [ + RoutePathMap[RoutePath], +] extends [never] + ? P + : [Candidate] extends [RoutePath] + ? P + : string extends Candidate + ? P + : P & Candidate; + +// Function helpers can widen Candidate to string when they infer the signature. +// The marker must not be a subtype of the path: method signatures and code without +// strictFunctionTypes compare parameters bivariantly and would accept the route. +// A string-literal message also keeps the quoted path in the error: TypeScript prints +// the argument as `string` when the parameter type has no literal or template members. +// Distributing over Candidate lets an implementation of `typeof routeUrl` accept the path +// as `RoutePath`: TypeScript checks it with Candidate widened to string, which yields P. +// That result must not be never, or TypeScript would not use it. +type UnknownRoute

= Candidate extends RoutePath + ? never + : string extends Candidate + ? NoInfer

+ : `Unknown route: ${Exclude, RoutePath>}. Use a registered route pattern.` & + UrlErrorToken; + +// Keep P out of a top-level union so TypeScript infers it from the whole argument. A +// generic path such as `P & RoutePath` would otherwise be inferred from its first member +// alone. The inner check always holds; its false branch only gives Candidate an inference +// site. That site is a template literal, so only string literals infer a candidate. Other +// paths, such as `P & RoutePath` in a generic helper, infer never and resolve to P like a +// plain parameter. Left deferred, the check would compare every route in that union with +// every other one, which exceeds TypeScript's complexity limit in apps with ~1,400 routes. +// The unreachable branch is also a route so that every branch is assignable to P. +type RouteArgument

= [Candidate] extends [never] + ? P + : string extends Candidate + ? P + : [Candidate] extends [unknown] + ? MatchingRoute | UnknownRoute + : `${Candidate}` & NoInfer

; + /** 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; +// A single signature with a positional path preserves inference in wrappers and currying helpers. +// Candidate is bounded by plain string: with `RoutePath | (string & {})`, the constraint of +// `P & Candidate` is a cross product of the route union that overflows past ~316 routes. +export function routeUrl

( + path: RouteArgument, + ...options: [RoutePathMap[NoInfer>]] extends [never] + ? [options?: RouteOptions>] + : [options: RouteOptions>] +): 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..782a769c2 --- /dev/null +++ b/packages/void/src/runtime/routing/url-diagnostics.ts @@ -0,0 +1,3 @@ +// Require a property ordinary argument lists cannot supply. A well-known symbol +// can be named in declarations emitted for functions that wrap routeUrl. +export type UrlErrorToken = { readonly [Symbol.toPrimitive]: never }; diff --git a/packages/void/test/integration/route-url-builder.test.ts b/packages/void/test/integration/route-url-builder.test.ts index eca1d02a5..d83204e3c 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,26 @@ import { readConfig } from '../../src/config.ts'; const packageRoot = join(import.meta.dirname, '../..'); const adapterSource = (path: string) => JSON.stringify(join(packageRoot, '..', path)); const roots: Array = []; +// tsrs is the repository's compiler. Apps and editors also run TypeScript 7 and 6. +const compilers = ( + [ + ['tsrs', 'bin/tsrs', createRequire(import.meta.url)], + ['typescript', 'bin/tsc', createRequire(import.meta.url)], + [ + 'typescript', + 'bin/tsc', + createRequire(join(packageRoot, '../../playground/analog/package.json')), + ], + ] as const +).map(([name, bin, require]) => ({ + version: `${name === 'tsrs' ? 'tsrs' : 'TS'} ${require(`${name}/package.json`).version}`, + tsc: join(dirname(require.resolve(`${name}/package.json`)), bin), +})); +// The oldest supported TypeScript, which still has legacy `node` resolution and a JS API. +const typescript6 = compilers[2]; +const declarationChecks = compilers.flatMap((compiler) => + (['generated', 'package'] as const).map((declarations) => ({ ...compiler, declarations })), +); afterEach(() => { for (const root of roots.splice(0)) { @@ -300,8 +321,15 @@ ${['react', 'vue', 'svelte', 'solid'] async function createFixture({ typedRoutes = false, + includeHandlers = true, + staticOnly = false, extraFiles = {}, -}: { typedRoutes?: boolean; extraFiles?: Record } = {}) { +}: { + typedRoutes?: boolean; + includeHandlers?: boolean; + staticOnly?: boolean; + extraFiles?: Record; +} = {}) { const root = mkdtempSync(join(tmpdir(), 'void-route-util-')); roots.push(root); const files: Record = { @@ -310,17 +338,24 @@ async function createFixture({ 'check-solid-link.ts': solidLinkHrefCheck, 'check-use-params.ts': useParamsCheck, 'package.json': '{"type":"module"}', - 'routes/api/users/[id].ts': - "import { defineHandler } from 'void/handler'; export const GET = defineHandler(() => ({ ok: true }));", - 'routes/api/legacy.ts': - "import { defineHandler } from 'void/handler'; export default defineHandler(() => ({ ok: true }));", + ...(includeHandlers && { + 'routes/api/legacy.ts': + "import { defineHandler } from 'void/handler'; export default defineHandler(() => ({ ok: true }));", + ...(!staticOnly && { + 'routes/api/users/[id].ts': + "import { defineHandler } from 'void/handler'; export const GET = defineHandler(() => ({ ok: true }));", + }), + }), 'pages/index.tsx': 'export default function Page() { return null; }', 'pages/about.tsx': 'export default function Page() { return null; }', 'pages/café menu.tsx': 'export default function Page() { return null; }', - 'pages/café/[id].tsx': 'export default function Page() { return null; }', - 'pages/users/[id].tsx': 'export default function Page() { return null; }', - 'pages/files/[...path].tsx': 'export default function Page() { return null; }', - 'pages/wild/[...].tsx': 'export default function Page() { return null; }', + ...(!staticOnly && { + 'pages/café/[id].tsx': 'export default function Page() { return null; }', + 'pages/users/[id].tsx': 'export default function Page() { return null; }', + 'pages/blog/[category]/[slug].tsx': 'export default function Page() { return null; }', + 'pages/files/[...path].tsx': 'export default function Page() { return null; }', + 'pages/wild/[...].tsx': 'export default function Page() { return null; }', + }), 'check.ts': `import type { Context, MiddlewareHandler } from 'hono'; import { getCookie } from 'hono/cookie'; import { @@ -343,6 +378,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 +482,7 @@ function typecheck( declarations: 'generated' | 'package', include: Array, compilerOptions: Record = {}, + tsc = compilers[0].tsc, ) { const config = `tsconfig.${include.join('-')}.json`; writeFileSync( @@ -457,17 +504,894 @@ function typecheck( include, }), ); - const tsrs = join( - dirname(createRequire(import.meta.url).resolve('tsrs/package.json')), - 'bin/tsrs', - ); - const result = spawnSync(process.execPath, [tsrs, '-p', join(root, config)], { + // Tests parse `file(line,col): error` lines. Under FORCE_COLOR, which `vp run` sets for + // tests, TypeScript 7 and tsrs print pretty diagnostics unless the command line opts out. + const result = spawnSync(process.execPath, [tsc, '-p', join(root, config), '--pretty', 'false'], { encoding: 'utf8', }); return { output: result.stdout + result.stderr, status: result.status }; } describe('standalone routeUrl utility', () => { + it.each(declarationChecks)( + 'preserves generic helpers and structural options through $declarations declarations with $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 forwardRouteOptions

(path: P, options: RouteOptions

) { + return routeUrl(path, options); +} +function forwardRouteOptionsSubtype

>(path: P, options: O) { + return routeUrl(path, options); +} +function forwardExplicitOptions

(path: P, options: RouteOptions

) { + return routeUrl

(path, options); +} +function forwardAnyOptions

(path: P, options: any) { + return routeUrl(path, options); +} +const buildRoute:

(path: P, options: RouteOptions

) => string = routeUrl; +const buildRouteWithSubtype:

>(path: P, options: O) => string = routeUrl; +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); +} +function forwardIntersectedPath

(path: P & RoutePath, options: any) { + return routeUrl(path, options); +} +function forwardUnconstrainedPath

(path: P & RoutePath, options: any) { + return routeUrl(path, options); +} +function forwardStaticIntersection

(path: P & ('/' | '/about')) { + return routeUrl(path); +} +function forwardPathOrAbout

(path: P | '/about', options: any) { + return routeUrl(path, options); +} +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, forwardRouteOptions, forwardRouteOptionsSubtype, forwardExplicitOptions, forwardAnyOptions, buildRoute, buildRouteWithSubtype, forwardStaticOptions, forwardDestination, forwardArgs, forwardGenericArgs, forwardIntersectedPath, forwardUnconstrainedPath, forwardStaticIntersection, forwardPathOrAbout]; +`, + }, + }); + expect(typecheck(root, declarations, ['check-compatibility.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + }, + ); + + it.each(declarationChecks)( + 'accepts implementations and helper types from main through $declarations declarations with $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-implementations.ts': `import { routeUrl, type RoutePath, type RouteUrl } from 'void/routes'; +import type { BuiltRouteUrl, CheckedRoutePath, EncodedRoutePath, RoutePathUrl, RoutePatternUrl, RouteSegmentsUrl, RouteUrlSegment, TypedRoutes } from 'void/routes'; +const routePath: typeof routeUrl = (path: RoutePath, options?: unknown) => path as RouteUrl; +const routePathRest: typeof routeUrl = (path: RoutePath, ...rest: unknown[]) => path as RouteUrl; +const genericRest: typeof routeUrl =

(path: P, ...args: any[]) => path as RouteUrl; +const forwarded: typeof routeUrl = (path, ...options) => routeUrl(path, ...options); +const satisfied = ((path: RoutePath, options?: unknown) => path as RouteUrl) satisfies typeof routeUrl; +function declared

(path: P, ...args: any[]): RouteUrl { + return path as RouteUrl; +} +const fromDeclaration: typeof routeUrl = declared; +const dependencies: { routeUrl: typeof routeUrl } = { + routeUrl(path: RoutePath, options?: unknown) { + return path as RouteUrl; + }, +}; +interface UrlBuilder { + build: typeof routeUrl; +} +class FakeBuilder implements UrlBuilder { + build(path: RoutePath, options?: unknown) { + return path as RouteUrl; + } +} +function withBuilder(build: typeof routeUrl = (path: RoutePath, options?: unknown) => path as RouteUrl) { + return build; +} +declare function fn any>(implementation?: T): T & { + mockImplementation(implementation: T): void; +}; +const mock: typeof routeUrl = fn((path: RoutePath, options?: unknown) => path as RouteUrl); +fn(routeUrl).mockImplementation((path: RoutePath) => path as RouteUrl); +routePath('/about'); +routePath('/users/[id]', { params: { id: 42 } }); +// @ts-expect-error an implementation keeps routeUrl's required params +routePath('/users/[id]'); +// @ts-expect-error an implementation keeps routeUrl's route check +forwarded('/missing'); +const typed: TypedRoutes = false; +const built = '' as BuiltRouteUrl; +const pathUrl: RoutePathUrl = '/users/42'; +type Helpers = [EncodedRoutePath, CheckedRoutePath<'/about'>, RoutePatternUrl<'/files/[...]'>, RouteSegmentsUrl<'a/b'>, RouteUrlSegment<'[id]'>]; +void [routePathRest, genericRest, satisfied, fromDeclaration, dependencies, FakeBuilder, withBuilder, mock, typed, built, pathUrl, {} as Helpers]; +`, + }, + }); + expect(typecheck(root, declarations, ['check-implementations.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + }, + ); + + it.each(declarationChecks)( + 'checks function helpers through $declarations declarations with $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); +} +function wrap(fn: (...args: A) => R): (...args: A) => R { + return (...args) => fn(...args); +} +function curry(fn: (path: P, ...args: A) => R) { + return (path: P) => (...args: A): R => fn(path, ...args); +} +export const wrapped = wrap(routeUrl); +wrapped('/about'); +wrapped('/users/[id]', { params: { id: 42 } }); +wrapped('/blog/[category]/[slug]', { params: { category: 'typescript', slug: 'routes' } }); +// @ts-expect-error wrapping retains required params +wrapped('/users/[id]'); +// @ts-expect-error wrapping retains per-route param names +wrapped('/users/[id]', { params: { slug: 'routes' } }); +// @ts-expect-error wrapping retains route checks +wrapped('/missing'); +function forwardWrappedOptions

>(path: P, options: O) { + return wrapped(path, options); +} +forwardWrappedOptions('/users/[id]', { params: { id: 42 }, trace: 'request' }); +// @ts-expect-error forwarding an options subtype still requires the route's params +forwardWrappedOptions('/users/[id]', { hash: 'team' }); +export const curried = curry(routeUrl); +const buildAbout: (path: '/about') => string = routeUrl; +const buildAboutWithOptions: (path: '/about', options?: RouteOptions<'/about'>) => string = routeUrl; +// @ts-expect-error a builder specialized to a dynamic route requires options +const buildUser: (path: '/users/[id]') => string = routeUrl<'/users/[id]'>; +void [buildAbout, buildAboutWithOptions, buildUser]; +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 an unknown candidate cannot make options optional for a dynamic route +routeUrl('/users/[id]'); +`, + 'check-inferred-exports.ts': `import { curried, wrapped } from './dist/check-function-helpers.js'; +curried('/about')(); +curried('/about')({ hash: 'team' }); +curried('/users/[id]')({ params: { id: 42 } }); +// @ts-expect-error currying retains required params +curried('/users/[id]')(); +// @ts-expect-error currying retains per-route param names +curried('/users/[id]')({ params: { slug: 'routes' } }); +// @ts-expect-error currying retains route checks +curried('/missing'); +wrapped('/about'); +wrapped('/users/[id]', { params: { id: 42 } }); +// @ts-expect-error the emitted wrapper declaration retains required params +wrapped('/users/[id]'); +`, + }, + }); + expect( + typecheck( + root, + declarations, + ['check-function-helpers.ts'], + { declaration: true, emitDeclarationOnly: true, noEmit: false, outDir: './dist' }, + tsc, + ), + ).toEqual({ output: '', status: 0 }); + expect(typecheck(root, declarations, ['check-inferred-exports.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + }, + ); + + it.each(declarationChecks)( + 'keeps options optional in static function helpers through $declarations declarations with $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + includeHandlers: false, + staticOnly: true, + extraFiles: { + 'check-static-binding.ts': `import { routeUrl } from 'void/routes'; +const build = routeUrl.bind(undefined, '/about'); +build(); +build({ hash: 'team' }); +const buildAbout = (routeUrl<'/about'>).bind(undefined, '/about'); +buildAbout(); +buildAbout({ hash: 'team' }); +// @ts-expect-error static routes still reject params when bound +buildAbout({ params: { id: 42 } }); +declare const unchecked: any; +routeUrl.call(undefined, unchecked); +routeUrl.call(undefined, unchecked, undefined); +`, + }, + }); + for (const compilerOptions of [ + { exactOptionalPropertyTypes: true }, + { strictNullChecks: false }, + ]) { + expect + .soft( + typecheck(root, declarations, ['check-static-binding.ts'], compilerOptions, tsc), + JSON.stringify(compilerOptions), + ) + .toEqual({ output: '', status: 0 }); + } + }, + ); + + it.each(compilers)( + 'checks generated routes in Node16 CommonJS with $version', + async ({ tsc }) => { + const root = await createFixture({ + typedRoutes: true, + includeHandlers: false, + extraFiles: { + 'package.json': '{"type":"commonjs"}', + 'check-commonjs.ts': `import { routeUrl, type Href } from 'void/routes'; +const url: Href = routeUrl('/users/[id]', { params: { id: 42 } }); +// @ts-expect-error known dynamic routes require params +routeUrl('/users/[id]'); +// @ts-expect-error unknown route patterns remain checked +routeUrl('/missing'); +// @ts-expect-error raw URLs remain checked +const missing: Href = '/missing'; +void [url, missing]; +`, + }, + }); + expect( + typecheck( + root, + 'generated', + ['check-commonjs.ts'], + { module: 'Node16', moduleResolution: 'Node16', skipLibCheck: false }, + 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 }, + typescript6.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)( + 'keeps invalid inputs rejected through $declarations declarations with $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-invalid-unions.ts': `import { routeUrl, type RoutePath } 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 }); +declare const overlappingQuery: { q: string } | { q: string; filter: { id: number } }; +// @ts-expect-error a valid union member cannot hide invalid values on another member +routeUrl('/about', { query: overlappingQuery }); +// @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 an index signature does not supply the required params +routeUrl('/users/[id]', uncheckedOptions); +const uncheckedPath = JSON.parse('"/users/[id]"'); +routeUrl(uncheckedPath, { params: { id: 42 } }); +// @ts-expect-error a path typed as any may require options +routeUrl(uncheckedPath); +// @ts-expect-error undefined cannot supply the options for a path typed as any +routeUrl(uncheckedPath, undefined); +// @ts-expect-error a broad candidate cannot make required options optional +routeUrl(uncheckedPath); +const fakeUnknownPath = Object.assign('/missing' as const, { + get 'Unknown route: /missing. Use a registered route pattern.'(): never { throw new Error(); }, +}); +// @ts-expect-error a boxed error message cannot make an unknown path valid +routeUrl(fakeUnknownPath); +// @ts-expect-error an any-valued unknown option remains invalid +routeUrl('/about', { search: undefined as any }); +// @ts-expect-error explicit diagnostic type arguments retain native params checking +routeUrl('/users/[id]', { params: { id: true } }); +// @ts-expect-error an any candidate cannot bypass the route pattern check +routeUrl<'/about', any>('/missing', { params: {} }); +// @ts-expect-error an any candidate cannot bypass per-route param checks +routeUrl<'/users/[id]', any>('/users/[id]', { params: {} }); +`, + 'check-exact-optional.ts': `import { routeUrl, type RouteOptions } from 'void/routes'; +routeUrl('/about'); +routeUrl('/about', undefined); +routeUrl('/users/[id]', { params: { id: 42 } }); +function forwardStaticOptions>(options?: O) { + return routeUrl('/about', options); +} +void forwardStaticOptions; +declare const value: any; +// @ts-expect-error exact optional properties do not allow params on static routes +routeUrl('/about', { params: value }); +// @ts-expect-error query cannot be explicitly undefined in exact mode +routeUrl('/about', { query: undefined }); +// @ts-expect-error hash cannot be explicitly undefined in exact mode +routeUrl('/about', { hash: undefined }); +// @ts-expect-error fresh extra params stay rejected when their value is any +routeUrl('/users/[id]', { params: { id: 42, extra: value } }); +`, + }, + }); + expect(typecheck(root, declarations, ['check-invalid-unions.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + expect( + typecheck( + root, + declarations, + ['check-exact-optional.ts'], + { exactOptionalPropertyTypes: true }, + tsc, + ), + ).toEqual({ output: '', status: 0 }); + }, + ); + + it.each(declarationChecks)( + 'rejects unknown routes in bivariant parameter checks through $declarations declarations with $version', + async ({ declarations, tsc }) => { + const root = await createFixture({ + extraFiles: { + 'check-bivariant.ts': `import { routeUrl } from 'void/routes'; +interface Builder { url(path: '/missing'): string } +// @ts-expect-error method signatures compare parameters bivariantly but still reject unknown routes +const builder: Builder = { url: routeUrl }; +// @ts-expect-error a class property implementing a method signature still rejects unknown routes +class RouteBuilder implements Builder { url = routeUrl; } +// @ts-expect-error an unknown bracket route would throw for its missing param at runtime +const renamed: { url(path: '/users/[uid]'): string } = { url: routeUrl }; +// @ts-expect-error a known route cannot hide an unknown one in the same union +const mixed: { url(path: '/about' | '/missing'): string } = { url: routeUrl }; +// @ts-expect-error function types without strictFunctionTypes still reject unknown routes +const callback: (path: '/missing') => string = routeUrl; +const known: { url(path: '/about'): string } = { url: routeUrl }; +void [builder, RouteBuilder, renamed, mixed, callback, known]; +`, + }, + }); + for (const compilerOptions of [{}, { strictFunctionTypes: false }]) { + expect + .soft( + typecheck(root, declarations, ['check-bivariant.ts'], compilerOptions, tsc), + JSON.stringify(compilerOptions), + ) + .toEqual({ output: '', status: 0 }); + } + }, + ); + + it.each(declarationChecks)( + 'checks routeUrl in apps with thousands of routes through $declarations declarations with $version', + async ({ declarations, tsc }) => { + // About 1,800 route keys, since each dynamic page also has a `:param` alias. A + // non-primitive member in Candidate's constraint made `P & Candidate` a cross product + // that TypeScript rejects (TS2590) past ~316 keys, and a deferred path check rejected + // generic helpers (TS2859) past ~1,400. + const pages = Object.fromEntries( + Array.from({ length: 600 }, (_, index) => [ + [`pages/large/s${index}.tsx`, 'export default function Page() { return null; }'], + [`pages/large/d${index}/[id].tsx`, 'export default function Page() { return null; }'], + ]).flat(), + ); + const root = await createFixture({ + extraFiles: { + ...pages, + 'check-large.ts': `import { routeUrl, type RouteOptions, type RoutePath } from 'void/routes'; +routeUrl('/large/s0'); +routeUrl('/large/d0/[id]', { params: { id: 1 } }); +declare const path: RoutePath; +routeUrl(path, {} as any); +function forward

(path: P, options: RouteOptions

) { + return routeUrl(path, options); +} +function forwardIntersectedPath

(path: P & RoutePath, options: any) { + return routeUrl(path, options); +} +// @ts-expect-error unknown routes are still rejected +routeUrl('/large/missing'); +// @ts-expect-error params are still required +routeUrl('/large/d0/[id]'); +void [forward, forwardIntersectedPath]; +`, + }, + }); + expect(typecheck(root, declarations, ['check-large.ts'], {}, tsc)).toEqual({ + output: '', + status: 0, + }); + }, + ); + + it.each(declarationChecks)( + 'uses native option errors and custom path errors through $declarations declarations with $version', + async ({ declarations, tsc }) => { + const cases: Array<[call: string, message: string | RegExp, kind: 'native' | 'custom']> = [ + ["routeUrl('/missing');", 'Unknown route: /missing.', 'custom'], + ["routeUrl('/missing', {});", 'Unknown route: /missing.', 'custom'], + ["routeUrl('/users/42');", 'Unknown route: /users/42.', 'custom'], + ["routeUrl('/users/[id]');", 'Expected 2 arguments, but got 1.', 'native'], + ["routeUrl('/users/[id]', {});", "Property 'params' is missing", 'native'], + [ + "routeUrl('/users/[id]', { query: { page: 1 } });", + "Property 'params' is missing", + 'native', + ], + ["routeUrl('/users/[id]', { params: {} });", "Property 'id' is missing", 'native'], + [ + "routeUrl('/users/[id]', { params: { userId: 42 } });", + "'userId' does not exist", + 'native', + ], + [ + "routeUrl('/users/[id]', { params: { id: 42, extra: 'x' } });", + "'extra' does not exist", + 'native', + ], + [ + "routeUrl('/users/[id]', { params: { id: true } });", + "Type 'boolean' is not assignable to type 'string | number'.", + 'native', + ], + [ + "routeUrl('/about', { params: {} });", + "Type '{}' is not assignable to type 'undefined'.", + 'native', + ], + [ + "routeUrl('/about', { hash: 123 });", + "Type 'number' is not assignable to type 'string'.", + 'native', + ], + [ + "routeUrl('/users/[id]', { params: {} as Record });", + "Property 'id' is missing", + 'native', + ], + [ + "routeUrl('/users/[id]', { params: {} as { id?: string } });", + "Type 'undefined' is not assignable to type 'string | number'.", + 'native', + ], + [ + "routeUrl('/users/[id]', { params: {} as Record & { id: boolean } });", + "Type 'boolean' is not assignable to type 'string | number'.", + 'native', + ], + [ + "routeUrl('/users/[id]', { params: {} as Record & { id: string }, query: { nested: {} } });", + /Type '\{\}' is not assignable to type '.*RouteQueryValue/, + 'native', + ], + [ + "routeUrl('/about', { query: () => 'x' });", + "Index signature for type 'string' is missing", + 'native', + ], + [ + "routeUrl('/about', { query: null });", + "Type 'null' is not assignable to type 'RouteQuery | undefined'.", + 'native', + ], + ["routeUrl('/about', () => 'x');", 'has no properties in common', 'native'], + [ + "routeUrl('/about', { query: { nested: { value: 'x' } } });", + "'value' does not exist", + 'native', + ], + [ + "routeUrl('/about', { query: null as unknown as { q: string } | { filter: { id: number } } });", + "Property 'filter' is incompatible with index signature.", + 'native', + ], + [ + "routeUrl('/users/[id]', { params: { 0: 'missing-id' } });", + "'0' does not exist", + 'native', + ], + ["routeUrl('/about', { 0: 'unknown' });", "'0' does not exist", 'native'], + ["routeUrl('/about', { search: 'x' });", "'search' does not exist", 'native'], + [ + "routeUrl('/users/[id]', undefined);", + "Argument of type 'undefined' is not assignable", + 'native', + ], + ["routeUrl('' as '/about' | '/users/[id]');", 'Expected 2 arguments, but got 1.', 'native'], + ["routeUrl('' as string, {});", "Argument of type 'string' is not assignable", 'native'], + ["routeUrl('' as '/about' | '/missing', {});", 'Unknown route: /missing.', 'custom'], + ["routeUrl('/missing', undefined);", 'Unknown route: /missing.', 'custom'], + ["routeUrl('/missing', {} as unknown);", 'Unknown route: /missing.', 'custom'], + ["routeUrl('/missing', {} as any);", 'Unknown route: /missing.', 'custom'], + [ + "routeUrl('/blog/[category]/[slug]', { params: { category: 'typescript' } });", + "Property 'slug' is missing", + 'native', + ], + ]; + 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, kind], index) => { + expect(diagnostics[index]).toMatch(message); + if (kind === 'native') { + expect(diagnostics[index]).not.toContain('UrlTypeError'); + expect(diagnostics[index]).not.toContain('UrlErrorToken'); + expect(diagnostics[index]).not.toContain('Symbol.toPrimitive'); + expect(diagnostics[index]).not.toMatch( + /not assignable to type '"(?:Missing|Unknown|Invalid|Param|Query|Hash|Options)/, + ); + } else { + // The error names the path the caller wrote, not its widened `string` type. + expect(diagnostics[index]).toMatch(/^Argument of type '"/); + } + }); + expect(output).not.toContain('No overload matches this call'); + expect(output).not.toContain('UrlTypeError'); + expect(output).not.toContain('RouteUrlOptionsInput'); + expect(output).not.toContain('__voidUrlError'); + expect(output).not.toContain('Unknown route: /about.'); + const missingSlug = diagnostics.at(-1)!.trim(); + expect(missingSlug).toBe( + "Property 'slug' is missing in type '{ category: string; }' but required in type '{ category: string | number; slug: string | number; }'.", + ); + }, + ); + + it.each(declarationChecks)( + 'requires options for generic paths through $declarations declarations with $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("Argument of type '[]' is not assignable"); + }, + ); + + 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(typescript6.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..9fed8c120 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,9 @@ 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;'); + const sdkTypes = 'import("void/_route-url-types", { with: { "resolution-mode": "import" } })'; + expect(off).toContain(`export type RouteUrlInput = ${sdkTypes}.RouteUrlInput;`); + expect(off).toContain(`export const routeUrl: typeof ${sdkTypes}.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); }); });