Skip to content

Commit d4d7ef8

Browse files
committed
fix(routes): improve routeUrl TypeScript diagnostics
1 parent 9a43af6 commit d4d7ef8

4 files changed

Lines changed: 277 additions & 11 deletions

File tree

‎packages/void/src/codegen/route-types.ts‎

Lines changed: 109 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -198,11 +198,115 @@ export function generateRouteTypes(
198198
);
199199
lines.push(' : string;');
200200
lines.push(' export type RouteUrlInput = Href | URL | RouteDestination;');
201-
lines.push(' export function routeUrl<P extends RoutePath>(');
202-
lines.push(' path: P,');
203-
lines.push(' ...args: [RoutePathMap[NoInfer<P>]] extends [never]');
204-
lines.push(' ? [options?: RouteOptions<P>]');
205-
lines.push(' : [options: RouteOptions<P>]');
201+
lines.push(' // Keep route/option shapes visible to editor completion while inferring the');
202+
lines.push(" // caller's input separately, so invalid calls can explain the correction.");
203+
lines.push(
204+
' type RouteUrlError<Message extends string> = { readonly __routeUrlError: Message };',
205+
);
206+
lines.push(' type RouteUrlOptionsInput<P extends RoutePath> = {');
207+
lines.push(
208+
' params?: { [K in RoutePathMap[P] & string]?: unknown } | Record<string, unknown>;',
209+
);
210+
lines.push(' query?: Record<string, unknown>;');
211+
lines.push(' hash?: unknown;');
212+
lines.push(' };');
213+
lines.push(' type RouteUrlArgs<P extends RoutePath> = [RoutePathMap[P]] extends [never]');
214+
lines.push(' ? [options?: RouteOptions<P>]');
215+
lines.push(' : [options: RouteOptions<P>];');
216+
lines.push(
217+
' type MissingRouteParam<P extends RoutePath, K extends string> = P extends RoutePath',
218+
);
219+
lines.push(' ? K extends RoutePathMap[P]');
220+
lines.push(' ? `Missing param ${K} for route ${P}. Pass it in { params: { ... } }.`');
221+
lines.push(' : never');
222+
lines.push(' : never;');
223+
lines.push(' type MissingRouteParamKeys<P extends RoutePath, Params> = {');
224+
lines.push(' [K in RoutePathMap[P] & string]: Params extends Record<K, unknown> ? never : K;');
225+
lines.push(' }[RoutePathMap[P] & string];');
226+
lines.push(' type InvalidRouteParamKeys<P extends RoutePath, Params> = {');
227+
lines.push(
228+
' [K in RoutePathMap[P] & string]: Params extends Record<K, string | number> ? never : K;',
229+
);
230+
lines.push(' }[RoutePathMap[P] & string];');
231+
lines.push(' type InvalidRouteValueKeys<Values, Allowed> = {');
232+
lines.push(' [K in keyof Values]-?: [Values[K]] extends [Allowed] ? never : K;');
233+
lines.push(' }[keyof Values] &');
234+
lines.push(' string;');
235+
lines.push(
236+
' type RouteUrlParamError<P extends RoutePath, O> = [RoutePathMap[P]] extends [never]',
237+
);
238+
lines.push(" ? 'params' extends keyof O");
239+
lines.push(" ? [O['params']] extends [undefined]");
240+
lines.push(' ? never');
241+
lines.push(' : `Route ${P} has no path params. Remove params.`');
242+
lines.push(' : never');
243+
lines.push(' : O extends { params: infer Params }');
244+
lines.push(' ? Params extends object');
245+
lines.push(' ? [Exclude<keyof Params, RoutePathMap[P]>] extends [never]');
246+
lines.push(' ? [MissingRouteParamKeys<P, Params>] extends [never]');
247+
lines.push(' ? [InvalidRouteParamKeys<P, Params>] extends [never]');
248+
lines.push(' ? never');
249+
lines.push(
250+
' : `Param ${InvalidRouteParamKeys<P, Params>} for route ${P} must be a string or number.`',
251+
);
252+
lines.push(' : MissingRouteParam<P, MissingRouteParamKeys<P, Params>>');
253+
lines.push(
254+
' : `Unknown param ${Exclude<keyof Params, RoutePathMap[P]> & string} for route ${P}. Use the parameter names in the route pattern.`',
255+
);
256+
lines.push(
257+
" : `Params for route ${P} must be an object with the route's parameter names.`",
258+
);
259+
lines.push(' : MissingRouteParam<P, RoutePathMap[P] & string>;');
260+
lines.push(
261+
' type RouteUrlQueryError<P extends RoutePath, Query> = [Query] extends [RouteQuery | undefined]',
262+
);
263+
lines.push(' ? never');
264+
lines.push(
265+
' : `Invalid query param ${InvalidRouteValueKeys<Exclude<Query, undefined>, RouteQueryValue | ReadonlyArray<RouteQueryValue>>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`;',
266+
);
267+
lines.push(' type RouteUrlOptionsError<P extends string, O> = [P] extends [RoutePath]');
268+
lines.push(' ? O extends undefined');
269+
lines.push(' ? MissingRouteParam<P, RoutePathMap[P] & string>');
270+
lines.push(' : O extends object');
271+
lines.push(' ?');
272+
lines.push(' | RouteUrlParamError<P, O>');
273+
lines.push(" | ('query' extends keyof O ? RouteUrlQueryError<P, O['query']> : never)");
274+
lines.push(" | ('hash' extends keyof O");
275+
lines.push(" ? [O['hash']] extends [string | undefined]");
276+
lines.push(' ? never');
277+
lines.push(' : `Hash for route ${P} must be a string.`');
278+
lines.push(' : never)');
279+
lines.push(
280+
" | (Exclude<keyof O, 'params' | 'query' | 'hash'> extends infer K extends string",
281+
);
282+
lines.push(' ? `Unknown routeUrl option: ${K}. Use params, query, or hash.`');
283+
lines.push(' : never)');
284+
lines.push(' : `Options for route ${P} must be an object with params, query, or hash.`');
285+
lines.push(' : never;');
286+
lines.push(' type ValidateRouteUrlArgs<P extends string, A extends [options?: unknown]> = [');
287+
lines.push(' RouteUrlOptionsError<P, A[0]>,');
288+
lines.push(' ] extends [never]');
289+
lines.push(' ? unknown');
290+
lines.push(' : RouteUrlOptionsError<P, A[0]>;');
291+
lines.push('');
292+
lines.push(' export function routeUrl<');
293+
lines.push(' P extends RoutePath | (string & {}),');
294+
lines.push(' A extends [options?: unknown] = RouteUrlArgs<Extract<P, RoutePath>>,');
295+
lines.push(' >(');
296+
lines.push(' path: P &');
297+
lines.push(' (');
298+
lines.push(' | RoutePath');
299+
lines.push(' | RouteUrlError<');
300+
lines.push(' string extends NoInfer<P>');
301+
lines.push(" ? 'Pass a route pattern literal to routeUrl(); string is too broad.'");
302+
lines.push(
303+
' : `Unknown route: ${NoInfer<P>}. Pass a registered route pattern as the first argument.`',
304+
);
305+
lines.push(' >');
306+
lines.push(' ),');
307+
lines.push(' ...args: A &');
308+
lines.push(' [options?: RouteUrlOptionsInput<Extract<NoInfer<P>, RoutePath>>] &');
309+
lines.push(' ValidateRouteUrlArgs<NoInfer<P>, NoInfer<A>>');
206310
lines.push(' ): RouteUrl;');
207311
lines.push('');
208312
lines.push(' export interface RouteTypesConfig {');

