@timber-js/app 0.2.0-alpha.230 → 0.2.0-alpha.232

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.
Files changed (98) hide show
  1. package/agent-skill.md +13 -0
  2. package/dist/_chunks/{actions-DHum77eH.js → actions-CYjRMpZI.js} +3 -2
  3. package/dist/_chunks/{actions-DHum77eH.js.map → actions-CYjRMpZI.js.map} +1 -1
  4. package/dist/_chunks/{cli-check-B-JZkpBD.js → cli-check-BAKOSTkg.js} +2 -2
  5. package/dist/_chunks/{cli-check-B-JZkpBD.js.map → cli-check-BAKOSTkg.js.map} +1 -1
  6. package/dist/_chunks/codec-registry-C8hOGmZo.js +13 -0
  7. package/dist/_chunks/codec-registry-C8hOGmZo.js.map +1 -0
  8. package/dist/_chunks/{codegen-B9oWkWGf.js → codegen-vaCyFyVN.js} +67 -17
  9. package/dist/_chunks/codegen-vaCyFyVN.js.map +1 -0
  10. package/dist/_chunks/{convention-lint-CrDKERHg.js → convention-lint-D54k6uUM.js} +2 -2
  11. package/dist/_chunks/{convention-lint-CrDKERHg.js.map → convention-lint-D54k6uUM.js.map} +1 -1
  12. package/dist/_chunks/href-BtspoNc9.js +164 -0
  13. package/dist/_chunks/href-BtspoNc9.js.map +1 -0
  14. package/dist/_chunks/href-validation-DNg-zV7u.js +102 -0
  15. package/dist/_chunks/href-validation-DNg-zV7u.js.map +1 -0
  16. package/dist/_chunks/merge-search-params-7o_5yX0L.js +111 -0
  17. package/dist/_chunks/merge-search-params-7o_5yX0L.js.map +1 -0
  18. package/dist/_chunks/{use-query-states-pkDV-jSg.js → use-query-states-D3MMl-KM.js} +12 -12
  19. package/dist/_chunks/use-query-states-D3MMl-KM.js.map +1 -0
  20. package/dist/cli.js +1 -1
  21. package/dist/client/index.d.ts +2 -1
  22. package/dist/client/index.d.ts.map +1 -1
  23. package/dist/client/index.js +4 -122
  24. package/dist/client/index.js.map +1 -1
  25. package/dist/client/internal.js +1 -1
  26. package/dist/client/link.d.ts +4 -25
  27. package/dist/client/link.d.ts.map +1 -1
  28. package/dist/client/nuqs-adapter.d.ts.map +1 -1
  29. package/dist/client/use-query-states.d.ts +1 -1
  30. package/dist/client/use-query-states.d.ts.map +1 -1
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +57 -1
  34. package/dist/index.js.map +1 -1
  35. package/dist/params/codec-registry.d.ts +21 -11
  36. package/dist/params/codec-registry.d.ts.map +1 -1
  37. package/dist/params/index.d.ts +0 -1
  38. package/dist/params/index.d.ts.map +1 -1
  39. package/dist/params/index.js +1 -2
  40. package/dist/params/index.js.map +1 -1
  41. package/dist/plugins/node-flight-builds.d.ts +38 -0
  42. package/dist/plugins/node-flight-builds.d.ts.map +1 -0
  43. package/dist/plugins/shims.d.ts.map +1 -1
  44. package/dist/routes/href.d.ts +124 -0
  45. package/dist/routes/href.d.ts.map +1 -0
  46. package/dist/routes/index.d.ts +4 -0
  47. package/dist/routes/index.d.ts.map +1 -0
  48. package/dist/routes/index.js +8 -0
  49. package/dist/routes/index.js.map +1 -0
  50. package/dist/routing/codegen.d.ts.map +1 -1
  51. package/dist/routing/index.js +1 -1
  52. package/dist/routing/link-codegen.d.ts +39 -8
  53. package/dist/routing/link-codegen.d.ts.map +1 -1
  54. package/dist/search-params/define.d.ts +37 -17
  55. package/dist/search-params/define.d.ts.map +1 -1
  56. package/dist/search-params/index.d.ts +1 -0
  57. package/dist/search-params/index.d.ts.map +1 -1
  58. package/dist/search-params/index.js +3 -2
  59. package/dist/search-params/index.js.map +1 -1
  60. package/dist/server/index.js +1 -1
  61. package/dist/server/internal.js +4 -6
  62. package/dist/server/internal.js.map +1 -1
  63. package/dist/server/param-coercion.d.ts +0 -7
  64. package/dist/server/param-coercion.d.ts.map +1 -1
  65. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  66. package/dist/shared/href.d.ts +88 -0
  67. package/dist/shared/href.d.ts.map +1 -0
  68. package/docs/api/31-api-client.mdx +1 -1
  69. package/docs/api/35-api-typescript.mdx +47 -15
  70. package/docs/learn/06-typed-params.mdx +33 -0
  71. package/docs/learn/07-typed-routes.mdx +75 -10
  72. package/package.json +6 -2
  73. package/src/client/browser-entry/index.ts +4 -4
  74. package/src/client/index.ts +3 -1
  75. package/src/client/link.tsx +5 -238
  76. package/src/client/nuqs-adapter.tsx +45 -2
  77. package/src/client/use-query-states.ts +27 -23
  78. package/src/index.ts +5 -0
  79. package/src/params/codec-registry.ts +24 -11
  80. package/src/params/index.ts +0 -1
  81. package/src/plugins/node-flight-builds.ts +94 -0
  82. package/src/plugins/shims.ts +10 -0
  83. package/src/routes/href.ts +171 -0
  84. package/src/routes/index.ts +10 -0
  85. package/src/routing/codegen.ts +8 -1
  86. package/src/routing/link-codegen.ts +103 -37
  87. package/src/search-params/define.ts +37 -17
  88. package/src/search-params/index.ts +10 -0
  89. package/src/server/param-coercion.ts +5 -23
  90. package/src/server/rsc-entry/index.ts +6 -3
  91. package/src/server/ssr-entry.ts +2 -2
  92. package/src/shared/href.ts +257 -0
  93. package/dist/_chunks/codec-registry-CPc6bjVl.js +0 -20
  94. package/dist/_chunks/codec-registry-CPc6bjVl.js.map +0 -1
  95. package/dist/_chunks/codegen-B9oWkWGf.js.map +0 -1
  96. package/dist/_chunks/href-validation-CEZy1V-k.js +0 -210
  97. package/dist/_chunks/href-validation-CEZy1V-k.js.map +0 -1
  98. package/dist/_chunks/use-query-states-pkDV-jSg.js.map +0 -1
