@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
@@ -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 { classifyUrlSegment, type UrlSegment } from '../routing/segment-classify.ts';
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
- searchParams?: LinkSearchParamsProp;
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?: LinkSearchParamsProp;
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?: LinkSearchParamsProp;
203
+ searchParams?: SearchParamsArg;
437
204
  }
438
205
  ): LinkOutputProps {
439
206
  const resolvedHref = resolveHref(props.href, props.params, props.searchParams);
@@ -6,7 +6,8 @@
6
6
  * This adapter implements nuqs's UseAdapterHook interface and:
7
7
  * - Calls router.navigate() for non-shallow updates (the default)
8
8
  * - Uses pushState/replaceState directly for shallow updates
9
- * - Sets timber defaults: shallow: false, scroll: true, history: 'push'
9
+ * - Sets timber defaults: shallow: false, scroll: true (history stays nuqs's 'replace')
10
+ * - Drops a rate-limited write that flushes after the user left its route
10
11
  *
11
12
  * Design doc: design/23-search-params.md §"Custom Adapter"
12
13
  */
@@ -23,6 +24,7 @@ import { getRouter } from './router-ref.ts';
23
24
  import { getNavigationApi } from './navigation-api.ts';
24
25
  import { locationSearch } from './location-search.ts';
25
26
  import { useNavigationContext } from './navigation-context.ts';
27
+ import { parseRouterUrl } from './router-url.ts';
26
28
 
27
29
  // ─── Adapter Hook ─────────────────────────────────────────────────
28
30
 
@@ -60,9 +62,17 @@ function useTimberAdapter(watchKeys: string[]): AdapterInterface {
60
62
  }
61
63
  const watched = filterKeys(new URLSearchParams(nav.search), watchKeys).toString();
62
64
  const searchParams = useMemo(() => new URLSearchParams(watched), [watched]);
65
+ const writtenFor = nav.pathname;
63
66
 
67
+ // One `updateUrl` per route this instance has rendered on — keyed on the
68
+ // pathname, not memoized once. nuqs captures the adapter when a write is
69
+ // QUEUED and calls that adapter's `updateUrl` when the write FLUSHES, which
70
+ // under `limitUrlUpdates` (a debounce, a throttle window) can be long after
71
+ // the user left the route. So each queued write carries the route it was
72
+ // written for, and is dropped if that is no longer where the user is.
64
73
  const updateUrl = useMemo(() => {
65
74
  return (search: URLSearchParams, options: Required<AdapterOptions>) => {
75
+ if (!isStillOn(writtenFor)) return;
66
76
  const url = new URL(window.location.href);
67
77
  url.search = renderQueryString(search);
68
78
 
@@ -100,7 +110,7 @@ function useTimberAdapter(watchKeys: string[]): AdapterInterface {
100
110
  window.scrollTo({ top: 0 });
101
111
  }
102
112
  };
103
- }, []);
113
+ }, [writtenFor]);
104
114
 
105
115
  return {
106
116
  searchParams,
@@ -109,6 +119,39 @@ function useTimberAdapter(watchKeys: string[]): AdapterInterface {
109
119
  };
110
120
  }
111
121
 