‎packages/void/src/runtime/routing/route-url.ts‎

Lines changed: 86 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -157,14 +157,94 @@ type UrlOptions = {
157157
hash?: string;
158158
};
159159

160+
// Keep route/option shapes visible to editor completion while inferring the
161+
// caller's input separately, so invalid calls can explain the correction.
162+
type RouteUrlError<Message extends string> = { readonly __routeUrlError: Message };
163+
type RouteUrlOptionsInput<P extends RoutePath> = {
164+
params?: { [K in RoutePathMap[P] & string]?: unknown } | Record<string, unknown>;
165+
query?: Record<string, unknown>;
166+
hash?: unknown;
167+
};
168+
type RouteUrlArgs<P extends RoutePath> = [RoutePathMap[P]] extends [never]
169+
? [options?: RouteOptions<P>]
170+
: [options: RouteOptions<P>];
171+
type MissingRouteParam<P extends RoutePath, K extends string> = P extends RoutePath
172+
? K extends RoutePathMap[P]
173+
? `Missing param ${K} for route ${P}. Pass it in { params: { ... } }.`
174+
: never
175+
: never;
176+
type MissingRouteParamKeys<P extends RoutePath, Params> = {
177+
[K in RoutePathMap[P] & string]: Params extends Record<K, unknown> ? never : K;
178+
}[RoutePathMap[P] & string];
179+
type InvalidRouteParamKeys<P extends RoutePath, Params> = {
180+
[K in RoutePathMap[P] & string]: Params extends Record<K, string | number> ? never : K;
181+
}[RoutePathMap[P] & string];
182+
type InvalidRouteValueKeys<Values, Allowed> = {
183+
[K in keyof Values]-?: [Values[K]] extends [Allowed] ? never : K;
184+
}[keyof Values] &
185+
string;
186+
type RouteUrlParamError<P extends RoutePath, O> = [RoutePathMap[P]] extends [never]
187+
? 'params' extends keyof O
188+
? [O['params']] extends [undefined]
189+
? never
190+
: `Route ${P} has no path params. Remove params.`
191+
: never
192+
: O extends { params: infer Params }
193+
? Params extends object
194+
? [Exclude<keyof Params, RoutePathMap[P]>] extends [never]
195+
? [MissingRouteParamKeys<P, Params>] extends [never]
196+
? [InvalidRouteParamKeys<P, Params>] extends [never]
197+
? never
198+
: `Param ${InvalidRouteParamKeys<P, Params>} for route ${P} must be a string or number.`
199+
: MissingRouteParam<P, MissingRouteParamKeys<P, Params>>
200+
: `Unknown param ${Exclude<keyof Params, RoutePathMap[P]> & string} for route ${P}. Use the parameter names in the route pattern.`
201+
: `Params for route ${P} must be an object with the route's parameter names.`
202+
: MissingRouteParam<P, RoutePathMap[P] & string>;
203+
type RouteUrlQueryError<P extends RoutePath, Query> = [Query] extends [RouteQuery | undefined]
204+
? never
205+
: `Invalid query param ${InvalidRouteValueKeys<Exclude<Query, undefined>, RouteQueryValue | ReadonlyArray<RouteQueryValue>>} for route ${P}. Use a string, number, boolean, null, undefined, or an array of these.`;
206+
type RouteUrlOptionsError<P extends string, O> = [P] extends [RoutePath]
207+
? O extends undefined
208+
? MissingRouteParam<P, RoutePathMap[P] & string>
209+
: O extends object
210+
?
211+
| RouteUrlParamError<P, O>
212+
| ('query' extends keyof O ? RouteUrlQueryError<P, O['query']> : never)
213+
| ('hash' extends keyof O
214+
? [O['hash']] extends [string | undefined]
215+
? never
216+
: `Hash for route ${P} must be a string.`
217+
: never)
218+
| (Exclude<keyof O, 'params' | 'query' | 'hash'> extends infer K extends string
219+
? `Unknown routeUrl option: ${K}. Use params, query, or hash.`
220+
: never)
221+
: `Options for route ${P} must be an object with params, query, or hash.`
222+
: never;
223+
type ValidateRouteUrlArgs<P extends string, A extends [options?: unknown]> = [
224+
RouteUrlOptionsError<P, A[0]>,
225+
] extends [never]
226+
? unknown
227+
: RouteUrlOptionsError<P, A[0]>;
228+
160229
/** Build a relative URL from a known route pattern. */
161-
export function routeUrl<P extends RoutePath>(
162-
path: P,
163-
...args: [RoutePathMap[NoInfer<P>]] extends [never]
164-
? [options?: RouteOptions<P>]
165-
: [options: RouteOptions<P>]
230+
export function routeUrl<
231+
P extends RoutePath | (string & {}),
232+
A extends [options?: unknown] = RouteUrlArgs<Extract<P, RoutePath>>,
233+
>(
234+
path: P &
235+
(
236+
| RoutePath
237+
| RouteUrlError<
238+
string extends NoInfer<P>
239+
? 'Pass a route pattern literal to routeUrl(); string is too broad.'
240+
: `Unknown route: ${NoInfer<P>}. Pass a registered route pattern as the first argument.`
241+
>
242+
),
243+
...args: A &
244+
[options?: RouteUrlOptionsInput<Extract<NoInfer<P>, RoutePath>>] &
245+
ValidateRouteUrlArgs<NoInfer<P>, NoInfer<A>>
166246
): RouteUrl {
167-
return buildRouteUrl(path, args[0]) as RouteUrl;
247+
return buildRouteUrl(path, args[0] as UrlOptions | undefined) as RouteUrl;
168248
}
169249

170250
/** @internal Convert navigation inputs to URL strings without requiring an origin. */

‎packages/void/test/integration/route-url-builder.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,17 @@ routeUrl('/wild/*', { params: { '*': 'a/b' } });
343343
routeUrl('/users/[id]', { params: { id: 123 } });
344344
routeUrl('/files/[...path]', { params: { path: 'docs/start' } });
345345
routeUrl('/wild/[...]', { params: { '*': 'a/b' } });
346+
routeUrl<'/users/[id]'>('/users/[id]', { params: { id: 123 } });
347+
interface UserParams { id: number; }
348+
const userParams: UserParams = { id: 123 };
349+
routeUrl('/users/[id]', { params: userParams });
350+
declare const either: '/about' | '/users/[id]';
351+
routeUrl(either, { params: { id: 123 } });
352+
// @ts-expect-error every possible route's params must be present
353+
routeUrl(either);
354+
declare const optional: [options?: RouteOptions<'/users/[id]'>];
355+
// @ts-expect-error an optional tuple cannot guarantee required params
356+
routeUrl('/users/[id]', ...optional);
346357
// @ts-expect-error bracket patterns require params
347358
routeUrl('/users/[id]');
348359
// @ts-expect-error bracket catch-all patterns require params
@@ -468,6 +479,65 @@ function typecheck(
468479
}
469480

470481
describe('standalone routeUrl utility', () => {
482+
it.each(['generated', 'package'] as const)(
483+
'explains invalid routeUrl calls through the %s declarations',
484+
async (declarations) => {
485+
const cases = [
486+
["routeUrl('/missing');", 'Unknown route: /missing.'],
487+
["routeUrl('/missing', {});", 'Unknown route: /missing.'],
488+
["routeUrl('/users/42');", 'Unknown route: /users/42.'],
489+
["routeUrl('/users/[id]');", 'Missing param id for route /users/[id].'],
490+
["routeUrl('/users/[id]', {});", 'Missing param id for route /users/[id].'],
491+
[
492+
"routeUrl('/users/[id]', { query: { page: 1 } });",
493+
'Missing param id for route /users/[id].',
494+
],
495+
["routeUrl('/users/[id]', { params: {} });", 'Missing param id for route /users/[id].'],
496+
[
497+
"routeUrl('/users/[id]', { params: { userId: 42 } });",
498+
'Unknown param userId for route /users/[id].',
499+
],
500+
[
501+
"routeUrl('/users/[id]', { params: { id: 42, extra: 'x' } });",
502+
'Unknown param extra for route /users/[id].',
503+
],
504+
[
505+
"routeUrl('/users/[id]', { params: { id: true } });",
506+
'Param id for route /users/[id] must be a string or number.',
507+
],
508+
["routeUrl('/about', { params: {} });", 'Route /about has no path params.'],
509+
["routeUrl('/about', { hash: 123 });", 'Hash for route /about must be a string.'],
510+
[
511+
"routeUrl('/about', { query: { nested: { value: 'x' } } });",
512+
'Invalid query param nested for route /about.',
513+
],
514+
["routeUrl('/about', { search: 'x' });", 'Unknown routeUrl option: search.'],
515+
["routeUrl('/users/[id]', undefined);", 'Missing param id for route /users/[id].'],
516+
["routeUrl('' as '/about' | '/users/[id]');", 'Missing param id for route /users/[id].'],
517+
[
518+
"routeUrl('' as string);",
519+
'Pass a route pattern literal to routeUrl(); string is too broad.',
520+
],
521+
];
522+
const root = await createFixture({
523+
extraFiles: {
524+
'check-diagnostics.ts': [
525+
"import { routeUrl } from 'void/routes';",
526+
...cases.map(([call]) => call),
527+
].join('\n'),
528+
},
529+
});
530+
const { output, status } = typecheck(root, declarations, ['check-diagnostics.ts']);
531+
expect(status).toBe(1);
532+
const diagnostics = output
533+
.split(/.*check-diagnostics\.ts\(\d+,\d+\): error TS\d+: /)
534+
.slice(1);
535+
expect(diagnostics).toHaveLength(cases.length);
536+
cases.forEach(([, message], index) => expect(diagnostics[index]).toContain(message));
537+
expect(output).not.toContain('TS2554');
538+
},
539+
);
540+
471541
it.each(['generated', 'package'] as const)(
472542
'preserves HTTP, WebSocket and page action contracts for both syntaxes through %s declarations',
473543
async (declarations) => {

‎packages/void/test/unit/route-url-builder.typecheck.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,13 @@ describe('routeUrl types', () => {
2222
routeUrl('/route-types/files/*', { params: { '*': 'a/b' } });
2323
const options: RouteOptions<'/route-types/:id'> = { params: { id: '123' } };
2424
routeUrl('/route-types/:id', options);
25+
routeUrl<'/route-types/:id'>('/route-types/:id', options);
26+
interface Params {
27+
id: number;
28+
}
29+
const params: Params = { id: 123 };
30+
routeUrl('/route-types/:id', { params });
31+
routeUrl('/route-types', undefined);
2532
});
2633

2734
it('rejects unknown paths and incorrect params', () => {
@@ -31,6 +38,8 @@ describe('routeUrl types', () => {
3138
routeUrl('/route-types/123');
3239
// @ts-expect-error params are required
3340
routeUrl('/route-types/:id');
41+
// @ts-expect-error undefined options cannot bypass required params
42+
routeUrl('/route-types/:id', undefined);
3443
// @ts-expect-error params are required even when other options are provided
3544
routeUrl('/route-types/:id', { query: { page: 1 } });
3645
// @ts-expect-error param names must match
@@ -57,5 +66,8 @@ describe('routeUrl types', () => {
5766
// @ts-expect-error one of the possible routes requires params
5867
routeUrl(path);
5968
routeUrl(path, { params: { id: '123' } });
69+
const optional: [options?: RouteOptions<'/route-types/:id'>] = [];
70+
// @ts-expect-error an optional tuple cannot guarantee required params
71+
routeUrl('/route-types/:id', ...optional);
6072
});
6173
});

0 commit comments

Comments
 (0)