@@ -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';
@@ -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 { formatLinkCatchAllOverloads, formatTypedLinkOverloads } from './link-codegen.ts';
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
 
@@ -42,37 +42,92 @@ import { classifyUrlSegment } from './segment-classify.ts';
42
42
  */
43
43
  export const SEARCH_PARAMS_PROP_TYPE = 'string | Record<string, unknown>';
44
44
 
45
- /** Shared Link base-props type literal used in every emitted call signature. */
46
- export const LINK_BASE_PROPS_TYPE =
47
- "Omit<import('react').AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> & { prefetch?: boolean; scroll?: boolean; preserveSearchParams?: true | string[]; onNavigate?: import('./client/link.js').OnNavigateHandler; children?: import('react').ReactNode }";
45
+ /**
46
+ * Link base props in every emitted call signature: the real `LinkBaseProps`
47
+ * from `@timber-js/app/client`, by reference.
48
+ *
49
+ * Until TIM-1621 this was an inline copy of the type. It drifted —
50
+ * `replace` and `transitionTypes` were never added, so typed `<Link>`
51
+ * rejected both — and its `onNavigate` came from `./client/link.js`, a
52
+ * path relative to `.timber/` that never resolved, so that prop was
53
+ * silently `any`. A reference cannot drift.
54
+ */
55
+ export const LINK_BASE_PROPS_TYPE = "import('@timber-js/app/client').LinkBaseProps";
56
+
57
+ // eslint-disable-next-line no-template-curly-in-string -- codegen output
58
+ const DOLLAR_STRING = '${string}';
48
59
 