122
+ /**
123
+ * Is the user still on — or still headed for — the route a queued write was
124
+ * made on?
125
+ *
126
+ * Every nuqs adapter answers this for its own router: Next's resets nuqs's
127
+ * queues on popstate and on a navigation nuqs did not start; the React,
128
+ * React Router and TanStack adapters do the same on traversal. timber cannot
129
+ * call that reset (`resetQueues` is not exported from `nuqs/adapters/custom`),
130
+ * so the adapter drops a stale write when it flushes instead.
131
+ *
132
+ * "Where the user is" is the router's in-flight target when there is one, and
133
+ * the address bar otherwise. The pending target matters because timber moves
134
+ * the address bar only at commit: a debounced write landing while a `<Link>`
135
+ * to another route is still fetching would otherwise `navigate()` back to the
136
+ * old route and supersede the click (TIM-1623). Only the pathname is compared.
137
+ * The router's own nuqs navigations keep it, so a search box beside a
138
+ * paginator does not discard its own pending write, and the query string is
139
+ * what the write is about to replace.
140
+ *
141
+ * Both sides go through `parseRouterUrl`, the parse `deriveNavigationState`
142
+ * produces `NavigationContext.pathname` with, so `/café` and `/caf%C3%A9`
143
+ * agree. (Not `deriveNavigationState` itself: its module pulls the segment
144
+ * cache into this one's graph.)
145
+ *
146
+ * Known gap: a Back/Forward between two URLs on the SAME pathname is not
147
+ * detected, so a write queued just before it still lands. nuqs's own adapters
148
+ * drop it.
149
+ */
150
+ function isStillOn(pathname: string): boolean {
151
+ const target = getRouter().getPendingUrl() ?? window.location.href;
152
+ return (parseRouterUrl(target).pathname || '/') === pathname;
153
+ }
154
+
112
155
  /** The entries of `search` whose key is in `keys`; all of them when `keys` is empty. */
113
156
  function filterKeys(search: URLSearchParams, keys: string[]): URLSearchParams {
114
157
  if (keys.length === 0) return search;
@@ -11,7 +11,7 @@
11
11
  'use client';
12
12
 
13
13
  import { useQueryStates as nuqsUseQueryStates } from 'nuqs';
14
- import type { MultiParser } from 'nuqs';
14
+ import type { MultiParser, SetValues, UseQueryStatesOptions } from 'nuqs';
15
15
  import type {
16
16
  SearchParamCodec,
17
17
  SearchParamsDefinition,
@@ -163,18 +163,25 @@ function deriveUrlKeys(codecs: Record<string, SearchParamCodec<unknown>>): Recor
163
163
  return result;
164
164
  }
165
165
 
166
+ type BridgedParsers = Record<string, MultiParser<unknown> & { defaultValue: unknown }>;
167
+
166
168
  /**
167
169
  * Bridge an entire codec map to nuqs-compatible parsers.
170
+ *
171
+ * Keyed by `string`, not `keyof T`: the per-key types are erased across the
172
+ * nuqs boundary anyway (the hook re-types its values as `T` on the way out),
173
+ * and a string-keyed map is what lets the timber-owned `urlKeys` — a
174
+ * `Record<string, string>` — type-check against nuqs's `UrlKeys<KeyMap>`.
168
175
  */
169
176
  function bridgeCodecs<T extends Record<string, unknown>>(codecs: {
170
177
  [K in keyof T]: SearchParamCodec<T[K]>;
171
- }) {
172
- const result: Record<string, MultiParser<unknown> & { defaultValue: unknown }> = {};
178
+ }): BridgedParsers {
179
+ const result: BridgedParsers = {};
173
180
  for (const key of Object.keys(codecs)) {
174
181
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
175
182
  result[key] = bridgeCodec(codecs[key as keyof T]) as any;
176
183
  }
177
- return result as { [K in keyof T]: MultiParser<T[K]> & { defaultValue: T[K] } };
184
+ return result;
178
185
  }
179
186
 
180
187
  // ─── Hook ─────────────────────────────────────────────────────────
