@timber-js/app 0.2.0-alpha.230 → 0.2.0-alpha.231
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent-skill.md +13 -0
- package/dist/_chunks/{actions-DHum77eH.js → actions-CYjRMpZI.js} +3 -2
- package/dist/_chunks/{actions-DHum77eH.js.map → actions-CYjRMpZI.js.map} +1 -1
- package/dist/_chunks/{cli-check-B-JZkpBD.js → cli-check-BAKOSTkg.js} +2 -2
- package/dist/_chunks/{cli-check-B-JZkpBD.js.map → cli-check-BAKOSTkg.js.map} +1 -1
- package/dist/_chunks/codec-registry-C8hOGmZo.js +13 -0
- package/dist/_chunks/codec-registry-C8hOGmZo.js.map +1 -0
- package/dist/_chunks/{codegen-B9oWkWGf.js → codegen-vaCyFyVN.js} +67 -17
- package/dist/_chunks/codegen-vaCyFyVN.js.map +1 -0
- package/dist/_chunks/{convention-lint-CrDKERHg.js → convention-lint-D54k6uUM.js} +2 -2
- package/dist/_chunks/{convention-lint-CrDKERHg.js.map → convention-lint-D54k6uUM.js.map} +1 -1
- package/dist/_chunks/href-BtspoNc9.js +164 -0
- package/dist/_chunks/href-BtspoNc9.js.map +1 -0
- package/dist/_chunks/href-validation-DNg-zV7u.js +102 -0
- package/dist/_chunks/href-validation-DNg-zV7u.js.map +1 -0
- package/dist/_chunks/merge-search-params-7o_5yX0L.js +111 -0
- package/dist/_chunks/merge-search-params-7o_5yX0L.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/client/index.d.ts +2 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +3 -121
- package/dist/client/index.js.map +1 -1
- package/dist/client/link.d.ts +4 -25
- package/dist/client/link.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/params/codec-registry.d.ts +21 -11
- package/dist/params/codec-registry.d.ts.map +1 -1
- package/dist/params/index.d.ts +0 -1
- package/dist/params/index.d.ts.map +1 -1
- package/dist/params/index.js +1 -2
- package/dist/params/index.js.map +1 -1
- package/dist/plugins/shims.d.ts.map +1 -1
- package/dist/routes/href.d.ts +124 -0
- package/dist/routes/href.d.ts.map +1 -0
- package/dist/routes/index.d.ts +4 -0
- package/dist/routes/index.d.ts.map +1 -0
- package/dist/routes/index.js +8 -0
- package/dist/routes/index.js.map +1 -0
- package/dist/routing/codegen.d.ts.map +1 -1
- package/dist/routing/index.js +1 -1
- package/dist/routing/link-codegen.d.ts +39 -8
- package/dist/routing/link-codegen.d.ts.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/internal.js +4 -6
- package/dist/server/internal.js.map +1 -1
- package/dist/server/param-coercion.d.ts +0 -7
- package/dist/server/param-coercion.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/shared/href.d.ts +88 -0
- package/dist/shared/href.d.ts.map +1 -0
- package/docs/api/31-api-client.mdx +1 -1
- package/docs/api/35-api-typescript.mdx +47 -15
- package/docs/learn/07-typed-routes.mdx +75 -10
- package/package.json +5 -1
- package/src/client/browser-entry/index.ts +4 -4
- package/src/client/index.ts +3 -1
- package/src/client/link.tsx +5 -238
- package/src/index.ts +3 -0
- package/src/params/codec-registry.ts +24 -11
- package/src/params/index.ts +0 -1
- package/src/plugins/shims.ts +10 -0
- package/src/routes/href.ts +171 -0
- package/src/routes/index.ts +10 -0
- package/src/routing/codegen.ts +8 -1
- package/src/routing/link-codegen.ts +103 -37
- package/src/server/param-coercion.ts +5 -23
- package/src/server/rsc-entry/index.ts +6 -3
- package/src/server/ssr-entry.ts +2 -2
- package/src/shared/href.ts +257 -0
- package/dist/_chunks/codec-registry-CPc6bjVl.js +0 -20
- package/dist/_chunks/codec-registry-CPc6bjVl.js.map +0 -1
- package/dist/_chunks/codegen-B9oWkWGf.js.map +0 -1
- package/dist/_chunks/href-validation-CEZy1V-k.js +0 -210
- package/dist/_chunks/href-validation-CEZy1V-k.js.map +0 -1
package/src/client/link.tsx
CHANGED
|
@@ -28,7 +28,7 @@ import {
|
|
|
28
28
|
} from 'react';
|
|
29
29
|
import { flushSync } from 'react-dom';
|
|
30
30
|
import type { LinkFunction } from './index.ts';
|
|
31
|
-
import {
|
|
31
|
+
import { resolveHref, type ParamValue, type SearchParamsArg } from '../shared/href.ts';
|
|
32
32
|
import {
|
|
33
33
|
validateNavigationHref as validateLinkHref,
|
|
34
34
|
isInternalHref,
|
|
@@ -37,7 +37,6 @@ import { LinkStatusContext } from './use-link-status.ts';
|
|
|
37
37
|
import { getRouterOrNull } from './router-ref.ts';
|
|
38
38
|
import { getSsrData } from './ssr-data.ts';
|
|
39
39
|
import { mergePreservedSearchParams } from '../shared/merge-search-params.ts';
|
|
40
|
-
import { getLinkCodec } from '../params/codec-registry.ts';
|
|
41
40
|
import { locationSearch } from './location-search.ts';
|
|
42
41
|
import { stripRscCacheKey } from '../shared/rsc-cache-key.ts';
|
|
43
42
|
import type { LinkStatus } from './use-link-status.ts';
|
|
@@ -164,40 +163,6 @@ export type LinkSegmentParams<T> = {
|
|
|
164
163
|
// augmentation merging — only originally-declared interfaces do.
|
|
165
164
|
// See TIM-624.
|
|
166
165
|
|
|
167
|
-
// ─── searchParams prop shapes ────────────────────────────────────
|
|
168
|
-
//
|
|
169
|
-
// Two shapes, discriminated at runtime by `typeof === 'string'`:
|
|
170
|
-
//
|
|
171
|
-
// 1. Codec-aware (preferred) — a query string built from a definition:
|
|
172
|
-
// searchParams={productParams.buildSearchParams({ page: 2, search: 'boots' })}
|
|
173
|
-
// `buildSearchParams` applies each codec, honours `withUrlKey` aliases,
|
|
174
|
-
// and omits values equal to their default. It is typed `Partial<T>` at
|
|
175
|
-
// the call site, so the definition supplies the type checking.
|
|
176
|
-
//
|
|
177
|
-
// 2. Plain object (escape hatch) — every value is String()-coerced:
|
|
178
|
-
// searchParams={{ ref: 'email' }}
|
|
179
|
-
// No codecs, no aliases. This is for one-off params that have no
|
|
180
|
-
// definition. Passing a *definition's* keys this way is a mistake the
|
|
181
|
-
// types cannot catch: `{ search: 'x' }` emits `?search=x`, where the
|
|
182
|
-
// definition would emit `?q=x`. Prefer (1) whenever a definition exists.
|
|
183
|
-
//
|
|
184
|
-
// Why a STRING and not a URLSearchParams: a Link is routinely rendered by a
|
|
185
|
-
// Server Component, so this prop crosses the RSC Flight boundary before the
|
|
186
|
-
// client Link runs. `URLSearchParams` is iterable, and React serializes any
|
|
187
|
-
// iterable as an array — so the prop arrived as `[['pg','2'], …]`, fell into
|
|
188
|
-
// the plain-object branch, and rendered `?0=pg&0=2`. Strings survive Flight
|
|
189
|
-
// unchanged. (Codex P1 on PR #1021; reproduced against a live dev server.)
|
|
190
|
-
//
|
|
191
|
-
// TIM-1343 removed the third shape — a flat values object resolved against a
|
|
192
|
-
// runtime registry keyed by href. It required scanning a `params.ts`
|
|
193
|
-
// convention file, a generated registry module, and eager imports of every
|
|
194
|
-
// route's definition into all three entries, to save one `.buildSearchParams`
|
|
195
|
-
// call. See design/23-search-params.md §"Link Integration".
|
|
196
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
197
|
-
export type ParamValue = string | number | string[] | { toString(): string; [key: string]: any };
|
|
198
|
-
|
|
199
|
-
type LinkSearchParamsProp = string | Record<string, unknown>;
|
|
200
|
-
|
|
201
166
|
/**
|
|
202
167
|
* Runtime-only loose props used internally by the Link implementation.
|
|
203
168
|
* Not exposed to callers — the public API uses LinkFunction.
|
|
@@ -205,14 +170,15 @@ type LinkSearchParamsProp = string | Record<string, unknown>;
|
|
|
205
170
|
interface LinkRuntimeProps extends LinkBaseProps {
|
|
206
171
|
href: string;
|
|
207
172
|
segmentParams?: Record<string, ParamValue>;
|
|
208
|
-
|
|
173
|
+
// The two shapes are documented on `SearchParamsArg` (../shared/href.ts).
|
|
174
|
+
searchParams?: SearchParamsArg;
|
|
209
175
|
}
|
|
210
176
|
|
|
211
177
|
// Legacy exports for backward compat (used by buildLinkProps, tests, etc.)
|
|
212
178
|
export type LinkPropsWithHref = LinkBaseProps & {
|
|
213
179
|
href: string;
|
|
214
180
|
segmentParams?: never;
|
|
215
|
-
searchParams?:
|
|
181
|
+
searchParams?: SearchParamsArg;
|
|
216
182
|
};
|
|
217
183
|
export type LinkPropsWithParams = LinkRuntimeProps & {
|
|
218
184
|
segmentParams: Record<string, ParamValue>;
|
|
@@ -221,205 +187,6 @@ export type LinkProps = LinkRuntimeProps;
|
|
|
221
187
|
|
|
222
188
|
export { validateLinkHref, isInternalHref };
|
|
223
189
|
|
|
224
|
-
// ─── URL Interpolation ──────────────────────────────────────────
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* Interpolate dynamic segments in a route pattern with actual values.
|
|
228
|
-
* e.g. interpolateParams("/products/[id]", { id: "123" }) → "/products/123"
|
|
229
|
-
*
|
|
230
|
-
* Supports:
|
|
231
|
-
* - [param] → single segment
|
|
232
|
-
* - [...param] → catch-all (joined with /)
|
|
233
|
-
* - [[...param]] → optional catch-all (omitted if undefined/empty)
|
|
234
|
-
*/
|
|
235
|
-
/**
|
|
236
|
-
* Parse a route pattern's path portion into classified segments.
|
|
237
|
-
* Exported for testing. Uses the shared character-based classifier.
|
|
238
|
-
*/
|
|
239
|
-
export function parseSegments(pattern: string): UrlSegment[] {
|
|
240
|
-
return pattern.split('/').filter(Boolean).map(classifyUrlSegment);
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* Resolve a single classified segment into its string representation.
|
|
245
|
-
* Returns null for optional catch-all with no value (filtered out before join).
|
|
246
|
-
*
|
|
247
|
-
* When schema codecs are registered (via virtual:timber-schema), uses
|
|
248
|
-
* codec.serialize() for URL construction instead of plain String().
|
|
249
|
-
*/
|
|
250
|
-
function resolveSegment(
|
|
251
|
-
seg: UrlSegment,
|
|
252
|
-
params: Record<string, ParamValue>,
|
|
253
|
-
pattern: string
|
|
254
|
-
): string | null {
|
|
255
|
-
switch (seg.kind) {
|
|
256
|
-
case 'static':
|
|
257
|
-
return seg.value;
|
|
258
|
-
|
|
259
|
-
case 'optional-catch-all': {
|
|
260
|
-
const value = params[seg.name];
|
|
261
|
-
if (value === undefined || (Array.isArray(value) && value.length === 0)) {
|
|
262
|
-
return null;
|
|
263
|
-
}
|
|
264
|
-
const codec = getLinkCodec(`[[...${seg.name}]]`);
|
|
265
|
-
if (codec) {
|
|
266
|
-
const serialized = codec.serialize(value);
|
|
267
|
-
if (!serialized) return null;
|
|
268
|
-
// Codec returns a path string (may contain '/') — encode each segment
|
|
269
|
-
return serialized.split('/').map(encodeURIComponent).join('/');
|
|
270
|
-
}
|
|
271
|
-
const segments = Array.isArray(value) ? value : [value];
|
|
272
|
-
return segments.map(encodeURIComponent).join('/');
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
case 'catch-all': {
|
|
276
|
-
const value = params[seg.name];
|
|
277
|
-
if (value === undefined) {
|
|
278
|
-
throw new Error(
|
|
279
|
-
`<Link> missing required catch-all param "${seg.name}" for pattern "${pattern}".`
|
|
280
|
-
);
|
|
281
|
-
}
|
|
282
|
-
const codec = getLinkCodec(`[...${seg.name}]`);
|
|
283
|
-
if (codec) {
|
|
284
|
-
const serialized = codec.serialize(value);
|
|
285
|
-
if (!serialized) {
|
|
286
|
-
throw new Error(
|
|
287
|
-
`<Link> catch-all param "${seg.name}" codec returned null for pattern "${pattern}".`
|
|
288
|
-
);
|
|
289
|
-
}
|
|
290
|
-
// Codec returns a path string (may contain '/') — encode each segment
|
|
291
|
-
return serialized.split('/').map(encodeURIComponent).join('/');
|
|
292
|
-
}
|
|
293
|
-
const segments = Array.isArray(value) ? value : [value];
|
|
294
|
-
if (segments.length === 0) {
|
|
295
|
-
throw new Error(
|
|
296
|
-
`<Link> catch-all param "${seg.name}" must have at least one segment for pattern "${pattern}".`
|
|
297
|
-
);
|
|
298
|
-
}
|
|
299
|
-
return segments.map(encodeURIComponent).join('/');
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
case 'dynamic': {
|
|
303
|
-
const value = params[seg.name];
|
|
304
|
-
if (value === undefined) {
|
|
305
|
-
throw new Error(`<Link> missing required param "${seg.name}" for pattern "${pattern}".`);
|
|
306
|
-
}
|
|
307
|
-
if (Array.isArray(value)) {
|
|
308
|
-
throw new Error(
|
|
309
|
-
`<Link> param "${seg.name}" expected a string but received an array for pattern "${pattern}".`
|
|
310
|
-
);
|
|
311
|
-
}
|
|
312
|
-
const codec = getLinkCodec(`[${seg.name}]`);
|
|
313
|
-
const str = codec ? (codec.serialize(value) ?? String(value)) : String(value);
|
|
314
|
-
const encoded = encodeURIComponent(str);
|
|
315
|
-
const prefix = seg.prefix ?? '';
|
|
316
|
-
const suffix = seg.suffix ?? '';
|
|
317
|
-
return prefix + encoded + suffix;
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/**
|
|
323
|
-
* Split a URL pattern into the path portion and any trailing ?query/#hash suffix.
|
|
324
|
-
* Uses URL parsing for correctness rather than manual index arithmetic.
|
|
325
|
-
*/
|
|
326
|
-
function splitPatternSuffix(pattern: string): [path: string, suffix: string] {
|
|
327
|
-
if (!pattern.includes('?') && !pattern.includes('#')) {
|
|
328
|
-
return [pattern, ''];
|
|
329
|
-
}
|
|
330
|
-
const url = new URL(pattern, 'http://x');
|
|
331
|
-
const suffix = url.search + url.hash;
|
|
332
|
-
const path = pattern.slice(0, pattern.length - suffix.length);
|
|
333
|
-
return [path, suffix];
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
export function interpolateParams(pattern: string, params: Record<string, ParamValue>): string {
|
|
337
|
-
const [pathPart, suffix] = splitPatternSuffix(pattern);
|
|
338
|
-
|
|
339
|
-
const resolved = parseSegments(pathPart)
|
|
340
|
-
.map((seg) => resolveSegment(seg, params, pattern))
|
|
341
|
-
.filter((s): s is string => s !== null);
|
|
342
|
-
return ('/' + resolved.join('/') || '/') + suffix;
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
// ─── Resolve Href ───────────────────────────────────────────────
|
|
346
|
-
|
|
347
|
-
/**
|
|
348
|
-
* Resolve the final href string from Link props.
|
|
349
|
-
*
|
|
350
|
-
* Handles:
|
|
351
|
-
* - params interpolation into route patterns
|
|
352
|
-
* - searchParams serialization (see the two shapes documented above)
|
|
353
|
-
* - Validation that searchParams and inline query strings are exclusive
|
|
354
|
-
*/
|
|
355
|
-
/**
|
|
356
|
-
* Tolerate a leading '?'. `buildSearchParams()` never emits one, but callers
|
|
357
|
-
* hand-rolling a query string reasonably might, and silently producing
|
|
358
|
-
* `?%3Fa=b` for it would be a worse failure than accepting both.
|
|
359
|
-
*/
|
|
360
|
-
function stripLeadingQuestionMark(qs: string): string {
|
|
361
|
-
return qs.startsWith('?') ? qs.slice(1) : qs;
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
/**
|
|
365
|
-
* Escape-hatch serialization for a plain object: String()-coerce every
|
|
366
|
-
* value, append arrays as repeated keys, skip null/undefined.
|
|
367
|
-
*
|
|
368
|
-
* Deliberately codec-free and alias-free — see the shape docs above.
|
|
369
|
-
*/
|
|
370
|
-
function coerceToQueryString(values: Record<string, unknown>): string {
|
|
371
|
-
const usp = new URLSearchParams();
|
|
372
|
-
for (const [key, val] of Object.entries(values)) {
|
|
373
|
-
if (val === undefined || val === null) continue;
|
|
374
|
-
if (Array.isArray(val)) {
|
|
375
|
-
for (const item of val) usp.append(key, String(item));
|
|
376
|
-
} else {
|
|
377
|
-
usp.set(key, String(val));
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
return usp.toString();
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
export function resolveHref(
|
|
384
|
-
href: string,
|
|
385
|
-
params?: Record<string, ParamValue>,
|
|
386
|
-
searchParams?: LinkSearchParamsProp
|
|
387
|
-
): string {
|
|
388
|
-
let resolvedPath = href;
|
|
389
|
-
|
|
390
|
-
// Interpolate params if provided
|
|
391
|
-
if (params) {
|
|
392
|
-
resolvedPath = interpolateParams(href, params);
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
// Serialize searchParams if provided
|
|
396
|
-
if (searchParams) {
|
|
397
|
-
// Validate: searchParams prop and inline query string are mutually exclusive
|
|
398
|
-
if (resolvedPath.includes('?')) {
|
|
399
|
-
throw new Error(
|
|
400
|
-
'<Link> received both a searchParams prop and a query string in href. ' +
|
|
401
|
-
'These are mutually exclusive — use one or the other.'
|
|
402
|
-
);
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
// A string is already a serialized query (from
|
|
406
|
-
// `definition.buildSearchParams()`), so it passes through untouched.
|
|
407
|
-
// `typeof` is the only discriminator that survives the RSC Flight
|
|
408
|
-
// boundary — see the shape docs above for what happened when this was
|
|
409
|
-
// an object test.
|
|
410
|
-
const qs =
|
|
411
|
-
typeof searchParams === 'string'
|
|
412
|
-
? stripLeadingQuestionMark(searchParams)
|
|
413
|
-
: coerceToQueryString(searchParams);
|
|
414
|
-
|
|
415
|
-
if (qs) {
|
|
416
|
-
resolvedPath = `${resolvedPath}?${qs}`;
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
return resolvedPath;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
190
|
// ─── Build Props ─────────────────────────────────────────────────
|
|
424
191
|
|
|
425
192
|
interface LinkOutputProps {
|
|
@@ -433,7 +200,7 @@ interface LinkOutputProps {
|
|
|
433
200
|
export function buildLinkProps(
|
|
434
201
|
props: Pick<LinkPropsWithHref, 'href'> & {
|
|
435
202
|
params?: Record<string, ParamValue>;
|
|
436
|
-
searchParams?:
|
|
203
|
+
searchParams?: SearchParamsArg;
|
|
437
204
|
}
|
|
438
205
|
): LinkOutputProps {
|
|
439
206
|
const resolvedHref = resolveHref(props.href, props.params, props.searchParams);
|
package/src/index.ts
CHANGED
|
@@ -84,6 +84,8 @@ export type { Metadata, MetadataRoute, MetadataHandler, MetadataResult } from '.
|
|
|
84
84
|
*
|
|
85
85
|
* Each key is a route path pattern. Values have:
|
|
86
86
|
* segmentParams: shape of URL segment params (e.g. { id: string })
|
|
87
|
+
* href: every URL the route resolves to (e.g. `/products/${string}`) —
|
|
88
|
+
* the return type of `href()` from `@timber-js/app/routes`
|
|
87
89
|
*
|
|
88
90
|
* There is no `searchParams` member: since TIM-1343 the framework does not
|
|
89
91
|
* scan for search-param definitions, so it has nothing to type them with. A
|
|
@@ -400,6 +402,7 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
|
|
|
400
402
|
'@timber-js/app/cache',
|
|
401
403
|
'@timber-js/app/search-params',
|
|
402
404
|
'@timber-js/app/params',
|
|
405
|
+
'@timber-js/app/routes',
|
|
403
406
|
'@timber-js/app/codec',
|
|
404
407
|
];
|
|
405
408
|
|
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* The app/schema.ts segment-param codecs, resolved and keyed by bracket form
|
|
3
|
+
* (`'[id]'`, `'[...slug]'`, `'[[...path]]'`).
|
|
3
4
|
*
|
|
4
|
-
*
|
|
5
|
-
* segment param values back to URL-safe strings. Without this registry,
|
|
6
|
-
* Link falls back to `String(value)` — which works for simple types
|
|
7
|
-
* but breaks for custom codecs (e.g., Date → '2026-04-10').
|
|
5
|
+
* One store per module graph, read in both directions:
|
|
8
6
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* - **parse** — `server/param-coercion.ts` runs `codec.parse` over the raw
|
|
8
|
+
* matcher output before middleware and rendering (RSC).
|
|
9
|
+
* - **serialize** — `shared/href.ts` runs `codec.serialize` when it
|
|
10
|
+
* interpolates a pattern for `<Link>` or `href()` (RSC, SSR, browser).
|
|
11
|
+
*
|
|
12
|
+
* Every entry registers it at startup from `virtual:timber-schema`: the RSC
|
|
13
|
+
* entry, the SSR entry and the browser entry. RSC and SSR are separate Vite
|
|
14
|
+
* module graphs with separate instances of this module, so each must
|
|
15
|
+
* register its own. Until TIM-1621 the RSC entry wrote a second,
|
|
16
|
+
* parse-only store instead, so an `href()` evaluated in a server component
|
|
17
|
+
* silently skipped `codec.serialize` and fell back to `String(value)`.
|
|
11
18
|
*
|
|
12
19
|
* Design doc: design/41-global-params.md §"Link Component"
|
|
13
20
|
*/
|
|
@@ -17,18 +24,24 @@ import type { Codec } from '../codec.ts';
|
|
|
17
24
|
let _codecs: Record<string, Codec<unknown>> | null = null;
|
|
18
25
|
|
|
19
26
|
/**
|
|
20
|
-
* Register the resolved schema codecs
|
|
21
|
-
*
|
|
27
|
+
* Register the resolved schema codecs. Called once at startup by each entry.
|
|
28
|
+
* `null` means the app has no schema — every segment stays a raw string.
|
|
22
29
|
* @internal
|
|
23
30
|
*/
|
|
24
|
-
export function
|
|
31
|
+
export function setSchemaCodecs(codecs: Record<string, Codec<unknown>> | null): void {
|
|
25
32
|
_codecs = codecs;
|
|
26
33
|
}
|
|
27
34
|
|
|
28
35
|
/**
|
|
29
36
|
* Look up a codec by bracket key (e.g. '[id]', '[...slug]').
|
|
30
37
|
* Returns undefined if no schema is registered or the key has no codec.
|
|
38
|
+
* @internal
|
|
31
39
|
*/
|
|
32
|
-
export function
|
|
40
|
+
export function getSchemaCodec(bracketKey: string): Codec<unknown> | undefined {
|
|
33
41
|
return _codecs?.[bracketKey] ?? undefined;
|
|
34
42
|
}
|
|
43
|
+
|
|
44
|
+
/** True once a schema with segment codecs has been registered. @internal */
|
|
45
|
+
export function hasSchemaCodecs(): boolean {
|
|
46
|
+
return _codecs !== null;
|
|
47
|
+
}
|
package/src/params/index.ts
CHANGED
package/src/plugins/shims.ts
CHANGED
|
@@ -54,6 +54,7 @@ export const SUBPATH_SRC_MAP: Record<string, string> = {
|
|
|
54
54
|
'codec': 'codec.ts',
|
|
55
55
|
'cookies': 'cookies/index.ts',
|
|
56
56
|
'params': 'params/index.ts',
|
|
57
|
+
'routes': 'routes/index.ts',
|
|
57
58
|
'search-params': 'search-params/index.ts',
|
|
58
59
|
|
|
59
60
|
'cache/stores/memory': 'cache/stores/memory.ts',
|
|
@@ -267,6 +268,15 @@ export function timberShims(_ctx: PluginContext): Plugin {
|
|
|
267
268
|
return resolve(PKG_ROOT, 'src', 'routing', 'index.ts');
|
|
268
269
|
}
|
|
269
270
|
|
|
271
|
+
// @timber-js/app/routes → src/ in EVERY environment, the browser
|
|
272
|
+
// included. `href()` serializes segment values through the codec
|
|
273
|
+
// registry that browser-entry (src/) fills at startup; resolved to
|
|
274
|
+
// dist/ in the client, it would read a second, never-filled copy and
|
|
275
|
+
// silently skip `codec.serialize` (TIM-1621).
|
|
276
|
+
if (cleanId === '@timber-js/app/routes') {
|
|
277
|
+
return resolve(PKG_ROOT, 'src', 'routes', 'index.ts');
|
|
278
|
+
}
|
|
279
|
+
|
|
270
280
|
// Legacy aliases — vitest and monorepo configs may still reference
|
|
271
281
|
// the old @timber-js/app/server/internal and @timber-js/app/client/internal
|
|
272
282
|
// specifiers via resolve.alias. When those aliases resolve to the
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `href()` — the typed URL builder over the generated `Routes` map.
|
|
3
|
+
*
|
|
4
|
+
* Every internal URL string — `router.push`, `redirect()`, an href passed
|
|
5
|
+
* as a prop, metadata — goes through this one function, so a renamed route
|
|
6
|
+
* directory breaks the build instead of silently breaking a link, and every
|
|
7
|
+
* segment value serializes through its app/schema.ts codec.
|
|
8
|
+
*
|
|
9
|
+
* Isomorphic by construction: no `'use client'`, no React, no ALS. The same
|
|
10
|
+
* call works in a server component, a client component, middleware, an
|
|
11
|
+
* action, or a plain module.
|
|
12
|
+
*
|
|
13
|
+
* Design doc: design/09-typescript.md §"Building URLs — href()".
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { Routes } from '../index.ts';
|
|
17
|
+
import { buildHref, type ParamValue, type SearchParamsArg } from '../shared/href.ts';
|
|
18
|
+
|
|
19
|
+
/** A URL pattern known to the generated route map (groups stripped). */
|
|
20
|
+
export type RoutePattern = keyof Routes;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Every URL `pattern` resolves to, as a template-literal type:
|
|
24
|
+
* `RouteHref<'/products/[id]'>` is `` `/products/${string}` ``.
|
|
25
|
+
*
|
|
26
|
+
* Use it to require a route-shaped string in a prop
|
|
27
|
+
* (`rowHref: RouteHref<'/artists/[artistSlug]'>`). It is a shape check, not
|
|
28
|
+
* a brand: a hand-built `` `/artists/${slug}` `` satisfies it too, which is
|
|
29
|
+
* how `<Link>` already treats literal hrefs. So does any route nested under
|
|
30
|
+
* it (`/artists/${string}` matches `/artists/a/songs/b`).
|
|
31
|
+
*
|
|
32
|
+
* Read from `Routes[P]['href']`, which codegen emits from the same function
|
|
33
|
+
* that builds `<Link>`'s resolved-template variants. Falls back to `string`
|
|
34
|
+
* only for a route map generated before that member existed.
|
|
35
|
+
*/
|
|
36
|
+
export type RouteHref<P extends keyof Routes> = Routes[P] extends {
|
|
37
|
+
href: infer H extends string;
|
|
38
|
+
}
|
|
39
|
+
? H
|
|
40
|
+
: string;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* `RouteHref<P>` with a query. The bare form stays in the union because an
|
|
44
|
+
* empty query (`buildSearchParams({})` → `''`) appends nothing — not a bare
|
|
45
|
+
* `?`.
|
|
46
|
+
*/
|
|
47
|
+
export type RouteHrefWithSearch<P extends keyof Routes> =
|
|
48
|
+
| RouteHref<P>
|
|
49
|
+
| `${RouteHref<P>}?${string}`;
|
|
50
|
+
|
|
51
|
+
type SegmentParamsOf<P extends keyof Routes> = Routes[P] extends { segmentParams: infer S }
|
|
52
|
+
? S
|
|
53
|
+
: never;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The params the PATTERN lets a caller omit: only an optional catch-all,
|
|
57
|
+
* which is always the last segment (`/docs/[[...path]]`). Read from the
|
|
58
|
+
* pattern's syntax, not from the param types — a schema codec may return
|
|
59
|
+
* `T | undefined` for a required `[id]`, and the runtime still throws for
|
|
60
|
+
* a missing `[id]` before any codec runs.
|
|
61
|
+
*/
|
|
62
|
+
type OmittableKeys<P extends keyof Routes, T> = {
|
|
63
|
+
[K in keyof T]: P extends `${string}[[...${K & string}]]` ? K : never;
|
|
64
|
+
}[keyof T];
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Codegen types an optional catch-all as a required key whose value may be
|
|
68
|
+
* `undefined` (`path: string[] | undefined`). Omittable keys become optional;
|
|
69
|
+
* every other key is required and cannot be `undefined` (the runtime throws
|
|
70
|
+
* on it, whatever the codec's type says).
|
|
71
|
+
*/
|
|
72
|
+
type ParamsShape<P extends keyof Routes, T> = {
|
|
73
|
+
[K in keyof T as K extends OmittableKeys<P, T> ? never : K]: Exclude<T[K], undefined>;
|
|
74
|
+
} & {
|
|
75
|
+
[K in keyof T as K extends OmittableKeys<P, T> ? K : never]?: T[K];
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
/** Flatten an intersection so diagnostics print one object type. */
|
|
79
|
+
type Flatten<T> = { [K in keyof T]: T[K] };
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The segment params `href(pattern, …)` takes. `Record<string, never>` for a
|
|
83
|
+
* route with none, so `href('/venues', { x: 1 })` is an error rather than a
|
|
84
|
+
* silent no-op (`{}` would accept any object).
|
|
85
|
+
*/
|
|
86
|
+
export type HrefParams<P extends keyof Routes> = [keyof SegmentParamsOf<P>] extends [never]
|
|
87
|
+
? Record<string, never>
|
|
88
|
+
: Flatten<ParamsShape<P, SegmentParamsOf<P>>>;
|
|
89
|
+
|
|
90
|
+
/** True when `T` is a union of more than one member. */
|
|
91
|
+
type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;
|
|
92
|
+
|
|
93
|
+
/** True when no member of `P` has a required segment param. */
|
|
94
|
+
type EveryParamOptional<P extends keyof Routes> = (
|
|
95
|
+
P extends unknown ? ({} extends HrefParams<P> ? true : false) : never
|
|
96
|
+
) extends true
|
|
97
|
+
? true
|
|
98
|
+
: false;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The arguments after `pattern`. Segment params are required unless every
|
|
102
|
+
* param is optional (none, or only an optional catch-all); the query is
|
|
103
|
+
* always optional.
|
|
104
|
+
*
|
|
105
|
+
* A UNION pattern (`'/products/[id]' | '/venues'`) has no single params
|
|
106
|
+
* shape: `keyof` a union of param objects is `never`, which would read as
|
|
107
|
+
* "no params" and let `href(pattern)` compile, then throw for the dynamic
|
|
108
|
+
* member. So a union takes no segment params at all, and only when none of
|
|
109
|
+
* its members requires one; otherwise the call needs an argument of type
|
|
110
|
+
* `never`, which nothing satisfies. Narrow the pattern before calling.
|
|
111
|
+
*
|
|
112
|
+
* The exception is `P` = all of `keyof Routes`: that is what TS infers when
|
|
113
|
+
* the pattern is NOT a known route, and the arity error would hide the
|
|
114
|
+
* useful one ("'/nope' is not assignable to keyof Routes"). That case takes
|
|
115
|
+
* the permissive shape so the pattern error is the one reported.
|
|
116
|
+
*/
|
|
117
|
+
export type HrefArgs<
|
|
118
|
+
P extends keyof Routes,
|
|
119
|
+
S extends SearchParamsArg | undefined = SearchParamsArg | undefined,
|
|
120
|
+
> =
|
|
121
|
+
true extends IsUnion<P>
|
|
122
|
+
? EveryParamOptional<P> extends true
|
|
123
|
+
? [segmentParams?: undefined, searchParams?: S]
|
|
124
|
+
: [keyof Routes] extends [P]
|
|
125
|
+
? [segmentParams?: undefined, searchParams?: S]
|
|
126
|
+
: [narrow_the_pattern_union_to_one_route: never]
|
|
127
|
+
: {} extends HrefParams<P>
|
|
128
|
+
? [segmentParams?: HrefParams<P>, searchParams?: S]
|
|
129
|
+
: [segmentParams: HrefParams<P>, searchParams?: S];
|
|
130
|
+
|
|
131
|
+
// One signature, not an overload per query shape: with two, a call missing
|
|
132
|
+
// its segment params was reported against whichever overload TS tried last
|
|
133
|
+
// ("Expected 3 arguments"). `S` is inferred from the query argument alone,
|
|
134
|
+
// so segment params are still checked against `HrefParams<P>` directly and
|
|
135
|
+
// keep excess-property errors; a maybe-undefined query distributes to the
|
|
136
|
+
// union of both return shapes.
|
|
137
|
+
/**
|
|
138
|
+
* Build the URL for a route pattern.
|
|
139
|
+
*
|
|
140
|
+
* ```ts
|
|
141
|
+
* href('/venues') // '/venues'
|
|
142
|
+
* href('/products/[id]', { id }) // `/products/${string}`
|
|
143
|
+
* href('/docs/[[...path]]') // '/docs'
|
|
144
|
+
* href('/artists/[artistSlug]', { artistSlug }, artistParams.buildSearchParams({ sort }))
|
|
145
|
+
* ```
|
|
146
|
+
*
|
|
147
|
+
* - **Segment params** are typed from `Routes[pattern]['segmentParams']` —
|
|
148
|
+
* the app/schema.ts codec types when a schema exists — and serialized
|
|
149
|
+
* through those codecs, then percent-encoded per segment.
|
|
150
|
+
* - **Search params** (third argument) take the string
|
|
151
|
+
* `definition.buildSearchParams()` returns (codecs, `withUrlKey` aliases,
|
|
152
|
+
* default omission) or a plain record as the uncodec'd escape hatch. An
|
|
153
|
+
* empty query appends nothing.
|
|
154
|
+
* - The result is validated like every navigation sink: a value that would
|
|
155
|
+
* produce a protocol-relative URL (`/[...slug]` with `['', 'evil.com']` →
|
|
156
|
+
* `//evil.com`) throws instead of returning an open redirect.
|
|
157
|
+
*
|
|
158
|
+
* `href(ROUTE, …)` works with the `ROUTE` constant from a route's generated
|
|
159
|
+
* `./$segment` module whenever that directory is a page or route handler.
|
|
160
|
+
*/
|
|
161
|
+
export function href<P extends keyof Routes, S extends SearchParamsArg | undefined = undefined>(
|
|
162
|
+
pattern: P,
|
|
163
|
+
...args: HrefArgs<P, S>
|
|
164
|
+
): S extends SearchParamsArg ? RouteHrefWithSearch<P> : RouteHref<P>;
|
|
165
|
+
export function href(
|
|
166
|
+
pattern: string,
|
|
167
|
+
segmentParams?: Record<string, ParamValue>,
|
|
168
|
+
searchParams?: SearchParamsArg
|
|
169
|
+
): string {
|
|
170
|
+
return buildHref(pattern, segmentParams, searchParams);
|
|
171
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// @timber-js/app/routes — typed URL construction over the generated route map.
|
|
2
|
+
//
|
|
3
|
+
// Directive-free, React-free and ALS-free: importable from server components,
|
|
4
|
+
// client components, middleware, actions and plain modules alike.
|
|
5
|
+
//
|
|
6
|
+
// See design/09-typescript.md §"Building URLs — href()".
|
|
7
|
+
|
|
8
|
+
export { href } from './href.ts';
|
|
9
|
+
export type { HrefArgs, HrefParams, RouteHref, RouteHrefWithSearch, RoutePattern } from './href.ts';
|
|
10
|
+
export type { SearchParamsArg } from '../shared/href.ts';
|
package/src/routing/codegen.ts
CHANGED
|
@@ -14,7 +14,11 @@ import type { RouteTree, SegmentNode } from './types.ts';
|
|
|
14
14
|
import type { ParamEntry, RouteEntry } from './codegen-types.ts';
|
|
15
15
|
import { buildSchemaParamType } from './codegen-shared.ts';
|
|
16
16
|
import { effectiveUrlSegment, type UrlSegmentIdentity } from './segment-classify.ts';
|
|
17
|
-
import {
|
|
17
|
+
import {
|
|
18
|
+
buildResolvedPattern,
|
|
19
|
+
formatLinkCatchAllOverloads,
|
|
20
|
+
formatTypedLinkOverloads,
|
|
21
|
+
} from './link-codegen.ts';
|
|
18
22
|
|
|
19
23
|
/** Options for route map generation. */
|
|
20
24
|
export interface CodegenOptions {
|
|
@@ -373,6 +377,9 @@ function formatDeclarationFile(
|
|
|
373
377
|
|
|
374
378
|
lines.push(` '${route.urlPath}': {`);
|
|
375
379
|
lines.push(` segmentParams: ${paramsType}`);
|
|
380
|
+
// TIM-1621: every URL the route resolves to — what `href()` returns.
|
|
381
|
+
// Built by the same function as `<Link>`'s resolved-template variants.
|
|
382
|
+
lines.push(` href: ${buildResolvedPattern(route)}`);
|
|
376
383
|
lines.push(` }`);
|
|
377
384
|
}
|
|
378
385
|
|