49
60
  /**
50
- * Build a TypeScript template literal pattern for a dynamic route.
51
- * e.g. '/products/[id]' → '/products/${string}'
52
- * '/blog/[...slug]' → '/blog/${string}'
53
- * '/docs/[[...path]]' → '/docs/${string}' (also matches /docs)
54
- * '/[org]/[repo]' → '/${string}/${string}'
61
+ * Build the TypeScript type of every URL a route resolves to — a type
62
+ * EXPRESSION, ready to drop into a declaration:
63
+ *
64
+ * '/venues' → '/venues'
65
+ * '/products/[id]' → `/products/${string}`
66
+ * '/img-[id].png' → `/img-${string}.png`
67
+ * '/blog/[...slug]' → `/blog/${string}`
68
+ * '/docs/[[...path]]' → '/docs' | `/docs/${string}`
69
+ * '/[[...path]]' → '/' | `/${string}`
70
+ *
71
+ * An optional catch-all that is omitted drops its segment AND its slash
72
+ * (`interpolateParams('/docs/[[...path]]', {})` is `/docs`), and
73
+ * `/docs/${string}` does not match `/docs` — so a trailing optional
74
+ * catch-all needs the bare prefix as a second member. Before TIM-1621 this
75
+ * emitted only the template, and `<Link href="/docs">` matched no route.
76
+ *
77
+ * Emitted once per route as `Routes[P]['href']` — the type `href()`
78
+ * returns — and reused for `<Link>`'s resolved-template variants, so the
79
+ * two cannot disagree about what a route's URLs look like.
55
80
  */
