@timber-js/app 0.2.0-alpha.231 → 0.2.0-alpha.233
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/dist/_chunks/{use-query-states-pkDV-jSg.js → use-query-states-D3MMl-KM.js} +12 -12
- package/dist/_chunks/use-query-states-D3MMl-KM.js.map +1 -0
- package/dist/adapters/nitro-presets.d.ts.map +1 -1
- package/dist/adapters/nitro.js +18 -2
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client/internal.js +17 -7
- package/dist/client/internal.js.map +1 -1
- package/dist/client/nuqs-adapter.d.ts.map +1 -1
- package/dist/client/router-types.d.ts +7 -0
- package/dist/client/router-types.d.ts.map +1 -1
- package/dist/client/router.d.ts.map +1 -1
- package/dist/client/use-query-states.d.ts +1 -1
- package/dist/client/use-query-states.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +53 -0
- package/dist/index.js.map +1 -1
- package/dist/plugins/node-flight-builds.d.ts +38 -0
- package/dist/plugins/node-flight-builds.d.ts.map +1 -0
- package/dist/search-params/define.d.ts +37 -17
- package/dist/search-params/define.d.ts.map +1 -1
- package/dist/search-params/index.d.ts +1 -0
- package/dist/search-params/index.d.ts.map +1 -1
- package/dist/search-params/index.js +3 -2
- package/dist/search-params/index.js.map +1 -1
- package/docs/learn/06-typed-params.mdx +33 -0
- package/package.json +2 -2
- package/src/adapters/nitro-presets.ts +14 -0
- package/src/client/nuqs-adapter.tsx +91 -29
- package/src/client/router-types.ts +7 -0
- package/src/client/router.ts +19 -10
- package/src/client/use-query-states.ts +27 -23
- package/src/index.ts +2 -0
- package/src/plugins/node-flight-builds.ts +94 -0
- package/src/search-params/define.ts +37 -17
- package/src/search-params/index.ts +10 -0
- package/dist/_chunks/use-query-states-pkDV-jSg.js.map +0 -1
|
@@ -4,9 +4,10 @@
|
|
|
4
4
|
*
|
|
5
5
|
* nuqs uses framework adapters to control how URL updates are applied.
|
|
6
6
|
* This adapter implements nuqs's UseAdapterHook interface and:
|
|
7
|
-
* -
|
|
8
|
-
* -
|
|
9
|
-
* - Sets timber defaults: shallow: false, scroll: true
|
|
7
|
+
* - Writes the address bar on every update, as nuqs's own adapters do
|
|
8
|
+
* - Then calls router.navigate() for non-shallow updates (the default)
|
|
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,39 +62,66 @@ 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
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
79
|
+
// Every write moves the address bar now, shallow or not, before any
|
|
80
|
+
// server roundtrip. That is the contract nuqs's own adapters keep (Next's
|
|
81
|
+
// writes history and then calls `router.replace`; React Router's writes
|
|
82
|
+
// history and then calls `navigate`), and nuqs core depends on it:
|
|
83
|
+
//
|
|
84
|
+
// - it builds every write from `getSearchParamsSnapshot()` (the address
|
|
85
|
+
// bar), so a second write, to any key, composes on this one;
|
|
86
|
+
// - it keeps a flushed value on screen until the adapter's
|
|
87
|
+
// `searchParams` catch up, but only while the snapshot still holds
|
|
88
|
+
// that value (`acknowledge` in nuqs's throttle queue).
|
|
89
|
+
//
|
|
90
|
+
// timber's router moves the address bar only when a navigation commits,
|
|
91
|
+
// so routing a non-shallow write straight to `router.navigate()` left
|
|
92
|
+
// the snapshot on the old value: nuqs dropped what was just typed and a
|
|
93
|
+
// debounced search box emptied until the response landed (TIM-1625).
|
|
94
|
+
//
|
|
95
|
+
// With the Navigation API, `info: { shallow: true }` tells the navigate
|
|
96
|
+
// handler not to intercept; otherwise the event fired by the write would
|
|
97
|
+
// start an RSC fetch of its own. Both paths reach the router's
|
|
98
|
+
// syncShallowSearch, which re-renders NavigationContext, so there is no
|
|
99
|
+
// local state to set.
|
|
100
|
+
//
|
|
101
|
+
// A push saves the departing entry's scroll position first: the router's
|
|
102
|
+
// own save, in navigate(), would otherwise land on the new entry, and
|
|
103
|
+
// the scroll listener's save is debounced, so Back could restore a
|
|
104
|
+
// stale position.
|
|
105
|
+
if (options.history === 'push') getRouter().saveScrollPosition();
|
|
106
|
+
const navigation = getNavigationApi();
|
|
107
|
+
if (navigation) {
|
|
108
|
+
navigation.navigate(url.toString(), {
|
|
109
|
+
history: options.history === 'push' ? 'push' : 'replace',
|
|
110
|
+
info: { shallow: true },
|
|
111
|
+
});
|
|
89
112
|
} else {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
113
|
+
const method =
|
|
114
|
+
options.history === 'push' ? window.history.pushState : window.history.replaceState;
|
|
115
|
+
method.call(window.history, window.history.state, '', url.toString());
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (!options.shallow) {
|
|
119
|
+
// Non-shallow (timber default): fetch fresh server data for the new
|
|
120
|
+
// search. The entry is already written, so the navigation replaces it
|
|
121
|
+
// whatever `history` asked for.
|
|
122
|
+
void getRouter().navigate(url.pathname + url.search + url.hash, {
|
|
94
123
|
scroll: options.scroll,
|
|
95
|
-
replace:
|
|
124
|
+
replace: true,
|
|
96
125
|
});
|
|
97
126
|
}
|
|
98
127
|
|
|
@@ -100,7 +129,7 @@ function useTimberAdapter(watchKeys: string[]): AdapterInterface {
|
|
|
100
129
|
window.scrollTo({ top: 0 });
|
|
101
130
|
}
|
|
102
131
|
};
|
|
103
|
-
}, []);
|
|
132
|
+
}, [writtenFor]);
|
|
104
133
|
|
|
105
134
|
return {
|
|
106
135
|
searchParams,
|
|
@@ -109,6 +138,39 @@ function useTimberAdapter(watchKeys: string[]): AdapterInterface {
|
|
|
109
138
|
};
|
|
110
139
|
}
|
|
111
140
|
|
|
141
|
+
/**
|
|
142
|
+
* Is the user still on — or still headed for — the route a queued write was
|
|
143
|
+
* made on?
|
|
144
|
+
*
|
|
145
|
+
* Every nuqs adapter answers this for its own router: Next's resets nuqs's
|
|
146
|
+
* queues on popstate and on a navigation nuqs did not start; the React,
|
|
147
|
+
* React Router and TanStack adapters do the same on traversal. timber cannot
|
|
148
|
+
* call that reset (`resetQueues` is not exported from `nuqs/adapters/custom`),
|
|
149
|
+
* so the adapter drops a stale write when it flushes instead.
|
|
150
|
+
*
|
|
151
|
+
* "Where the user is" is the router's in-flight target when there is one, and
|
|
152
|
+
* the address bar otherwise. The pending target matters because timber moves
|
|
153
|
+
* the address bar only at commit: a debounced write landing while a `<Link>`
|
|
154
|
+
* to another route is still fetching would otherwise `navigate()` back to the
|
|
155
|
+
* old route and supersede the click (TIM-1623). Only the pathname is compared.
|
|
156
|
+
* The router's own nuqs navigations keep it, so a search box beside a
|
|
157
|
+
* paginator does not discard its own pending write, and the query string is
|
|
158
|
+
* what the write is about to replace.
|
|
159
|
+
*
|
|
160
|
+
* Both sides go through `parseRouterUrl`, the parse `deriveNavigationState`
|
|
161
|
+
* produces `NavigationContext.pathname` with, so `/café` and `/caf%C3%A9`
|
|
162
|
+
* agree. (Not `deriveNavigationState` itself: its module pulls the segment
|
|
163
|
+
* cache into this one's graph.)
|
|
164
|
+
*
|
|
165
|
+
* Known gap: a Back/Forward between two URLs on the SAME pathname is not
|
|
166
|
+
* detected, so a write queued just before it still lands. nuqs's own adapters
|
|
167
|
+
* drop it.
|
|
168
|
+
*/
|
|
169
|
+
function isStillOn(pathname: string): boolean {
|
|
170
|
+
const target = getRouter().getPendingUrl() ?? window.location.href;
|
|
171
|
+
return (parseRouterUrl(target).pathname || '/') === pathname;
|
|
172
|
+
}
|
|
173
|
+
|
|
112
174
|
/** The entries of `search` whose key is in `keys`; all of them when `keys` is empty. */
|
|
113
175
|
function filterKeys(search: URLSearchParams, keys: string[]): URLSearchParams {
|
|
114
176
|
if (keys.length === 0) return search;
|
|
@@ -200,6 +200,13 @@ export interface RouterInstance {
|
|
|
200
200
|
externalSignal?: AbortSignal,
|
|
201
201
|
direction?: TraverseDirection
|
|
202
202
|
): Promise<void>;
|
|
203
|
+
/**
|
|
204
|
+
* Save the current scroll position into the current history entry, so Back
|
|
205
|
+
* to it restores it. `navigate()` does this itself. Code that pushes a
|
|
206
|
+
* history entry before navigating (the nuqs adapter) calls it first, or
|
|
207
|
+
* the position would be saved onto the entry it just pushed.
|
|
208
|
+
*/
|
|
209
|
+
saveScrollPosition(): void;
|
|
203
210
|
/** Whether a navigation is currently in flight */
|
|
204
211
|
isPending(): boolean;
|
|
205
212
|
/** The URL currently being navigated to, or null if idle */
|
package/src/client/router.ts
CHANGED
|
@@ -112,6 +112,21 @@ export function createRouter(deps: RouterDeps): RouterInstance {
|
|
|
112
112
|
navigate(url, { replace, scroll, _renderTypes: types }),
|
|
113
113
|
});
|
|
114
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Write the current scroll position into the current history entry — the
|
|
117
|
+
* Navigation API's entry state when available, otherwise history.state —
|
|
118
|
+
* and return it. Back restores from there.
|
|
119
|
+
*/
|
|
120
|
+
function saveScrollPosition(): number {
|
|
121
|
+
const scrollY = deps.getScrollY();
|
|
122
|
+
if (deps.saveNavigationEntryScroll) {
|
|
123
|
+
deps.saveNavigationEntryScroll(scrollY);
|
|
124
|
+
} else {
|
|
125
|
+
deps.replaceState({ timber: true, scrollY }, '', deps.getCurrentUrl());
|
|
126
|
+
}
|
|
127
|
+
return scrollY;
|
|
128
|
+
}
|
|
129
|
+
|
|
115
130
|
function navigate(url: string, options: NavigationOptions = {}): NavigationHandle {
|
|
116
131
|
return runAsHandle((endings) => navigateWith(url, options, endings));
|
|
117
132
|
}
|
|
@@ -144,16 +159,9 @@ export function createRouter(deps: RouterDeps): RouterInstance {
|
|
|
144
159
|
// names the page being left (TIM-1232).
|
|
145
160
|
const departingUrl = deps.getCurrentUrl();
|
|
146
161
|
|
|
147
|
-
//
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
// Save the departing page's scroll position — use Navigation API entry
|
|
151
|
-
// state when available, otherwise fall back to history.state.
|
|
152
|
-
if (deps.saveNavigationEntryScroll) {
|
|
153
|
-
deps.saveNavigationEntryScroll(currentScrollY);
|
|
154
|
-
} else {
|
|
155
|
-
deps.replaceState({ timber: true, scrollY: currentScrollY }, '', deps.getCurrentUrl());
|
|
156
|
-
}
|
|
162
|
+
// Save the departing page's scroll position, and keep it for
|
|
163
|
+
// scroll={false} preservation.
|
|
164
|
+
const currentScrollY = saveScrollPosition();
|
|
157
165
|
|
|
158
166
|
// This bundle has been superseded. Every subsequent navigation is a full
|
|
159
167
|
// document load — it is the only way to get code that matches the server,
|
|
@@ -459,6 +467,7 @@ export function createRouter(deps: RouterDeps): RouterInstance {
|
|
|
459
467
|
navigate,
|
|
460
468
|
refresh,
|
|
461
469
|
handlePopState,
|
|
470
|
+
saveScrollPosition: () => void saveScrollPosition(),
|
|
462
471
|
isPending,
|
|
463
472
|
getPendingUrl,
|
|
464
473
|
onPendingChange,
|
|
@@ -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:
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
229
|
-
|
|
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:
|
|
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
|
-
|
|
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';
|
|
@@ -565,6 +566,7 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
|
|
|
565
566
|
return [
|
|
566
567
|
rootSync,
|
|
567
568
|
timberReactResolve(),
|
|
569
|
+
timberNodeFlightBuilds(), // Dev: one (Node, pre-bundled) Flight build per server environment
|
|
568
570
|
timberReactProd(),
|
|
569
571
|
// @vitejs/plugin-react provides React Fast Refresh (state-preserving HMR)
|
|
570
572
|
// for client components via Babel transform. Placed before @vitejs/plugin-rsc
|
|
@@ -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
|
+
}
|
|
@@ -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
|
-
/**
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
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
|
-
/**
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
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)
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-query-states-pkDV-jSg.js","names":["useQueryStates","nuqsUseQueryStates"],"sources":["../../src/search-params/parse-total.ts","../../src/search-params/serialize-equal.ts","../../src/client/use-query-states.ts"],"sourcesContent":["/**\n * parseTotal — invoke a codec over the FULL raw domain.\n *\n * `SearchParamCodec.parse` is documented to be total over\n * `string | string[] | undefined`, because that is exactly what a URL\n * hands it: a param can be absent (`undefined`) or repeated (`string[]`).\n * Timber's own codecs and the Standard Schema bridges honour that.\n *\n * nuqs parsers do not. Their `parse` expects a **present scalar string** —\n * nuqs checks presence itself before ever calling it — so `parseAsBoolean`\n * and `parseAsIsoDate` threw a render-phase 500 on an absent param and\n * `parseAsString` returned an array on a repeated one (TIM-1350).\n *\n * nuqs ships the missing adapter: every parser builder exposes\n * `parseServerSide(value: string | string[] | undefined)`, which maps\n * absent → `null` (or the parser's `withDefault` value), takes the FIRST\n * entry of a repeated param (matching `URLSearchParams.get()`), and wraps\n * the inner `parse` so a throw becomes `null`. That is precisely timber's\n * domain, so we call it in preference to `parse` rather than hand-rolling\n * a second normalization that could disagree with the client hook.\n *\n * Feature detection, not an instanceof check: any codec MAY publish\n * `parseServerSide` to declare \"this is my total entry point\" — it is an\n * optional member of `SearchParamCodec` — and a codec that does not is\n * assumed already total and called through `parse`. Timber codecs and\n * schema bridges take the second branch untouched; several of them rely on\n * `parse(undefined)` to produce their default.\n *\n * **Search params only.** Segment params (`server/param-coercion.ts`) call\n * `codec.parse` directly and must keep doing so: their domain is a value\n * the router matched, never absent, and a codec that REJECTS one is how a\n * route produces a 404. Routing a rejection through nuqs's `safeParse`\n * would turn that 404 into a silent `null` param. The two domains differ\n * in what \"no value\" means, not just in plumbing. Cookies are a third\n * domain (`cookies/define-cookie.ts`) and are likewise untouched.\n *\n * `parseServerSide` carries a `@deprecated` tag in nuqs (it steers users to\n * loaders, which timber does not use). It remains public, typed and\n * exercised; `tests/nuqs-codec-boundary.test.ts` asserts totality for every\n * parser through timber's own API, so a nuqs release that drops it fails\n * loudly rather than silently reinstating the 500s.\n *\n * Design doc: design/23-search-params.md §\"nuqs parsers, made total\"\n */\n\n/**\n * Minimal interface for anything `parseTotal` can dispatch. Only `parse` is\n * required; `parseServerSide` is the optional total entry point. `serialize`\n * is deliberately absent — `parseTotal` never calls it, and requiring it\n * would prevent `SearchParamCodec<T>` (whose serialize returns `string |\n * string[] | null`) from being passed where `Codec<T>` (whose serialize\n * returns `string | null`) is expected.\n */\nexport interface ParseableCodec<T> {\n parse(value: string | string[] | undefined): T;\n parseServerSide?(value: string | string[] | undefined): T;\n}\n\n/**\n * A codec that publishes a total entry point over the raw URL domain.\n *\n * The return is `T`, not `T | null`. This is the entry point timber calls,\n * so whatever it answers IS the field's type. A `null` for an absent param\n * belongs in `T` — a bare nuqs parser is a codec of `string | null`, and\n * `parseAsInteger.withDefault(1)` is a codec of `number`, because nuqs\n * narrows its own `parseServerSide` return to `NonNullable<T>`. Declaring\n * `T | null` here would let a codec annotated `SearchParamCodec<string>`\n * hand back `null` under a non-nullable type (TIM-1350 review).\n */\nexport interface TotalCodec<T> {\n parseServerSide(value: string | string[] | undefined): T;\n}\n\nfunction hasParseServerSide<T>(\n codec: ParseableCodec<T>\n): codec is ParseableCodec<T> & TotalCodec<T> {\n return typeof (codec as Partial<TotalCodec<T>>).parseServerSide === 'function';\n}\n\n/**\n * Parse a raw URL value through a codec, using the codec's total entry\n * point when it publishes one.\n *\n * Returns `T`, from both branches. A `null` for an absent param is part of\n * the codec's own `T` — see TotalCodec above — so this signature does not\n * widen it, and a caller that must handle \"no value\" (`withDefault`) sees\n * it because `T` carries it.\n */\nexport function parseTotal<T>(codec: ParseableCodec<T>, raw: string | string[] | undefined): T {\n return hasParseServerSide(codec) ? codec.parseServerSide(raw) : codec.parse(raw);\n}\n","/**\n * Compare two serialize results for equality. Needed because `string[]`\n * from repeated-key codecs does not compare by reference.\n *\n * Shared between define.ts (buildSearchParams default-omission) and\n * use-query-states.ts (bridgeCodec eq). One source of truth.\n */\nexport function serializedEqual(a: string | string[] | null, b: string | string[] | null): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n }\n return false;\n}\n","/**\n * useQueryStates — client-side hook for URL-synced search params.\n *\n * Delegates to nuqs for URL synchronization, batching, React 19 transitions,\n * and throttled URL writes. Bridges timber's SearchParamCodec protocol to\n * nuqs-compatible parsers.\n *\n * Design doc: design/23-search-params.md §\"Codec Bridge\"\n */\n\n'use client';\n\nimport { useQueryStates as nuqsUseQueryStates } from 'nuqs';\nimport type { MultiParser } from 'nuqs';\nimport type {\n SearchParamCodec,\n SearchParamsDefinition,\n SetParams,\n QueryStatesOptions,\n} from '../search-params/define.ts';\nimport { parseTotal } from '../search-params/parse-total.ts';\nimport { serializedEqual } from '../search-params/serialize-equal.ts';\n\n// ─── Codec Bridge ─────────────────────────────────────────────────\n\n// nuqs's parser contract conflates values timber codecs distinguish:\n// parse() returning null means \"unparseable, substitute defaultValue\",\n// and undefined entries are skipped entirely. Timber codecs can\n// legitimately produce both — bare z.string() yields undefined for absent\n// params (implicit optionality), and a codec may map a present value to\n// null. Wrap those two values in sentinels across the nuqs boundary and\n// unwrap them before handing values back to the caller, so the client\n// hook returns exactly what server-side parse() returns.\n// Unique object references compared by identity — a codec can never\n// produce these from URL input, so user-controlled strings cannot collide\n// with them (unlike string sentinels), and unlike Symbols they survive\n// nuqs's internal string coercion without throwing.\nconst NULL_SENTINEL: object = { timberSentinel: 'null' };\nconst UNDEFINED_SENTINEL: object = { timberSentinel: 'undefined' };\n\nfunction wrapNuqsValue(value: unknown): unknown {\n if (value === null) return NULL_SENTINEL;\n if (value === undefined) return UNDEFINED_SENTINEL;\n return value;\n}\n\nfunction unwrapNuqsValue(value: unknown): unknown {\n if (value === NULL_SENTINEL) return null;\n if (value === UNDEFINED_SENTINEL) return undefined;\n return value;\n}\n\n/**\n * Bridge a timber SearchParamCodec to a nuqs-compatible MultiParser.\n *\n * nuqs parsers: { parse(string) → T|null, serialize?(T) → string, eq?, defaultValue? }\n * timber codecs: { parse(string|string[]|undefined) → T, serialize(T) → string|null }\n *\n * The defaultValue is computed eagerly, through `parseTotal` — the same\n * entry point server-side `parse()` uses, so the hook and the server agree\n * on what an absent param means (a bare nuqs parser answers `null`, not\n * `undefined`; TIM-1350). Codecs are documented to return a default rather\n * than throw, but a throwing codec must not crash every component that\n * mounts the hook — treat its default as undefined and let its error\n * surface from server-side parse() instead.\n *\n * A `null` absent-value is NOT registered as the nuqs default. nuqs\n * already represents an absent key as `null`, so the hook reads the same\n * value either way — but registering it makes `clearOnDefault` fire on\n * `setParams({ q: null })` and delete the key before the bridged\n * `serialize` runs. For a codec that encodes `null` as a real query value\n * (`serialize(null) === 'none'`), that silently disagrees with\n * `buildSearchParams({ q: null })`, which writes it. Same reasoning as\n * `getDefaultSerialized` on the server: a codec with no value for an\n * absent param has no default to register.\n */\nfunction bridgeCodec<T>(codec: SearchParamCodec<T>): MultiParser<T> & { defaultValue: T } {\n let absent: unknown;\n try {\n absent = parseTotal(codec, undefined);\n } catch {\n absent = undefined;\n }\n\n const parser = {\n // `multi`, so nuqs reads the key with `searchParams.getAll()` and hands\n // us EVERY value. A single parser reads `.get()` — the first value only\n // — which is not the domain a timber codec is defined over. The server\n // parses `?tags=a&tags=b` as `['a','b']`; a single parser made the hook\n // answer `['a']` for the same URL, under a declared `string[]` that\n // admitted no such disagreement (TIM-1352). Scalar codecs are unaffected:\n // they receive the array and take `value[0]`, exactly as they do on the\n // server, so first-value-wins is preserved through the same code path\n // rather than through nuqs's reader.\n //\n // nuqs never calls this with an empty array — `isAbsentFromUrl` treats\n // `[]` as absent and answers `defaultValue` directly — which is what\n // keeps the absent case agreeing with the server's `undefined`.\n //\n // Reading every value is only half of it: the values must arrive in the\n // SAME SHAPE the server would have produced, or the divergence just\n // moves. `normalizeRaw` (search-params/define.ts) collapses a\n // single-valued key to a bare string and keeps an array only for a\n // repeated one, so this mirrors that rule exactly. Handing a codec\n // `['3']` where the server hands it `'3'` breaks every codec whose\n // `parse` is written for the scalar case — which is most hand-written\n // ones, contract or no contract.\n type: 'multi' as const,\n // Through parseTotal, not codec.parse. nuqs's own `.withDefault(d)`\n // overrides ONLY `parseServerSide`, so `parseAsInteger.withDefault(1)`\n // on `?page=abc` returned 1 from the server and null from the hook —\n // a divergence the declared non-nullable `number` did not admit.\n parse: (v: readonly string[]) =>\n wrapNuqsValue(parseTotal(codec, v.length === 1 ? v[0] : [...v])),\n serialize: (v: unknown) => {\n const value = unwrapNuqsValue(v);\n if (value === undefined) return [''];\n // TIM-1354: catch TypeError from codecs whose serialize is not total\n // over null (e.g. parseAsIsoDate.serialize(null) → null.toISOString()).\n // Only TypeError — deliberate signals must not be swallowed.\n let result: string | string[] | null;\n try {\n result = codec.serialize(value as T);\n } catch (error) {\n if (error instanceof TypeError) return [''];\n throw error;\n }\n // TIM-1353: pass through string[] from codecs that emit repeated\n // keys. nuqs multi parsers append one key=value per array element.\n if (Array.isArray(result)) return result;\n return [result ?? ''];\n },\n eq: (a: unknown, b: unknown) => {\n if (a === b) return true;\n try {\n return serializedEqual(\n codec.serialize(unwrapNuqsValue(a) as T),\n codec.serialize(unwrapNuqsValue(b) as T)\n );\n } catch {\n return false;\n }\n },\n } as MultiParser<T> & { defaultValue: T };\n\n if (absent !== null) parser.defaultValue = wrapNuqsValue(absent) as T;\n return parser;\n}\n\n/**\n * Collect `withUrlKey` aliases off a codec map.\n *\n * `withUrlKey(codec, 'q')` returns a codec carrying `urlKey: 'q'`, so the map\n * alone is enough to reconstruct the aliases — `defineSearchParams` builds its\n * own `urlKeys` from exactly this property.\n */\nfunction deriveUrlKeys(codecs: Record<string, SearchParamCodec<unknown>>): Record<string, string> {\n const result: Record<string, string> = {};\n for (const key of Object.keys(codecs)) {\n const alias = codecs[key]?.urlKey;\n if (alias) result[key] = alias;\n }\n return result;\n}\n\n/**\n * Bridge an entire codec map to nuqs-compatible parsers.\n */\nfunction bridgeCodecs<T extends Record<string, unknown>>(codecs: {\n [K in keyof T]: SearchParamCodec<T[K]>;\n}) {\n const result: Record<string, MultiParser<unknown> & { defaultValue: unknown }> = {};\n for (const key of Object.keys(codecs)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n result[key] = bridgeCodec(codecs[key as keyof T]) as any;\n }\n return result as { [K in keyof T]: MultiParser<T[K]> & { defaultValue: T[K] } };\n}\n\n// ─── Hook ─────────────────────────────────────────────────────────\n\n/**\n * Read and write typed search params from/to the URL.\n *\n * Delegates to nuqs internally. The timber nuqs adapter (auto-injected in\n * browser-entry.ts) handles RSC navigation on non-shallow updates.\n *\n * Usage:\n * ```ts\n * // Via a SearchParamsDefinition imported from the route's params.ts\n * const [params, setParams] = definition.useQueryStates()\n *\n * // Standalone with inline codecs\n * const [params, setParams] = useQueryStates({\n * page: fromSchema(z.coerce.number().int().min(1).default(1)),\n * })\n * ```\n *\n * There is deliberately no route-string form (`useQueryStates('/products')`).\n * Importing the definition from `params.ts` is the documented way to reach\n * another route's codecs — it needs no runtime registry lookup and so has no\n * \"not registered yet\" failure mode. See design/23-search-params.md\n * §\"Client Access\".\n */\nexport function useQueryStates<T extends Record<string, unknown>>(\n codecs: { [K in keyof T]: SearchParamCodec<T[K]> },\n _options?: QueryStatesOptions,\n urlKeys?: Readonly<Record<string, string>>\n): [T, SetParams<T>] {\n const bridged = bridgeCodecs(codecs);\n\n // Forward hook-level options (shallow, scroll, history) to nuqs.\n // These become the default for all setter calls from this hook instance.\n // Per-call options in setParams(values, opts) override these defaults.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const nuqsOptions: any = {};\n if (_options?.shallow !== undefined) nuqsOptions.shallow = _options.shallow;\n if (_options?.scroll !== undefined) nuqsOptions.scroll = _options.scroll;\n if (_options?.history !== undefined) nuqsOptions.history = _options.history;\n // `withUrlKey` attaches the alias to the codec itself — that is the design's\n // \"URL keys travel with codecs\" principle — so the aliases are derivable\n // here and must be, for the inline codec-map form: nobody passes `urlKeys`\n // on that path, and without this an aliased bundle silently read and wrote\n // the property name instead of the alias. `bindUseQueryStates` still passes\n // the definition's precomputed map, which wins on conflict; it is built from\n // these same codecs, so the two agree by construction rather than by luck.\n const resolvedUrlKeys = { ...deriveUrlKeys(codecs), ...urlKeys };\n if (Object.keys(resolvedUrlKeys).length > 0) {\n nuqsOptions.urlKeys = resolvedUrlKeys;\n }\n\n let values: Record<string, unknown>;\n let setValues: Function;\n try {\n [values, setValues] = nuqsUseQueryStates(bridged, nuqsOptions);\n } catch (err) {\n if (\n err instanceof Error &&\n /Invalid hook call|cannot be called|Cannot read properties of null/i.test(err.message)\n ) {\n throw new Error(\n 'useQueryStates is a client component hook and cannot be called outside a React component. ' +\n 'Use definition.parse(searchParams) in server components instead.'\n );\n }\n throw err;\n }\n\n // Unwrap the null/undefined sentinels the bridge injected (see Codec\n // Bridge above) so callers see exactly what server-side parse() returns.\n // Copy-on-write preserves the identity of nuqs's memoized values object\n // when nothing needs unwrapping.\n let normalized = values;\n for (const key of Object.keys(bridged)) {\n const value = normalized[key];\n if (value === NULL_SENTINEL || value === UNDEFINED_SENTINEL) {\n if (normalized === values) normalized = { ...values };\n normalized[key] = unwrapNuqsValue(value);\n }\n }\n\n // Wrap the nuqs setter to match timber's SetParams<T> signature.\n // nuqs's setter accepts Partial<Nullable<Values>> | UpdaterFn | null.\n // timber's setter accepts Partial<T> with optional SetParamsOptions.\n const setParams: SetParams<T> = (partial, setOptions?) => {\n const nuqsSetOptions: Record<string, unknown> = {};\n if (setOptions?.shallow !== undefined) nuqsSetOptions.shallow = setOptions.shallow;\n if (setOptions?.scroll !== undefined) nuqsSetOptions.scroll = setOptions.scroll;\n if (setOptions?.history !== undefined) nuqsSetOptions.history = setOptions.history;\n // nuqs's update loop skips undefined entries and treats null as a\n // key deletion before serialize runs. Timber semantics:\n // - setParams({ q: undefined }) must clear ?q= (absent = undefined),\n // so explicit undefined maps to a null deletion.\n // - setParams({ q: null }) clears the key only when the codec encodes\n // null as \"omit\" (serialize(null) === null). If the codec encodes\n // null as a real query value, forward the sentinel so the bridged\n // serialize writes it — matching definition.serialize({ q: null }).\n let forwarded: Record<string, unknown> = partial;\n for (const key of Object.keys(partial)) {\n const value = partial[key as keyof T];\n if (value === undefined) {\n if (forwarded === partial) forwarded = { ...partial };\n forwarded[key] = null;\n } else if (value === null) {\n let encoded: string | string[] | null = null;\n try {\n const raw = codecs[key as keyof T]?.serialize(null as T[keyof T]);\n // string[] is non-null, but an empty array carries no value\n encoded = raw === null ? null : Array.isArray(raw) ? (raw.length > 0 ? raw : null) : raw;\n } catch {\n // Codec can't serialize null — treat as a deletion.\n }\n if (encoded !== null) {\n if (forwarded === partial) forwarded = { ...partial };\n forwarded[key] = NULL_SENTINEL;\n }\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n void setValues(forwarded as any, nuqsSetOptions);\n };\n\n return [normalized as T, setParams];\n}\n\n// ─── Definition binding ───────────────────────────────────────────\n\n/**\n * Create a useQueryStates binding for a SearchParamsDefinition.\n * This is used internally by SearchParamsDefinition.useQueryStates().\n */\nexport function bindUseQueryStates<T extends Record<string, unknown>>(\n definition: SearchParamsDefinition<T>\n): (options?: QueryStatesOptions) => [T, SetParams<T>] {\n return (options?: QueryStatesOptions) => {\n return useQueryStates<T>(definition.codecs, options, definition.urlKeys);\n };\n}\n"],"mappings":"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"}
|