@@ -204,19 +211,11 @@ function bridgeCodecs<T extends Record<string, unknown>>(codecs: {
204
211
  */
205
212
  export function useQueryStates<T extends Record<string, unknown>>(
206
213
  codecs: { [K in keyof T]: SearchParamCodec<T[K]> },
207
- _options?: QueryStatesOptions,
214
+ options?: QueryStatesOptions,
208
215
  urlKeys?: Readonly<Record<string, string>>
209
216
  ): [T, SetParams<T>] {
210
217
  const bridged = bridgeCodecs(codecs);
211
218
 
212
- // Forward hook-level options (shallow, scroll, history) to nuqs.
213
- // These become the default for all setter calls from this hook instance.
214
- // Per-call options in setParams(values, opts) override these defaults.
215
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
216
- const nuqsOptions: any = {};
217
- if (_options?.shallow !== undefined) nuqsOptions.shallow = _options.shallow;
218
- if (_options?.scroll !== undefined) nuqsOptions.scroll = _options.scroll;
219
- if (_options?.history !== undefined) nuqsOptions.history = _options.history;
220
219
  // `withUrlKey` attaches the alias to the codec itself — that is the design's
221
220
  // "URL keys travel with codecs" principle — so the aliases are derivable
222
221
  // here and must be, for the inline codec-map form: nobody passes `urlKeys`
@@ -225,12 +224,20 @@ export function useQueryStates<T extends Record<string, unknown>>(
225
224
  // the definition's precomputed map, which wins on conflict; it is built from
226
225
  // these same codecs, so the two agree by construction rather than by luck.
227
226
  const resolvedUrlKeys = { ...deriveUrlKeys(codecs), ...urlKeys };
228
- if (Object.keys(resolvedUrlKeys).length > 0) {
229
- nuqsOptions.urlKeys = resolvedUrlKeys;
230
- }
227
+
228
+ // Every hook option goes to nuqs whole, so an option nuqs adds later works
229
+ // with no change here (TIM-1623: a field-by-field copy silently dropped
230
+ // `limitUrlUpdates`). These are the defaults for every setter call from
231
+ // this hook; nuqs resolves each write as per-call ?? hook ?? adapter
232
+ // default. `urlKeys` is spread last: timber owns it, and nuqs's `Options`
233
+ // does not declare it, so only an untyped caller could have supplied one.
234
+ const nuqsOptions: Partial<UseQueryStatesOptions<BridgedParsers>> = {
235
+ ...options,
236
+ urlKeys: resolvedUrlKeys,
237
+ };
231
238
 
232
239
  let values: Record<string, unknown>;
233
- let setValues: Function;
240
+ let setValues: SetValues<BridgedParsers>;
234
241
  try {
235
242
  [values, setValues] = nuqsUseQueryStates(bridged, nuqsOptions);
236
243
  } catch (err) {
@@ -262,11 +269,9 @@ export function useQueryStates<T extends Record<string, unknown>>(
262
269
  // Wrap the nuqs setter to match timber's SetParams<T> signature.
263
270
  // nuqs's setter accepts Partial<Nullable<Values>> | UpdaterFn | null.
264
271
  // timber's setter accepts Partial<T> with optional SetParamsOptions.
272
+ // `setOptions` is nuqs's own `Options` and is forwarded untouched — see
273
+ // the hook options above.
265
274
  const setParams: SetParams<T> = (partial, setOptions?) => {
266
- const nuqsSetOptions: Record<string, unknown> = {};
267
- if (setOptions?.shallow !== undefined) nuqsSetOptions.shallow = setOptions.shallow;
268
- if (setOptions?.scroll !== undefined) nuqsSetOptions.scroll = setOptions.scroll;
269
- if (setOptions?.history !== undefined) nuqsSetOptions.history = setOptions.history;
270
275
  // nuqs's update loop skips undefined entries and treats null as a
271
276
  // key deletion before serialize runs. Timber semantics:
272
277
  // - setParams({ q: undefined }) must clear ?q= (absent = undefined),
@@ -296,8 +301,7 @@ export function useQueryStates<T extends Record<string, unknown>>(
296
301
  }
297
302
  }
298
303
  }
299
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
300
- void setValues(forwarded as any, nuqsSetOptions);
304
+ void setValues(forwarded, setOptions);
301
305
  };
302
306
 
303
307
  return [normalized as T, setParams];
package/src/index.ts CHANGED
@@ -37,6 +37,7 @@ import { timberCacheTransform } from './plugins/cache.ts';
37
37
  import { timberRequestDep } from './plugins/request-dep/index.ts';
38
38
  import { timberOptimizePackageImports } from './plugins/optimize-package-imports.ts';
39
39
  import { timberClientInServerPackageDeps } from './plugins/client-in-server-package-deps.ts';
40
+ import { timberNodeFlightBuilds } from './plugins/node-flight-builds.ts';
40
41
  import { timberPrebuilt } from './plugins/prebuilt.ts';
41
42
  import { timberPrerenderSugar } from './plugins/prerender-sugar.ts';
42
43
  import { timberDevAwait } from './plugins/dev-await.ts';
@@ -84,6 +85,8 @@ export type { Metadata, MetadataRoute, MetadataHandler, MetadataResult } from '.
84
85
  *
85
86
  * Each key is a route path pattern. Values have:
86
87
  * segmentParams: shape of URL segment params (e.g. { id: string })
88
+ * href: every URL the route resolves to (e.g. `/products/${string}`) —
89
+ * the return type of `href()` from `@timber-js/app/routes`
87
90
  *
88
91
  * There is no `searchParams` member: since TIM-1343 the framework does not
89
92
  * scan for search-param definitions, so it has nothing to type them with. A
@@ -400,6 +403,7 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
400
403
  '@timber-js/app/cache',
401
404
  '@timber-js/app/search-params',
402
405
  '@timber-js/app/params',
406
+ '@timber-js/app/routes',
403
407
  '@timber-js/app/codec',
404
408
  ];
405
409
 
@@ -562,6 +566,7 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
562
566
  return [
563
567
  rootSync,
564
568
  timberReactResolve(),
569
+ timberNodeFlightBuilds(), // Dev: one (Node, pre-bundled) Flight build per server environment
565
570
  timberReactProd(),
566
571
  // @vitejs/plugin-react provides React Fast Refresh (state-preserving HMR)
567
572
  // for client components via Babel transform. Placed before @vitejs/plugin-rsc
@@ -1,13 +1,20 @@
1
1
  /**
2
- * Client-side registry for schema segment param codecs.
2
+ * The app/schema.ts segment-param codecs, resolved and keyed by bracket form
3
+ * (`'[id]'`, `'[...slug]'`, `'[[...path]]'`).
3
4
  *
4
- * The Link component uses codec `serialize` functions to convert typed
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
- * Populated at startup by the browser entry importing `virtual:timber-schema`.
10
- * Also usable on the server (isomorphic).
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 for use by Link's URL interpolation.
21
- * Called once at startup from the browser entry or RSC entry.
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 setLinkCodecs(codecs: Record<string, Codec<unknown>> | null): void {
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 getLinkCodec(bracketKey: string): Codec<unknown> | undefined {
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
+ }
@@ -14,4 +14,3 @@ export type {
14
14
  ValidDynamicSegmentKeysRegistry,
15
15
  } from './define-schema.ts';
16
16
  export { resolveSchemaCodecs, toBracketKey } from './resolve-schema.ts';
17
- export { setLinkCodecs, getLinkCodec } from './codec-registry.ts';
@@ -0,0 +1,94 @@
1
+ /**
2
+ * timber-node-flight-builds — in dev, the RSC and SSR environments load only
3
+ * the Node builds of React's Flight runtime, pre-bundled.
4
+ *
5
+ * On Node, timber renders Flight with `renderToPipeableStream` and decodes it
6
+ * with `createFromNodeStream` (TIM-1585), which only the `.node` builds of
7
+ * plugin-rsc's vendored `react-server-dom-webpack` export. plugin-rsc itself
8
+ * imports the `.edge` builds: its core (`core/rsc.js`) registers references
9
+ * through `vendor/react-server-dom/server.edge`, and the imports it injects
10
+ * into every 'use client' proxy and 'use server' module reach the edge server
11
+ * and client. Without this plugin each server environment loads both builds
12
+ * of each runtime — React's largest development files, evaluated twice — and
13
+ * the Node ones raw, through Vite's CommonJS transform, because plugin-rsc
14
+ * pre-bundles only the edge ones. Measured on a starter app, a cold
15
+ * `timber dev` spent ~0.7s of CPU (~20%) on this before its first response.
16
+ *
17
+ * Two changes, which only work together:
18
+ * - Every import of a vendored edge build (`…/react-server-dom/server.edge`,
19
+ * `client.edge`, `static.edge`) resolves to its `.node` sibling. Each Node
20
+ * build exports everything its edge build does, plus the Node-stream APIs,
21
+ * so every importer keeps working and shares one instance. In SSR,
22
+ * `react-dom/server` and `react-dom/static` resolve to their `.node` builds
23
+ * the same way.
24
+ * - The server environments' `optimizeDeps.include` lists the `.node` builds
25
+ * in place of the edge ones, so what loads is the pre-bundle. Keeping the
26
+ * edge entries would pre-bundle files nothing loads; dropping them without
27
+ * the redirect would load the edge builds raw.
28
+ *
29
+ * Dev only: the dev server runs both server environments in this Node process
30
+ * (timber-dev-server requires a runnable RSC environment). A build keeps both
31
+ * builds, because the runtime probe (`server/node-streams-platform.ts`), not
32
+ * the build, decides whether it runs on Node.
33
+ *
34
+ * See design/21-dev-server.md §"One Flight Build per Server Environment".
35
+ */
36
+
37
+ import type { Plugin } from 'vite';
38
+
39
+ const SERVER_ENVIRONMENTS = new Set(['rsc', 'ssr']);
40
+
41
+ const VENDOR = '@vitejs/plugin-rsc/vendor/react-server-dom';
42
+
43
+ const VENDOR_EDGE_RE =
44
+ /^@vitejs\/plugin-rsc\/vendor\/react-server-dom\/(server|client|static)\.edge$/;
45
+ const REACT_DOM_SERVER_RE = /^react-dom\/(server|static)(?:\.edge)?$/;
46
+
47
+ /**
48
+ * A server renderer specifier → its Node build; null for anything else.
49
+ *
50
+ * react-dom's bare `react-dom/server` already resolves to the Node build on
51
+ * Node, but as a raw file: once `react-dom/server.node` is pre-bundled it
52
+ * would be a second instance, so it is redirected too. SSR only: in RSC,
53
+ * plugin-rsc rejects `react-dom/server`, and that error must stay.
54
+ */
55
+ function nodeBuildOf(specifier: string, environmentName: string): string | null {
56
+ const vendor = VENDOR_EDGE_RE.exec(specifier);
57
+ if (vendor) return `${VENDOR}/${vendor[1]}.node`;
58
+ if (environmentName !== 'ssr') return null;
59
+ const reactDom = REACT_DOM_SERVER_RE.exec(specifier);
60
+ if (reactDom) return `react-dom/${reactDom[1]}.node`;
61
+ return null;
62
+ }
63
+
64
+ /**
65
+ * The pre-bundle list with each edge build replaced by its Node build. A Node
66
+ * build already listed is not listed twice.
67
+ */
68
+ function withNodeFlightBuilds(include: readonly string[], environmentName: string): string[] {
69
+ return [...new Set(include.map((entry) => nodeBuildOf(entry, environmentName) ?? entry))];
70
+ }
71
+
72
+ export function timberNodeFlightBuilds(): Plugin {
73
+ return {
74
+ name: 'timber-node-flight-builds',
75
+ apply: 'serve',
76
+ // Before Vite's resolver, which would resolve the edge specifier itself.
77
+ enforce: 'pre',
78
+ configEnvironment: {
79
+ // After plugin-rsc has added its edge builds to the list.
80
+ order: 'post',
81
+ handler(name, config) {
82
+ if (!SERVER_ENVIRONMENTS.has(name)) return;
83
+ const deps = config.optimizeDeps;
84
+ if (deps?.include) deps.include = withNodeFlightBuilds(deps.include, name);
85
+ },
86
+ },
87
+ resolveId(source, importer, options) {
88
+ if (!SERVER_ENVIRONMENTS.has(this.environment.name)) return;
89
+ const nodeBuild = nodeBuildOf(source, this.environment.name);
90
+ if (!nodeBuild) return;
91
+ return this.resolve(nodeBuild, importer, { ...options, skipSelf: true });
92
+ },
93
+ };
94
+ }