56
- export function buildResolvedPattern(route: RouteEntry): string | null {
81
+ export function buildResolvedPattern(route: RouteEntry): string {
82
+ return resolvedMembers(route)
83
+ .map((m) => (m.includes(DOLLAR_STRING) ? `\`${m}\`` : `'${m}'`))
84
+ .join(' | ');
85
+ }
86
+
87
+ /**
88
+ * `<Link>`'s query-bearing href type: each member of `buildResolvedPattern`
89
+ * that ends in a static part, with `?${string}` appended. `href(pattern,
90
+ * params, search)` can return such a value, and a `/venues?${string}` is
91
+ * not wide `string`, so without this it would match no Link overload.
92
+ * `null` when every member ends in `${string}` (which already matches a query).
93
+ */
94
+ export function buildResolvedPatternWithQuery(route: RouteEntry): string | null {
95
+ // A member ending in `${string}` already matches any query, so it needs no
96
+ // `?` form — emitting one anyway doubled the union and pushed real routes
97
+ // out of the truncated "not assignable to" list in diagnostics.
98
+ const members = resolvedMembers(route).filter((m) => !m.endsWith(DOLLAR_STRING));
99
+ if (members.length === 0) return null;
100
+ return members.map((m) => `\`${m}?${DOLLAR_STRING}\``).join(' | ');
101
+ }
102
+
103
+ /**
104
+ * Template-literal bodies (no delimiters) of a route's URLs: one per
105
+ * route, plus the bare prefix for a trailing optional catch-all.
106
+ */
107
+ function resolvedMembers(route: RouteEntry): string[] {
57
108
  const parts = route.urlPath.split('/');
58
- const templateParts = parts.map((part) => {
109
+ let omittedAt: number | null = null;
110
+ const templateParts = parts.map((part, i) => {
59
111
  const seg = classifyUrlSegment(part);
60
112
  switch (seg.kind) {
61
- case 'catch-all':
62
113
  case 'optional-catch-all':
63
- // eslint-disable-next-line no-template-curly-in-string -- codegen output
64
- return '${string}';
65
- case 'dynamic': {
66
- const prefix = seg.prefix ?? '';
67
- const suffix = seg.suffix ?? '';
68
- // eslint-disable-next-line no-template-curly-in-string -- codegen output
69
- return `${prefix}\${string}${suffix}`;
70
- }
114
+ // Only a trailing optional catch-all is valid; omitted, it takes the
115
+ // slash before it along.
116
+ if (i === parts.length - 1) omittedAt = i;
117
+ return DOLLAR_STRING;
118
+ case 'catch-all':
119
+ return DOLLAR_STRING;
120
+ case 'dynamic':
121
+ return `${seg.prefix ?? ''}${DOLLAR_STRING}${seg.suffix ?? ''}`;
71
122
  default:
72
123
  return part;
73
124
  }
74
125
  });
75
- return templateParts.join('/');
126
+ const template = templateParts.join('/');
127
+ if (omittedAt === null) return [template];
128
+ // Built from the TEMPLATE parts, so a dynamic ancestor stays a placeholder:
129
+ // `/[org]/[[...path]]` omitted is `/${string}`, not the literal `/[org]`.
130
+ return [templateParts.slice(0, omittedAt).join('/') || '/', template];
76
131
  }
77
132
 
78
133
  /**
@@ -210,9 +265,9 @@ export function formatTypedLinkOverloads(routes: RouteEntry[], hasSchema?: boole
210
265
  const baseProps = LINK_BASE_PROPS_TYPE;
211
266
 
212
267
  // Build the union variants. Each route contributes one variant for the
213
- // pattern href (e.g. '/products/[id]') and, for dynamic routes, an
214
- // additional variant for the resolved-template href (e.g.
215
- // `/products/${string}`).
268
+ // pattern href (e.g. '/products/[id]'); for dynamic routes, a variant for
269
+ // the resolved-template href (e.g. `/products/${string}`); and, when its
270
+ // URL can end in a static part, a query-bearing variant (`/venues?${string}`).
216
271
  //
217
272
  // The PATTERN variant must be listed BEFORE the resolved-template
218
273
  // variant for the same route so that when the user writes the literal
@@ -233,7 +288,7 @@ export function formatTypedLinkOverloads(routes: RouteEntry[], hasSchema?: boole
233
288
 
234
289
  // TIM-1343: searchParams is no longer typed per-route. There is no
235
290
  // convention file to read a definition from, so codegen has nothing to
236
- // narrow with — the value is either a URLSearchParams built by
291
+ // narrow with — the value is either a query string built by
237
292
  // `definition.buildSearchParams()` (which type-checks its own
238
293
  // `Partial<T>` at that call) or a plain String()-coerced record.
239
294
  const searchParamsProp = `searchParams?: ${SEARCH_PARAMS_PROP_TYPE}`;
@@ -244,20 +299,31 @@ export function formatTypedLinkOverloads(routes: RouteEntry[], hasSchema?: boole
244
299
  );
245
300
 
246
301
  // Resolved-template variant SECOND (looser, matches interpolated hrefs).
302
+ // TIM-835: `Record<string, never>` for segmentParams forbids ANY
303
+ // provided keys on the resolved-template variant. Without this, the
304
+ // resolved-template would shadow the pattern variant for literal pattern
305
+ // hrefs (`<Link href="/products/[id]" segmentParams={...} />`) because
306
+ // both variants accept the literal '/products/[id]' and the looser
307
+ // variant would silently swallow segmentParams type errors.
247
308
  if (hasDynamicParams) {
248
- const templatePattern = buildResolvedPattern(route);
249
- if (templatePattern) {
250
- // TIM-835: `Record<string, never>` for segmentParams forbids ANY
251
- // provided keys on the resolved-template variant. Without this,
252
- // the resolved-template would shadow the pattern variant for
253
- // literal pattern hrefs (`<Link href="/products/[id]" segmentParams={...} />`)
254
- // because both variants accept the literal `'/products/[id]'`
255
- // and the looser variant would silently swallow segmentParams
256
- // type errors.
257
- variants.push(
258
- `${baseProps} & { href: \`${templatePattern}\`; segmentParams?: Record<string, never>; ${searchParamsProp} }`
259
- );
260
- }
309
+ variants.push(
310
+ `${baseProps} & { href: ${buildResolvedPattern(route)}; segmentParams?: Record<string, never>; ${searchParamsProp} }`
311
+ );
312
+ }
313
+
314
+ // Query-bearing variant LAST (TIM-1621): what `href(pattern, params,
315
+ // search)` returns, and any literal href with an inline query, for URLs
316
+ // that end in a static part (`/venues?…`, `/docs?…`). It forbids both
317
+ // props: the params are already interpolated and the query is already in
318
+ // the string. A template ending in `${string}` already matches a query,
319
+ // so those routes get no `?` variant — and their template variant still
320
+ // accepts `searchParams`, which template types cannot prevent. That
321
+ // combination throws in `resolveHref` at render instead.
322
+ const queryPattern = buildResolvedPatternWithQuery(route);
323
+ if (queryPattern) {
324
+ variants.push(
325
+ `${baseProps} & { href: ${queryPattern}; segmentParams?: Record<string, never>; searchParams?: never }`
326
+ );
261
327
  }
262
328
  }
263
329
 
@@ -14,6 +14,7 @@ import { useQueryStates as clientUseQueryStates } from '../client/use-query-stat
14
14
  import { fromSchema, isStandardSchema, isCodec } from '../schema-bridge.ts';
15
15
  import type { StandardSchemaV1 } from '../schema-bridge.ts';
16
16
  import type { Codec } from '../codec.ts';
17
+ import type { Options as NuqsOptions } from 'nuqs';
17
18
  // Server-only reference for .get() — avoids pulling server ALS into client
18
19
  // bundles. In client environments, .get() throws before reaching this code
19
20
  // path. The slot lives in its own leaf module so that `request-context.ts`
@@ -94,28 +95,47 @@ export type CodecMap<T extends Record<string, unknown>> = {
94
95
  [K in keyof T]: SearchParamCodec<T[K]>;
95
96
  };
96
97
 
97
- /** Options for useQueryStates setter. */
98
- export interface SetParamsOptions {
99
- /** Update URL without server roundtrip (default: false). */
100
- shallow?: boolean;
101
- /** Scroll to top after update (default: true). */
102
- scroll?: boolean;
103
- /** 'push' (default) or 'replace' for history state. */
104
- history?: 'push' | 'replace';
98
+ /**
99
+ * Options for a `setParams` call: nuqs's own `Options`, passed through
100
+ * whole. Not a hand-copied subset — a whitelist silently dropped
101
+ * `limitUrlUpdates` (debounce/throttle) and `clearOnDefault`, and would drop
102
+ * whatever nuqs adds next (TIM-1623).
103
+ *
104
+ * `urlKeys` is not here: nuqs's `Options` does not carry it (it lives on
105
+ * the hook-only `UseQueryStatesOptions`), and timber owns it — the aliases
106
+ * come from the codecs (`withUrlKey`).
107
+ *
108
+ * The fields re-listed below are not a second declaration: each takes its
109
+ * type from nuqs (`NuqsOptions['shallow']`), and is re-listed only because
110
+ * nuqs's own JSDoc, which an editor shows on hover, is wrong for timber.
111
+ * See design/23-search-params.md §"Options pass through to nuqs".
112
+ */
113
+ export interface SetParamsOptions extends NuqsOptions {
114
+ /**
115
+ * `false` (timber's default): the write is an RSC navigation, so the server
116
+ * renders the new params. `true`: the URL changes with no server request.
117
+ */
118
+ shallow?: NuqsOptions['shallow'];
119
+ /** Scroll to the top after the write. Defaults to `true` in timber. */
120
+ scroll?: NuqsOptions['scroll'];
121
+ /**
122
+ * Forwarded to nuqs, but it does not track the server request in timber.
123
+ * timber runs navigations outside any transition, so `isPending` ends
124
+ * before the RSC fetch does. Use `usePendingNavigation()` for a loading
125
+ * state.
126
+ */
127
+ startTransition?: NuqsOptions['startTransition'];
105
128
  }
106
129
 
107
130
  /** Setter function returned by useQueryStates. */
108
131
  export type SetParams<T> = (values: Partial<T>, options?: SetParamsOptions) => void;
109
132
 
110
- /** Options for useQueryStates hook. */
111
- export interface QueryStatesOptions {
112
- /** Update URL without server roundtrip (default: false). */
113
- shallow?: boolean;
114
- /** Scroll to top after update (default: true). */
115
- scroll?: boolean;
116
- /** 'push' (default) or 'replace' for history state. */
117
- history?: 'push' | 'replace';
118
- }
133
+ /**
134
+ * Options for the `useQueryStates` hook — the defaults for every setter call
135
+ * from that hook instance. Same shape as {@link SetParamsOptions}; a per-call
136
+ * option overrides the hook's.
137
+ */
138
+ export type QueryStatesOptions = SetParamsOptions;
119
139
 
120
140
  /**
121
141
  * A fully typed, composable search params definition.
@@ -25,4 +25,14 @@ export { defineSearchParams } from './define.ts';
25
25
  // Codec wrappers
26
26
  export { withDefault, withUrlKey } from './wrappers.ts';
27
27
 
28
+ // Rate-limit builders for the `limitUrlUpdates` option of useQueryStates /
29
+ // setParams, which go to nuqs whole (TIM-1623). nuqs owns them; timber only
30
+ // re-exports so apps need no direct nuqs import. From `nuqs/server`, not
31
+ // `nuqs`: this entry is in the RSC graph (server components import their
32
+ // definitions from it), and nuqs's main entry is client-only — it is kept
33
+ // out of RSC only because `client/use-query-states.ts` is a client
34
+ // reference. `nuqs/server` carries the same three values with no client-only
35
+ // imports, so the re-export is safe on both sides.
36
+ export { debounce, throttle, defaultRateLimit } from 'nuqs/server';
37
+
28
38
  // Runtime registry (route-scoped useQueryStates)
@@ -12,10 +12,10 @@
12
12
  * See design/07-routing.md §"Where Coercion Runs".
13
13
  */
14
14
 
15
- import type { Codec } from '../codec.ts';
16
15
  import type { SegmentType } from '../routing/types.ts';
17
16
  import { effectiveUrlSegment } from '../routing/segment-classify.ts';
18
17
  import { toBracketKey } from '../params/resolve-schema.ts';
18
+ import { getSchemaCodec, hasSchemaCodecs } from '../params/codec-registry.ts';
19
19
  import type { RouteMatch } from './pipeline.ts';
20
20
  import { normalizeParamValue, type CoercedParams } from '../shared/param-value.ts';
21
21
  /**
@@ -52,22 +52,6 @@ export function warnParamCoercionFailure(
52
52
  }
53
53
  import { isDebug } from './debug.ts';
54
54
 
55
- // ---------------------------------------------------------------------------
56
- // Module-level global codec store (TIM-931)
57
- // ---------------------------------------------------------------------------
58
-
59
- /** Global schema codecs, set once at startup from virtual:timber-schema. */
60
- let _globalCodecs: Record<string, Codec<unknown>> | null = null;
61
-
62
- /**
63
- * Register the global schema codecs. Called once from the RSC entry
64
- * at server startup when app/schema.ts provides segment param codecs.
65
- * @internal
66
- */
67
- export function setGlobalSchemaCodecs(codecs: Record<string, Codec<unknown>> | null): void {
68
- _globalCodecs = codecs;
69
- }
70
-
71
55
  /**
72
56
  * Coerce raw slot params through global schema codecs.
73
57
  *
@@ -97,8 +81,7 @@ export function coerceSlotParams(
97
81
  }>,
98
82
  rawParams: Record<string, string | string[]>
99
83
  ): CoercedParams {
100
- const globalCodecs = _globalCodecs;
101
- if (!globalCodecs) return rawParams;
84
+ if (!hasSchemaCodecs()) return rawParams;
102
85
 
103
86
  const result: CoercedParams = Object.create(null);
104
87
  for (const key of Object.keys(rawParams)) {
@@ -109,7 +92,7 @@ export function coerceSlotParams(
109
92
  const segment = effectiveUrlSegment(node);
110
93
  if (!segment.paramName) continue;
111
94
  const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
112
- const codec = globalCodecs[bracketKey];
95
+ const codec = getSchemaCodec(bracketKey);
113
96
  if (!codec) continue;
114
97
 
115
98
  const key = segment.paramName;
@@ -166,7 +149,6 @@ export function coerceSlotParams(
166
149
  */
167
150
  // eslint-disable-next-line @typescript-eslint/require-await -- see above
168
151
  export async function coerceSegmentParams(match: RouteMatch): Promise<CoercedParams> {
169
- const globalCodecs = _globalCodecs;
170
152
  // Always a null-prototype record, whether or not any segment has a codec.
171
153
  const mergeTarget: CoercedParams = Object.create(null);
172
154
  for (const key of Object.keys(match.rawSegmentParams)) {
@@ -179,7 +161,7 @@ export async function coerceSegmentParams(match: RouteMatch): Promise<CoercedPar
179
161
  // instead of per-segment params.ts files. The global codec map is keyed
180
162
  // by bracket name (e.g. '[id]', '[...slug]') to avoid collisions between
181
163
  // distinct segment types that share a param name.
182
- if (globalCodecs) {
164
+ if (hasSchemaCodecs()) {
183
165
  for (const node of match.segments) {
184
166
  // Read through `effectiveUrlSegment` for the same reason
185
167
  // `coerceSlotParams` does: an intercepting node's own `segmentType` is
@@ -193,7 +175,7 @@ export async function coerceSegmentParams(match: RouteMatch): Promise<CoercedPar
193
175
  const segment = effectiveUrlSegment(node);
194
176
  if (!segment.paramName) continue;
195
177
  const bracketKey = toBracketKey(segment.segmentType, segment.paramName);
196
- const codec = globalCodecs[bracketKey];
178
+ const codec = getSchemaCodec(bracketKey);
197
179
  if (!codec) continue; // no codec in schema → keep raw string
198
180
 
199
181
  const key = segment.paramName;
@@ -48,7 +48,8 @@ import { collectEarlyHintHeaders } from '../early-hints.ts';
48
48
  import { buildClientScripts } from '../html-injectors.ts';
49
49
  import type { InterceptionContext, PipelineConfig, RouteMatch } from '../pipeline.ts';
50
50
  import { createPipeline } from '../pipeline.ts';
51
- import { coerceSegmentParams, setGlobalSchemaCodecs } from '../param-coercion.ts';
51
+ import { coerceSegmentParams } from '../param-coercion.ts';
52
+ import { setSchemaCodecs } from '../../params/codec-registry.ts';
52
53
  import { createMetadataRouteMatcher, createRouteMatcher } from '../route-matcher.ts';
53
54
  import { createInterceptedRouteMatcher } from '../children-interception.ts';
54
55
  import { initDevTracing } from '../tracing.ts';
@@ -516,8 +517,10 @@ export function __timber_generateStaticSite(
516
517
  }
517
518
 
518
519
  // Schema codecs are needed by both the capture path (param coercion) and
519
- // the request handler, so register them unconditionally.
520
- setGlobalSchemaCodecs(globalSchemaCodecs);
520
+ // the request handler, so register them unconditionally. The same store
521
+ // serves URL construction (`href()`, server-rendered `<Link>`), so codecs
522
+ // serialize here exactly as they do in SSR and the browser (TIM-1621).
523
+ setSchemaCodecs(globalSchemaCodecs);
521
524
 
522
525
  // Singleflight timeout protects against deadlocked cache calls — needed
523
526
  // in both capture mode (components may call timber.cache) and normal mode.
@@ -18,8 +18,8 @@ import config from 'virtual:timber-config';
18
18
  // use codec.serialize() instead of String() fallback for URL interpolation.
19
19
  // @ts-expect-error — virtual module provided by timber-routing plugin
20
20
  import schemaCodecs from 'virtual:timber-schema';
21
- import { setLinkCodecs } from '../params/codec-registry.ts';
22
- setLinkCodecs(schemaCodecs);
21
+ import { setSchemaCodecs } from '../params/codec-registry.ts';
22
+ setSchemaCodecs(schemaCodecs);
23
23
  import { createFromReadableStream, createFromNodeStream } from '../rsc-runtime/ssr.ts';
24
24
  import { AsyncLocalStorage } from 'node:async_hooks';
25
25