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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/guide/type-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`.
Expand Down
5 changes: 5 additions & 0 deletions packages/void/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions packages/void/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
77 changes: 16 additions & 61 deletions packages/void/src/codegen/route-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, RouteQueryValue | ReadonlyArray<RouteQueryValue>>;',
);
lines.push(' export type RouteOptions<P extends RoutePath> = {');
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 = RoutePath> = P extends RoutePath',
);
lines.push(' ? { pathname: P } & RouteOptions<P>');
lines.push(' : never;');
lines.push(
' type RouteUrlSegment<S extends string> = S extends `:${string}` | `[${string}]` | "*" ? string : S;',
);
lines.push(
' type CheckedRoutePath<P extends string> = P extends `/${infer Segment}/${infer Rest}`',
);
lines.push(' ? Rest extends ""');
lines.push(' ? string extends RouteUrlSegment<Segment> ? never : P');
lines.push(' : P');
lines.push(' : P extends `/${infer Segment}`');
lines.push(' ? string extends RouteUrlSegment<Segment> ? never : P');
lines.push(' : P;');
lines.push(
' type RouteSegmentsUrl<P extends string> = P extends `${infer Segment}/${infer Rest}`',
);
lines.push(' ? `${RouteUrlSegment<Segment>}/${RouteSegmentsUrl<Rest>}`');
lines.push(' : RouteUrlSegment<P>;');
lines.push(
' type RoutePatternUrl<P extends string> = P extends `${infer Prefix}/${"*" | "[...]"}/`',
);
lines.push(' ? `${RouteSegmentsUrl<Prefix>}/` | `${RouteSegmentsUrl<Prefix>}/${string}/`');
lines.push(' : P extends `${infer Prefix}/${"*" | "[...]"}`');
lines.push(
' ? (Prefix extends "" ? "/" : RouteSegmentsUrl<Prefix>) | `${RouteSegmentsUrl<Prefix>}/${string}`',
);
lines.push(' : RouteSegmentsUrl<P>;');
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<CheckedRoutePath<RoutePath | EncodedRoutePath>>;',
` export type RouteOptions<P extends RoutePath> = import(${sdkRoutesModule}).RouteOptions<P>;`,
);
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<P extends RoutePath = RoutePath> = import(${sdkRoutesModule}).RouteDestination<P>;`,
);
lines.push(' : string;');
lines.push(' export type RouteUrlInput = Href | URL | RouteDestination;');
lines.push(' export function routeUrl<P extends RoutePath>(');
lines.push(' path: P,');
lines.push(' ...args: [RoutePathMap[NoInfer<P>]] extends [never]');
lines.push(' ? [options?: RouteOptions<P>]');
lines.push(' : [options: RouteOptions<P>]');
lines.push(' ): RouteUrl;');
lines.push(` export const routeUrl: typeof import(${sdkRoutesModule}).routeUrl;`);
lines.push('');
lines.push(' export interface RouteTypesConfig {');
if (options.typedRoutes) {
Expand Down
124 changes: 117 additions & 7 deletions packages/void/src/runtime/routing/route-url.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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<P extends RoutePath> = [RoutePathMap[P]] extends [never]
? [options?: RouteOptions<P>]
: [options: RouteOptions<P>];
type MissingRouteParam<P extends RoutePath, K extends string> = 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<Params> = keyof {
[K in keyof Params as string extends K ? never : {} extends Pick<Params, K> ? never : K]: unknown;
};
type MissingRouteParamKeys<P extends RoutePath, Params> = Exclude<
RoutePathMap[P] & string,
RequiredParamKeys<Params>
>;
type InvalidRouteParamKeys<P extends RoutePath, Params> = {
[K in RoutePathMap[P] & string]: K extends keyof Params
? [Params[K]] extends [string | number]
? never
: K
: K;
}[RoutePathMap[P] & string];
type RequiredRouteParamError<P extends RoutePath, Params> = [
MissingRouteParamKeys<P, Params>,
] extends [never]
? [InvalidRouteParamKeys<P, Params>] extends [never]
? never
: `Param ${InvalidRouteParamKeys<P, Params>} for route ${P} must be a string or number.`
: MissingRouteParam<P, MissingRouteParamKeys<P, Params>>;
type RouteUrlParamError<P extends RoutePath, O> = [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<P, Params>
: [Exclude<keyof Params, RoutePathMap[P]>] extends [never]
? RequiredRouteParamError<P, Params>
: `Unknown param ${DiagnosticKeyName<Exclude<keyof Params, RoutePathMap[P]>>} 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<P, RoutePathMap[P] & string>;
type RouteUrlQueryError<P extends RoutePath, Query> = [Query] extends [RouteQuery | undefined]
? never
: [
InvalidValueKeys<
Exclude<Query, undefined>,
RouteQueryValue | ReadonlyArray<RouteQueryValue>
>,
] extends [never]
? `Query for route ${P} must be an object with supported query values.`
: `Invalid query param ${DiagnosticKeyName<InvalidValueKeys<Exclude<Query, undefined>, RouteQueryValue | ReadonlyArray<RouteQueryValue>>>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`;
type RouteUrlOptionsError<P extends string, O> = [P] extends [RoutePath]
? O extends undefined
? MissingRouteParam<P, RoutePathMap[P] & string>
: O extends object
? | RouteUrlParamError<P, O>
| ('query' extends keyof O ? RouteUrlQueryError<P, O['query']> : never)
| ('hash' extends keyof O
? [O['hash']] extends [string | undefined]
? never
: `Hash for route ${P} must be a string.`
: never)
| `Unknown routeUrl option: ${DiagnosticKeyName<Exclude<keyof O, 'params' | 'query' | 'hash'>>}. Use params, query, or hash.`
: `Options for route ${P} must be an object with params, query, or hash.`
: never;
type RouteUrlCallError<P extends string, O> = [P] extends [RoutePath]
? [RouteUrlOptionsError<P, O>] extends [never]
? `Invalid options for route ${P}. Pass an object with params, query, or hash.`
: RouteUrlOptionsError<P, O>
: 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<O> = {
[
K in Exclude<keyof O, 'params' | 'query' | 'hash'>
]: UrlTypeError<`Unknown routeUrl option: ${DiagnosticKeyName<K>}. 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<P extends RoutePath>(
path: P,
...args: [RoutePathMap[NoInfer<P>]] extends [never]
? [options?: RouteOptions<P>]
: [options: RouteOptions<P>]
): RouteUrl {
return buildRouteUrl(path, args[0]) as RouteUrl;
export function routeUrl<P extends RoutePath>(path: P, ...args: RouteUrlArgs<NoInfer<P>>): 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 <P> and Parameters<typeof routeUrl<P>> native.
export function routeUrl<P extends RoutePath, S extends RoutePath | (string & {}), O = never>(
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<RouteUrlCallError<S, undefined>>
: S &
([S] extends [RoutePath]
? unknown
: UrlTypeError<RouteUrlCallError<NoInfer<S>, undefined>>),
...args: unknown extends O
? RouteUrlArgs<NoInfer<P>>
: [O] extends [never]
? [options?: never]
: [
options: [O] extends [object]
? ([Exclude<keyof O, 'params' | 'query' | 'hash'>] extends [never]
? RouteUrlCallError<NoInfer<S>, NoInfer<O>>
: UnknownRouteUrlOptions<O>) &
O & { readonly [invalid]: never }
: UrlTypeError<RouteUrlCallError<NoInfer<S>, NoInfer<O>>>,
]
): 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. */
Expand Down
16 changes: 16 additions & 0 deletions packages/void/src/runtime/routing/url-diagnostics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/** An unsatisfied marker for diagnostic fallbacks, never an accepted input. */
export type UrlTypeError<Message extends string> = [Message] extends [never]
? never
: { readonly [K in Message]: never };

/** Inspect every union member, including members with disjoint property names. */
export type InvalidValueKeys<Values, Allowed> = 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> = K extends string | number
? `${K}`
: K extends symbol
? 'symbol'
: never;
Loading
Loading