@timber-js/app 0.2.0-alpha.231 → 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.
- 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/client/index.js +1 -1
- package/dist/client/internal.js +1 -1
- package/dist/client/nuqs-adapter.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/client/nuqs-adapter.tsx +45 -2
- 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
|
@@ -0,0 +1,38 @@
|
|
|
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
|
+
import type { Plugin } from 'vite';
|
|
37
|
+
export declare function timberNodeFlightBuilds(): Plugin;
|
|
38
|
+
//# sourceMappingURL=node-flight-builds.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-flight-builds.d.ts","sourceRoot":"","sources":["../../src/plugins/node-flight-builds.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAmCnC,wBAAgB,sBAAsB,IAAI,MAAM,CAsB/C"}
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import type { StandardSchemaV1 } from '../schema-bridge.ts';
|
|
13
13
|
import type { Codec } from '../codec.ts';
|
|
14
|
+
import type { Options as NuqsOptions } from 'nuqs';
|
|
14
15
|
/**
|
|
15
16
|
* A codec that converts between URL string values and typed values.
|
|
16
17
|
*
|
|
@@ -74,26 +75,45 @@ export type InferCodec<C> = C extends SearchParamCodec<infer T> ? T : never;
|
|
|
74
75
|
export type CodecMap<T extends Record<string, unknown>> = {
|
|
75
76
|
[K in keyof T]: SearchParamCodec<T[K]>;
|
|
76
77
|
};
|
|
77
|
-
/**
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
78
|
+
/**
|
|
79
|
+
* Options for a `setParams` call: nuqs's own `Options`, passed through
|
|
80
|
+
* whole. Not a hand-copied subset — a whitelist silently dropped
|
|
81
|
+
* `limitUrlUpdates` (debounce/throttle) and `clearOnDefault`, and would drop
|
|
82
|
+
* whatever nuqs adds next (TIM-1623).
|
|
83
|
+
*
|
|
84
|
+
* `urlKeys` is not here: nuqs's `Options` does not carry it (it lives on
|
|
85
|
+
* the hook-only `UseQueryStatesOptions`), and timber owns it — the aliases
|
|
86
|
+
* come from the codecs (`withUrlKey`).
|
|
87
|
+
*
|
|
88
|
+
* The fields re-listed below are not a second declaration: each takes its
|
|
89
|
+
* type from nuqs (`NuqsOptions['shallow']`), and is re-listed only because
|
|
90
|
+
* nuqs's own JSDoc, which an editor shows on hover, is wrong for timber.
|
|
91
|
+
* See design/23-search-params.md §"Options pass through to nuqs".
|
|
92
|
+
*/
|
|
93
|
+
export interface SetParamsOptions extends NuqsOptions {
|
|
94
|
+
/**
|
|
95
|
+
* `false` (timber's default): the write is an RSC navigation, so the server
|
|
96
|
+
* renders the new params. `true`: the URL changes with no server request.
|
|
97
|
+
*/
|
|
98
|
+
shallow?: NuqsOptions['shallow'];
|
|
99
|
+
/** Scroll to the top after the write. Defaults to `true` in timber. */
|
|
100
|
+
scroll?: NuqsOptions['scroll'];
|
|
101
|
+
/**
|
|
102
|
+
* Forwarded to nuqs, but it does not track the server request in timber.
|
|
103
|
+
* timber runs navigations outside any transition, so `isPending` ends
|
|
104
|
+
* before the RSC fetch does. Use `usePendingNavigation()` for a loading
|
|
105
|
+
* state.
|
|
106
|
+
*/
|
|
107
|
+
startTransition?: NuqsOptions['startTransition'];
|
|
85
108
|
}
|
|
86
109
|
/** Setter function returned by useQueryStates. */
|
|
87
110
|
export type SetParams<T> = (values: Partial<T>, options?: SetParamsOptions) => void;
|
|
88
|
-
/**
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
/** 'push' (default) or 'replace' for history state. */
|
|
95
|
-
history?: 'push' | 'replace';
|
|
96
|
-
}
|
|
111
|
+
/**
|
|
112
|
+
* Options for the `useQueryStates` hook — the defaults for every setter call
|
|
113
|
+
* from that hook instance. Same shape as {@link SetParamsOptions}; a per-call
|
|
114
|
+
* option overrides the hook's.
|
|
115
|
+
*/
|
|
116
|
+
export type QueryStatesOptions = SetParamsOptions;
|
|
97
117
|
/**
|
|
98
118
|
* A fully typed, composable search params definition.
|
|
99
119
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.d.ts","sourceRoot":"","sources":["../../src/search-params/define.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"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CAAC,EAC3E,MAAM,EAAE,CAAC,GACR,sBAAsB,CAAC;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,CAAC,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export type { SearchParamCodec, SearchParamCodecWithUrlKey, TotalSearchParamCodec, InferCodec, InferField, CodecMap, SearchParamsDefinition, SetParams, SetParamsOptions, QueryStatesOptions, StandardSchemaV1, } from './define.ts';
|
|
2
2
|
export { defineSearchParams } from './define.ts';
|
|
3
3
|
export { withDefault, withUrlKey } from './wrappers.ts';
|
|
4
|
+
export { debounce, throttle, defaultRateLimit } from 'nuqs/server';
|
|
4
5
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/search-params/index.ts"],"names":[],"mappings":"AAMA,YAAY,EACV,gBAAgB,EAChB,0BAA0B,EAC1B,qBAAqB,EACrB,UAAU,EACV,UAAU,EACV,QAAQ,EACR,sBAAsB,EACtB,SAAS,EACT,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAMjD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/search-params/index.ts"],"names":[],"mappings":"AAMA,YAAY,EACV,gBAAgB,EAChB,0BAA0B,EAC1B,qBAAqB,EACrB,UAAU,EACV,UAAU,EACV,QAAQ,EACR,sBAAsB,EACtB,SAAS,EACT,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAMjD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAUxD,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { r as getSearchParamsFromAls } from "../_chunks/als-slots-kbQrHTzm.js";
|
|
2
2
|
import { i as isStandardSchema, n as fromSchema, r as isCodec } from "../_chunks/schema-bridge-DyRs3cqy.js";
|
|
3
|
-
import { i as parseTotal, n as useQueryStates, r as serializedEqual } from "../_chunks/use-query-states-
|
|
3
|
+
import { i as parseTotal, n as useQueryStates, r as serializedEqual } from "../_chunks/use-query-states-D3MMl-KM.js";
|
|
4
|
+
import { debounce, defaultRateLimit, throttle } from "nuqs/server";
|
|
4
5
|
// src/search-params/define.ts
|
|
5
6
|
/**
|
|
6
7
|
* defineSearchParams — factory for SearchParamsDefinition<T>.
|
|
@@ -285,6 +286,6 @@ function withUrlKey(codecOrSchema, urlKey) {
|
|
|
285
286
|
if (typeof codec.parseServerSide === "function") wrapped.parseServerSide = codec.parseServerSide.bind(codec);
|
|
286
287
|
return wrapped;
|
|
287
288
|
}
|
|
288
|
-
export { defineSearchParams, withDefault, withUrlKey };
|
|
289
|
+
export { debounce, defaultRateLimit, defineSearchParams, throttle, withDefault, withUrlKey };
|
|
289
290
|
|
|
290
291
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useQueryStates","clientUseQueryStates"],"sources":["../../src/search-params/define.ts","../../src/search-params/wrappers.ts"],"sourcesContent":["/**\n * defineSearchParams — factory for SearchParamsDefinition<T>.\n *\n * Creates a typed, composable definition for a route's search parameters.\n * Accepts both SearchParamCodec values and Standard Schema objects (Zod,\n * Valibot, ArkType) with auto-detection. Supports URL key aliasing via\n * withUrlKey(), default-omission serialization, and composition via\n * .extend() / .pick().\n *\n * Design doc: design/23-search-params.md §\"defineSearchParams — The Factory\"\n */\n\nimport { useQueryStates as clientUseQueryStates } from '../client/use-query-states.ts';\nimport { fromSchema, isStandardSchema, isCodec } from '../schema-bridge.ts';\nimport type { StandardSchemaV1 } from '../schema-bridge.ts';\nimport type { Codec } from '../codec.ts';\n// Server-only reference for .get() — avoids pulling server ALS into client\n// bundles. In client environments, .get() throws before reaching this code\n// path. The slot lives in its own leaf module so that `request-context.ts`\n// can register the getter without importing this file, which would drag\n// `nuqs` into every server entry (TIM-1298). See shared/als-slots.ts.\nimport { getSearchParamsFromAls } from '../shared/als-slots.ts';\nimport { parseTotal } from './parse-total.ts';\nimport { serializedEqual } from './serialize-equal.ts';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A codec that converts between URL string values and typed values.\n *\n * `parse` receives the RAW url value: `string | string[] | undefined`.\n * A codec must be TOTAL over that domain — return a default rather than\n * throwing on an absent or repeated param.\n *\n * A codec whose own `parse` covers only a PRESENT, SINGLE-VALUED param\n * may publish `parseServerSide` instead, and timber calls that. nuqs\n * parsers do exactly this, which is how they become total here: absent →\n * `null` (or their `withDefault` value), repeated → the first value, and\n * a throw from the inner parse → `null`. See\n * design/23-search-params.md §'nuqs parsers, made total',\n * `parse-total.ts`, and tests/nuqs-codec-boundary.test.ts (TIM-1350).\n *\n * Standard Schema objects (Zod, Valibot, ArkType) are auto-detected\n * by defineSearchParams and wrapped via fromSchema; those ARE total\n * through `parse` and are called that way.\n */\nexport interface SearchParamCodec<T> extends Omit<Codec<T>, 'serialize'> {\n /**\n * Typed value → URL string(s). Return `null` to omit/clear.\n *\n * A codec MAY return `string[]` to emit repeated keys (`?tag=a&tag=b`).\n * `buildSearchParams` appends one `key=value` entry per array element;\n * the nuqs bridge forwards the array to nuqs, which does the same.\n * Codecs that always produce a single value return a plain string.\n *\n * Wider than `Codec<T>.serialize` (`string | null`) because search params\n * have a repeated-key concept that cookies and segment params do not.\n */\n serialize(value: T): string | string[] | null;\n /** Optional URL key alias, set by withUrlKey(). */\n urlKey?: string;\n /**\n * Optional TOTAL entry point over `string | string[] | undefined`,\n * preferred over `parse` wherever timber invokes a codec. Declared here\n * so the protocol is typed rather than duck-checked at each wrapper:\n * anything that reconstructs a codec has to carry it, and a wrapper\n * cannot carry a property the interface does not admit.\n *\n * It returns `T`, not `T | null`. This is the entry point timber calls,\n * so whatever it returns IS the field's type — admitting a `null` the\n * field type did not carry would let `SearchParamCodec<string>` produce\n * `null` for an absent param under a non-nullable annotation. A codec\n * whose absent-case answer is `null` declares that in `T`, exactly as a\n * bare nuqs parser does: `parseAsString` is a `SearchParamCodec<string |\n * null>` here, never a `SearchParamCodec<string>`.\n *\n * nuqs parser builders satisfy this. See parse-total.ts.\n */\n parseServerSide?(value: string | string[] | undefined): T;\n}\n\n/** A codec with a URL key alias attached via withUrlKey(). */\nexport interface SearchParamCodecWithUrlKey<T> extends SearchParamCodec<T> {\n urlKey: string;\n}\n\n/** Infer the output type of a codec. */\nexport type InferCodec<C> = C extends SearchParamCodec<infer T> ? T : never;\n\n/** Map of property names to codecs. */\nexport type CodecMap<T extends Record<string, unknown>> = {\n [K in keyof T]: SearchParamCodec<T[K]>;\n};\n\n/** Options for useQueryStates setter. */\nexport interface SetParamsOptions {\n /** Update URL without server roundtrip (default: false). */\n shallow?: boolean;\n /** Scroll to top after update (default: true). */\n scroll?: boolean;\n /** 'push' (default) or 'replace' for history state. */\n history?: 'push' | 'replace';\n}\n\n/** Setter function returned by useQueryStates. */\nexport type SetParams<T> = (values: Partial<T>, options?: SetParamsOptions) => void;\n\n/** Options for useQueryStates hook. */\nexport interface QueryStatesOptions {\n /** Update URL without server roundtrip (default: false). */\n shallow?: boolean;\n /** Scroll to top after update (default: true). */\n scroll?: boolean;\n /** 'push' (default) or 'replace' for history state. */\n history?: 'push' | 'replace';\n}\n\n/**\n * A fully typed, composable search params definition.\n *\n * Returned by defineSearchParams(). Carries a phantom _type property\n * for build-time type extraction.\n */\nexport interface SearchParamsDefinition<T extends Record<string, unknown>> {\n /** Parse raw URL search params into typed values. */\n parse(raw: URLSearchParams | Record<string, string | string[] | undefined>): T;\n /** Parse a Promise of URLSearchParams (e.g., from the ALS `searchParams()` API). */\n parse(raw: Promise<URLSearchParams | Record<string, string | string[] | undefined>>): Promise<T>;\n\n /**\n * Get typed search params from the current request context (ALS-backed).\n *\n * Server-only, sync. Reads getSearchParams() from ALS and parses through codecs.\n * Throws on client.\n *\n * ```tsx\n * // app/products/page.tsx\n * import { searchParams } from './search-params'\n * export default function Page() {\n * const { page, category } = searchParams.get()\n * }\n * ```\n */\n get(): T;\n\n /** Client hook — reads current URL params and returns typed values + setter. */\n useQueryStates(options?: QueryStatesOptions): [T, SetParams<T>];\n\n /** Extend with additional codecs or Standard Schema objects. */\n extend<U extends Record<string, SearchParamField>>(\n codecs: U\n ): SearchParamsDefinition<T & { [K in keyof U]: InferField<U[K]> }>;\n\n /** Pick a subset of keys. Preserves codecs and aliases. */\n pick<K extends keyof T & string>(...keys: K[]): SearchParamsDefinition<Pick<T, K>>;\n\n /**\n * Serialize values to a query string (no leading '?'), omitting defaults\n * and applying `withUrlKey` aliases. This is the value to pass to\n * `<Link searchParams={...}>`.\n *\n * Returns a **string**, not a `URLSearchParams`. A `<Link>` prop crosses\n * the RSC Flight boundary, and `URLSearchParams` is iterable — React\n * serializes it as an entries array, which arrives as `[['pg','2'], …]`\n * and renders as `?0=pg&0=2`. A string survives intact.\n */\n buildSearchParams(values: Partial<T>): string;\n\n /** Build a full path with query string, omitting defaults. */\n href(pathname: string, values: Partial<T>): string;\n\n /** Read-only codec map for spreading into .extend(). */\n codecs: { [K in keyof T]: SearchParamCodec<T[K]> };\n\n /** Read-only URL key alias map. Maps property names to URL query parameter keys. */\n readonly urlKeys: Readonly<Record<string, string>>;\n\n /**\n * Phantom property for build-time type extraction.\n * Never set at runtime — exists only in the type system.\n */\n readonly _type?: T;\n}\n\n// StandardSchemaV1 is imported from schema-bridge.ts — single source of truth.\n// Re-export for consumers that import it from this module.\nexport type { StandardSchemaV1 } from '../schema-bridge.ts';\n\n// ---------------------------------------------------------------------------\n// Type-level helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Extract a Standard Schema's declared *input* type from its optional\n * `~standard.types` property (part of the Standard Schema spec; Zod, Valibot,\n * and ArkType all declare it at the type level). Falls back to `never` when\n * the schema doesn't declare types (e.g. hand-written schemas): with no\n * metadata we can't know whether the schema handles `undefined`, so InferField\n * widens conservatively rather than risk a type lie.\n */\ntype InferSchemaInput<V> = V extends { '~standard': { types?: infer TS } }\n ? [NonNullable<TS>] extends [{ input: infer I }]\n ? I\n : never\n : never;\n\n/**\n * Infer the output type from either a SearchParamCodec or a StandardSchemaV1.\n *\n * A codec publishing `parseServerSide` is read through THAT signature, not\n * through `parse` — it is the entry point timber actually calls, and it is\n * the one that tells the truth about absent input. A bare `parseAsString`\n * declares `parse(value: string): string` but answers `null` for a missing\n * param, so the field is `string | null`; `parseAsInteger.withDefault(1)`\n * narrows its own `parseServerSide` to `NonNullable<number>` and the field\n * stays `number`. Reading `parse` instead produced a non-nullable type for\n * a nullable field (TIM-1350).\n *\n * The match is structural, not nuqs-specific: any codec declaring that\n * signature opts into being read through it, which is exactly the contract\n * `parseTotal` applies at runtime. The two must stay in step — a type\n * inferred from `parse` while the runtime calls `parseServerSide` is the\n * lie this branch exists to remove.\n *\n * Schemas whose input type rejects `undefined` (e.g. bare `z.string()`, whose\n * input is `string`) are implicitly optional: the URL might not contain the\n * param, and fromSchema returns `undefined` when the schema rejects absent\n * input and has no default. The output type widens to `T | undefined` so the\n * type doesn't lie. Schemas that accept `undefined` input (`.optional()`,\n * `.default()`) keep their declared output type.\n *\n * Limitation: `z.coerce.*` schemas declare input `unknown`, which accepts\n * `undefined` at the type level — so a coerce schema without `.default()`\n * keeps its narrow output type even though absent input yields `undefined`\n * at runtime. Add `.default()` to coerce schemas for accurate types.\n */\nexport type InferField<V> = V extends {\n parseServerSide(value: string | string[] | undefined): infer R;\n}\n ? R\n : V extends SearchParamCodec<infer T>\n ? T\n : V extends StandardSchemaV1<infer T>\n ? undefined extends InferSchemaInput<V>\n ? T\n : T | undefined\n : never;\n\n/**\n * A codec whose total entry point is `parseServerSide`, even when `parse`\n * has a narrower signature. nuqs multi parsers (`parseAsNativeArrayOf`) have\n * `parse(value: readonly string[])` — too narrow for `SearchParamCodec`'s\n * `parse(string | string[] | undefined)` — but their `parseServerSide`\n * covers the full domain. Timber never calls `parse` directly on these;\n * `parseTotal` always reaches `parseServerSide` first (TIM-1355).\n */\nexport interface TotalSearchParamCodec<T> {\n parseServerSide(value: string | string[] | undefined): T;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parse(...args: any[]): any;\n serialize(value: T): string | string[] | null;\n urlKey?: string;\n}\n\n/** Acceptable field value for defineSearchParams: a codec, a total codec, or a Standard Schema. */\nexport type SearchParamField<T = unknown> =\n | SearchParamCodec<T>\n | TotalSearchParamCodec<T>\n | StandardSchemaV1<T>;\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert URLSearchParams or a plain record to a normalized record\n * where repeated keys produce arrays.\n */\nfunction normalizeRaw(\n raw: URLSearchParams | Record<string, string | string[] | undefined>\n): Record<string, string | string[] | undefined> {\n if (raw instanceof URLSearchParams) {\n const result: Record<string, string | string[] | undefined> = Object.create(null);\n for (const key of new Set(raw.keys())) {\n const values = raw.getAll(key);\n result[key] = values.length === 1 ? values[0] : values;\n }\n return result;\n }\n return raw;\n}\n\n/**\n * Compute the serialized default value for a codec. Used for\n * default-omission: when serialize(value) === serialize(parse(undefined)),\n * the field is omitted from the URL.\n *\n * Goes through `parseTotal` for the same reason request-time parsing does:\n * a nuqs parser's own `parse` throws on absent input, and this is the\n * absent case by construction.\n *\n * **A codec with no value for an absent param has no default to omit**,\n * and `null` is returned rather than `serialize(null)`. Serializing it\n * makes the \"no value\" case collide with a real one: `parseAsInteger`\n * serializes `null` as the string `'null'`, so `buildSearchParams({ q:\n * 'null' })` would silently drop a legitimate value (before TIM-1350 the\n * absent parse was `undefined` and the swallowed input was the string\n * `'undefined'` — same defect, a less likely input). Nothing is lost:\n * `buildSearchParams` already skips a field whose `serialize` returns\n * `null`, so a codec that encodes \"no value\" as an omission behaves\n * identically, and one that encodes it as a real query value now writes\n * it instead of dropping it.\n *\n * Codecs are documented to return a default rather than throw, but a\n * hand-written codec that throws on absent input must not turn definition\n * into a crash — treat its default as null (nothing to omit). `serialize`\n * is inside the try for the same reason.\n *\n * Typed `SearchParamCodec<unknown>` rather than generic on purpose: the\n * absent-input value is whatever the codec's total entry point returns,\n * which for a nuqs parser is `T | null` while its `serialize` declares\n * `T`. Widening to `unknown` states that honestly instead of casting.\n */\nfunction getDefaultSerialized(codec: SearchParamCodec<unknown>): string | string[] | null {\n try {\n const absent = parseTotal(codec, undefined);\n return absent === null || absent === undefined ? null : codec.serialize(absent);\n } catch {\n return null;\n }\n}\n\n// isStandardSchema and isCodec are imported from schema-bridge.ts.\n\n/**\n * Resolve a field value to a SearchParamCodec. Auto-detects Standard Schema\n * objects and wraps them with fromSchema. Reads .urlKey from codecs.\n *\n * The returned codec is typed as `SearchParamCodec<unknown>` because the\n * codec map uses that type. Both `fromSchema` results and nuqs parsers may\n * serialize to `string | string[] | null`; `buildSearchParams` handles the\n * union.\n */\nfunction resolveField(\n fieldName: string,\n value: SearchParamField\n): { codec: SearchParamCodec<unknown>; urlKey?: string } {\n // Check for codec first (codecs may also have '~standard' if they're nuqs parsers)\n if (isCodec(value)) {\n const urlKey = (value as SearchParamCodec<unknown>).urlKey;\n return { codec: value as SearchParamCodec<unknown>, urlKey };\n }\n\n // Auto-detect Standard Schema. Schemas that reject undefined input and\n // have no default are implicitly optional: fromSchema returns undefined\n // for absent params, and InferField widens the output type to\n // T | undefined. design/23-search-params.md §\"Implicit Optionality\"\n if (isStandardSchema(value)) {\n return { codec: fromSchema(value) };\n }\n\n throw new Error(\n `[timber] defineSearchParams: field '${fieldName}' is not a valid codec or Standard Schema. ` +\n `Expected an object with { parse, serialize } methods, or a Standard Schema object ` +\n `(Zod, Valibot, ArkType).`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a SearchParamsDefinition from a map of codecs and/or Standard Schema\n * objects. Accepts both SearchParamCodec values and raw Zod/Valibot/ArkType\n * schemas with auto-detection.\n *\n * ```ts\n * import { defineSearchParams, withDefault, withUrlKey } from '@timber-js/app/search-params'\n * import { parseAsString, parseAsStringEnum } from 'nuqs/server'\n * import { z } from 'zod/v4'\n *\n * export const searchParams = defineSearchParams({\n * page: z.coerce.number().int().min(1).default(1), // Standard Schema — auto-wrapped\n * q: withUrlKey(parseAsString, 'search'), // nuqs codec with URL alias\n * sort: withDefault(parseAsStringEnum(['price', 'name']), 'price'),\n * })\n * ```\n */\n/**\n * Overload: accept a Standard Schema object schema (e.g., z.object({...})).\n *\n * The schema must have a `.shape` property whose values are themselves\n * Standard Schema objects. Each shape property becomes a field codec\n * via fromSchema().\n *\n * ```ts\n * const searchParams = defineSearchParams(\n * z.object({ page: z.coerce.number().default(1), q: z.string().optional() })\n * )\n * ```\n */\nexport function defineSearchParams<\n S extends StandardSchemaV1<Record<string, unknown>> & {\n shape: Record<string, StandardSchemaV1<unknown>>;\n },\n>(\n schema: S\n): SearchParamsDefinition<{ [K in keyof S['shape'] & string]: InferField<S['shape'][K]> }>;\n\n/**\n * Overload: accept a map of codecs and/or Standard Schema objects.\n */\nexport function defineSearchParams<C extends Record<string, SearchParamField>>(\n codecs: C\n): SearchParamsDefinition<{ [K in keyof C]: InferField<C[K]> }>;\n\nexport function defineSearchParams(\n codecsOrSchema:\n | Record<string, SearchParamField>\n | (StandardSchemaV1<unknown> & { shape: Record<string, StandardSchemaV1<unknown>> })\n): SearchParamsDefinition<Record<string, unknown>> {\n // Detect Standard Schema object with .shape (e.g., z.object(...))\n if (isStandardSchema(codecsOrSchema) && hasShape(codecsOrSchema)) {\n const fieldCodecs: Record<string, SearchParamField> = {};\n for (const [key, fieldSchema] of Object.entries(codecsOrSchema.shape)) {\n if (isStandardSchema(fieldSchema)) {\n fieldCodecs[key] = fieldSchema;\n } else {\n throw new Error(\n `[timber] defineSearchParams: field '${key}' in schema.shape is not a Standard Schema. ` +\n `All shape properties must be Standard Schema objects (Zod, Valibot, ArkType).`\n );\n }\n }\n return defineSearchParamsFromMap(fieldCodecs);\n }\n\n return defineSearchParamsFromMap(codecsOrSchema as Record<string, SearchParamField>);\n}\n\n/** Check if a schema has a .shape property with object-type values. */\nfunction hasShape(schema: unknown): schema is { shape: Record<string, unknown> } {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n 'shape' in schema &&\n typeof (schema as { shape: unknown }).shape === 'object' &&\n (schema as { shape: unknown }).shape !== null\n );\n}\n\nfunction defineSearchParamsFromMap(\n codecs: Record<string, SearchParamField>\n): SearchParamsDefinition<Record<string, unknown>> {\n const resolvedCodecs: Record<string, SearchParamCodec<unknown>> = {};\n const urlKeys: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(codecs)) {\n const resolved = resolveField(key, value as SearchParamField);\n resolvedCodecs[key] = resolved.codec;\n if (resolved.urlKey) {\n urlKeys[key] = resolved.urlKey;\n }\n }\n\n return buildDefinition(resolvedCodecs as unknown as CodecMap<Record<string, unknown>>, urlKeys);\n}\n\n// ---------------------------------------------------------------------------\n// Internal: build the definition object\n// ---------------------------------------------------------------------------\n\n/**\n * Internal: build a SearchParamsDefinition from a typed codec map and url keys.\n */\nfunction buildDefinition<T extends Record<string, unknown>>(\n codecMap: CodecMap<T>,\n urlKeys: Record<string, string>\n): SearchParamsDefinition<T> {\n // Pre-compute default serialized values for omission check\n const defaultSerialized: Record<string, string | string[] | null> = {};\n for (const key of Object.keys(codecMap)) {\n defaultSerialized[key] = getDefaultSerialized(codecMap[key as keyof T]);\n }\n\n function getUrlKey(prop: string): string {\n return urlKeys[prop] ?? prop;\n }\n\n // ---- parse ----\n function parseSync(raw: URLSearchParams | Record<string, string | string[] | undefined>): T {\n const normalized = normalizeRaw(raw);\n const result: Record<string, unknown> = {};\n\n for (const prop of Object.keys(codecMap)) {\n const urlKey = getUrlKey(prop);\n const rawValue = normalized[urlKey];\n result[prop] = parseTotal(codecMap[prop as keyof T] as SearchParamCodec<unknown>, rawValue);\n }\n\n return result as T;\n }\n\n // Overloaded parse: sync when given raw params, async when given a Promise.\n // This enables the ergonomic pattern: await def.parse(searchParams())\n function parse(raw: URLSearchParams | Record<string, string | string[] | undefined>): T;\n function parse(\n raw: Promise<URLSearchParams | Record<string, string | string[] | undefined>>\n ): Promise<T>;\n function parse(\n raw:\n | URLSearchParams\n | Record<string, string | string[] | undefined>\n | Promise<URLSearchParams | Record<string, string | string[] | undefined>>\n ): T | Promise<T> {\n if (raw instanceof Promise) {\n return raw.then(parseSync);\n }\n return parseSync(raw);\n }\n\n // ---- buildSearchParams ----\n //\n // Returns a query string. It used to have a URLSearchParams-returning\n // sibling (`toSearchParams`) that `<Link>` consumed; that shape cannot\n // cross the RSC Flight boundary (see the interface docstring), and having\n // two methods produce the same query two ways was a drift waiting to\n // happen. One method now.\n function buildSearchParams(values: Partial<T>): string {\n const parts: string[] = [];\n\n for (const prop of Object.keys(codecMap)) {\n if (!(prop in values)) continue;\n const codec = codecMap[prop as keyof T] as SearchParamCodec<unknown>;\n\n // TIM-1354: serialize may not be total over null — nuqs parsers like\n // parseAsIsoDate throw TypeError on null (null.toISOString()). Catch\n // TypeError and omit, matching what setParams does on the client.\n // Only TypeError — a deliberate throw (redirect(), notFound()) from a\n // codec's serialize must propagate, not be silently swallowed.\n let serialized: string | string[] | null;\n try {\n serialized = codec.serialize(values[prop as keyof T] as unknown);\n } catch (error) {\n if (error instanceof TypeError) continue;\n throw error;\n }\n\n if (serialized === null) continue;\n // Omit if serialized value matches the default\n if (serializedEqual(serialized, defaultSerialized[prop])) continue;\n\n // TIM-1353: string[] → repeated keys (?tag=a&tag=b)\n const urlKey = encodeURIComponent(getUrlKey(prop));\n if (Array.isArray(serialized)) {\n for (const entry of serialized) {\n parts.push(`${urlKey}=${encodeURIComponent(entry)}`);\n }\n } else {\n parts.push(`${urlKey}=${encodeURIComponent(serialized)}`);\n }\n }\n\n return parts.join('&');\n }\n\n // ---- href ----\n function href(pathname: string, values: Partial<T>): string {\n const qs = buildSearchParams(values);\n return qs ? `${pathname}?${qs}` : pathname;\n }\n\n // ---- extend ----\n function extend<U extends Record<string, SearchParamField>>(\n newCodecs: U\n ): SearchParamsDefinition<T & { [K in keyof U]: InferField<U[K]> }> {\n type Combined = T & { [K in keyof U]: InferField<U[K]> };\n\n // Resolve any Standard Schema objects in the extension\n const resolvedNewCodecs: Record<string, SearchParamCodec<unknown>> = {};\n const newUrlKeys: Record<string, string> = {};\n for (const [key, value] of Object.entries(newCodecs)) {\n const resolved = resolveField(key, value as SearchParamField);\n resolvedNewCodecs[key] = resolved.codec;\n if (resolved.urlKey) {\n newUrlKeys[key] = resolved.urlKey;\n }\n }\n\n const combinedCodecs = {\n ...codecMap,\n ...resolvedNewCodecs,\n } as unknown as CodecMap<Combined>;\n\n // Merge URL keys: base keys + new codec urlKeys from withUrlKey\n const combinedUrlKeys: Record<string, string> = { ...urlKeys, ...newUrlKeys };\n\n return buildDefinition<Combined>(combinedCodecs, combinedUrlKeys);\n }\n\n // ---- pick ----\n function pick<K extends keyof T & string>(...keys: K[]): SearchParamsDefinition<Pick<T, K>> {\n const pickedCodecs: Record<string, SearchParamCodec<unknown>> = {};\n const pickedUrlKeys: Record<string, string> = {};\n\n for (const key of keys) {\n // Explicit guard — TypeScript prevents this, but JS callers and\n // casts reach here, and \"Cannot read properties of undefined\n // (reading 'serialize')\" is no help (TIM-1066).\n if (!(key in codecMap)) {\n throw new Error(\n `[timber] pick('${key}'): unknown key. ` +\n `Available keys: ${Object.keys(codecMap)\n .map((k) => `'${k}'`)\n .join(', ')}.`\n );\n }\n pickedCodecs[key] = codecMap[key] as SearchParamCodec<unknown>;\n if (key in urlKeys) {\n pickedUrlKeys[key] = urlKeys[key];\n }\n }\n\n return buildDefinition<Pick<T, K>>(\n pickedCodecs as unknown as CodecMap<Pick<T, K>>,\n pickedUrlKeys\n );\n }\n\n // ---- useQueryStates ----\n // Delegates to the 'use client' implementation from use-query-states.ts.\n //\n // In the RSC environment: use-query-states.ts is transformed by the RSC\n // plugin into a client reference proxy. Calling it throws — correct,\n // because hooks can't run during server component rendering.\n // In SSR: use-query-states.ts is the real nuqs-backed function. Hooks\n // work during SSR's renderToReadableStream, so this works correctly.\n // On the client: same as SSR — the real function is available.\n function useQueryStates(options?: QueryStatesOptions): [T, SetParams<T>] {\n return clientUseQueryStates(codecMap, options, Object.freeze({ ...urlKeys })) as [\n T,\n SetParams<T>,\n ];\n }\n\n // ---- get ----\n // ALS-backed: reads getSearchParams() from the current request context\n // and parses through codecs. Server-only, sync.\n function get(): T {\n if (typeof window !== 'undefined') {\n throw new Error(\n '[timber] searchParams.get() is server-only. ' +\n 'Use searchParams.useQueryStates() on the client.'\n );\n }\n const raw = getSearchParamsFromAls();\n return parseSync(raw);\n }\n\n const definition: SearchParamsDefinition<T> = {\n parse,\n get,\n useQueryStates,\n extend,\n pick,\n href,\n buildSearchParams,\n codecs: codecMap,\n urlKeys: Object.freeze({ ...urlKeys }),\n };\n\n return definition;\n}\n","/**\n * Codec wrappers — withDefault and withUrlKey.\n *\n * These are timber-specific utilities that work with any SearchParamCodec.\n * For actual codecs (string, integer, boolean, etc.), use nuqs parsers\n * or Standard Schema objects (Zod, Valibot, ArkType) with auto-detection.\n *\n * Design doc: design/23-search-params.md\n */\n\nimport type {\n InferField,\n SearchParamCodec,\n SearchParamCodecWithUrlKey,\n SearchParamField,\n} from './define.ts';\nimport { isCodec, isStandardSchema, fromSchema } from '../schema-bridge.ts';\nimport { parseTotal } from './parse-total.ts';\n\n// ---------------------------------------------------------------------------\n// withDefault\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap a nullable codec with a default value. The output type becomes\n * non-nullable, and the wrapper is TOTAL over `string | string[] |\n * undefined` even when the inner codec is not.\n *\n * The default is substituted for `null` — the documented \"no value\"\n * answer — and for `undefined`, which is what an implicitly-optional\n * Standard Schema field and a bare `parseAsString` produce for an absent\n * param. Substituting only for `null` left a field typed non-nullable\n * `string` holding `undefined` (TIM-1350).\n *\n * The inner codec is invoked through `parseTotal`, so a nuqs parser gets\n * its own normalization (absent → null, repeated → first value, inner\n * throw → null) before either check applies. That is what makes\n * `withDefault(parseAsBoolean, false)` total; the wrapper itself does NOT\n * catch. A throw from a codec is a deliberate signal — `fromSchema` throws\n * on an async schema, and an app codec may `redirect()` or `notFound()` on\n * a value it refuses — and swallowing it would convert a loud failure into\n * a permanently-default field. design/09 §\"The SearchParamCodec Protocol\":\n * a codec that throws bubbles as a render-phase error, by design.\n *\n * Works with any codec — nuqs parsers, custom codecs, fromSchema results.\n *\n * ```ts\n * import { parseAsInteger } from 'nuqs/server'\n * import { withDefault } from '@timber-js/app/search-params'\n *\n * const page = withDefault(parseAsInteger, 1)\n * // page.parse(undefined) → 1 (not null)\n * // page.parse('5') → 5\n * ```\n *\n * The signature strips BOTH nullish constituents from the result, not just\n * `null`, because the runtime substitutes for both. An implicitly-optional\n * schema field is a `SearchParamCodec<string | undefined>`, and wrapping it\n * used to yield `SearchParamCodec<string | undefined>` — a field the\n * wrapper guarantees is always present, still typed as maybe-absent.\n */\nexport function withDefault<T>(\n codec: SearchParamCodec<T | null | undefined>,\n defaultValue: NonNullable<T>\n): SearchParamCodec<NonNullable<T>> {\n // A wrapper that rebuilds a codec from two methods drops everything else\n // the codec carries. `withUrlKey` lost `parseServerSide` that way; this\n // one lost `urlKey`, so `withDefault(withUrlKey(parseAsInteger, 'p'), 1)`\n // silently read `?page=` instead of `?p=`. Carry it explicitly rather\n // than spreading: this wrapper's own `parse` IS the total entry point,\n // and re-publishing the inner `parseServerSide` would let `parseTotal`\n // reach past it and skip the default entirely.\n const wrapped: SearchParamCodec<NonNullable<T>> = {\n parse(value: string | string[] | undefined): NonNullable<T> {\n const result = parseTotal(codec, value);\n return result === null || result === undefined ? defaultValue : result;\n },\n serialize(value: NonNullable<T>): string | string[] | null {\n return codec.serialize(value);\n },\n };\n if (codec.urlKey !== undefined) wrapped.urlKey = codec.urlKey;\n return wrapped;\n}\n\n// ---------------------------------------------------------------------------\n// withUrlKey\n// ---------------------------------------------------------------------------\n\n/**\n * Attach a URL key alias to a codec. The alias determines what query\n * parameter key is used in the URL, while the TypeScript property name\n * stays descriptive.\n *\n * Aliases travel with codecs through object spread composition — when\n * you spread a bundle containing aliased codecs into defineSearchParams,\n * the aliases come along automatically.\n *\n * ```ts\n * import { parseAsString } from 'nuqs/server'\n * import { withUrlKey } from '@timber-js/app/search-params'\n *\n * export const searchable = {\n * q: withUrlKey(parseAsString, 'search'),\n * // ?search=shoes → { q: 'shoes' }\n * }\n * ```\n *\n * Composes with withDefault:\n * ```ts\n * import { parseAsInteger } from 'nuqs/server'\n * withUrlKey(withDefault(parseAsInteger, 1), 'p')\n * ```\n */\nexport function withUrlKey<F extends SearchParamField>(\n codecOrSchema: F,\n urlKey: string\n): SearchParamCodecWithUrlKey<InferField<F>> {\n type T = InferField<F>;\n // Auto-detect Standard Schema (Zod, Valibot, ArkType) and wrap. Schemas\n // that reject undefined input are implicitly optional — fromSchema returns\n // undefined for absent params, and InferField widens the type to include\n // undefined. design/23-search-params.md §\"Implicit Optionality\"\n const codec: SearchParamCodec<T> = isCodec(codecOrSchema)\n ? (codecOrSchema as SearchParamCodec<T>)\n : isStandardSchema(codecOrSchema)\n ? (fromSchema(codecOrSchema) as SearchParamCodec<T>)\n : (codecOrSchema as SearchParamCodec<T>);\n // Carry the total entry point, bound like the other two methods. A\n // codec's totality lives in a THIRD property, `parseServerSide` (see\n // parse-total.ts); picking only `parse`/`serialize` silently produced a\n // non-total alias, so `withUrlKey(parseAsBoolean, 'b')` threw on an\n // absent param while the bare parser did not (TIM-1350).\n //\n // Bound explicitly rather than spread: a spread copies own enumerable\n // properties only, so a class-based codec — whose `parse` and\n // `serialize` this wrapper already reaches through the prototype —\n // would have kept its methods and lost exactly the one that makes it\n // total. Three properties, one rule, no dependence on how the inner\n // codec was constructed.\n const wrapped: SearchParamCodecWithUrlKey<T> = {\n parse: codec.parse.bind(codec),\n serialize: codec.serialize.bind(codec),\n urlKey,\n };\n if (typeof codec.parseServerSide === 'function') {\n wrapped.parseServerSide = codec.parseServerSide.bind(codec);\n }\n return wrapped;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwRA,SAAS,aACP,KAC+C;CAC/C,IAAI,eAAe,iBAAiB;EAClC,MAAM,SAAwD,OAAO,OAAO,IAAI;EAChF,KAAK,MAAM,OAAO,IAAI,IAAI,IAAI,KAAK,CAAC,GAAG;GACrC,MAAM,SAAS,IAAI,OAAO,GAAG;GAC7B,OAAO,OAAO,OAAO,WAAW,IAAI,OAAO,KAAK;EAClD;EACA,OAAO;CACT;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,qBAAqB,OAA4D;CACxF,IAAI;EACF,MAAM,SAAS,WAAW,OAAO,KAAA,CAAS;EAC1C,OAAO,WAAW,QAAQ,WAAW,KAAA,IAAY,OAAO,MAAM,UAAU,MAAM;CAChF,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;AAaA,SAAS,aACP,WACA,OACuD;CAEvD,IAAI,QAAQ,KAAK,GAEf,OAAO;EAAE,OAAO;EAAoC,QADpC,MAAoC;CACO;CAO7D,IAAI,iBAAiB,KAAK,GACxB,OAAO,EAAE,OAAO,WAAW,KAAK,EAAE;CAGpC,MAAM,IAAI,MACR,uCAAuC,UAAU,sJAGnD;AACF;AAmDA,SAAgB,mBACd,gBAGiD;CAEjD,IAAI,iBAAiB,cAAc,KAAK,SAAS,cAAc,GAAG;EAChE,MAAM,cAAgD,CAAC;EACvD,KAAK,MAAM,CAAC,KAAK,gBAAgB,OAAO,QAAQ,eAAe,KAAK,GAClE,IAAI,iBAAiB,WAAW,GAC9B,YAAY,OAAO;OAEnB,MAAM,IAAI,MACR,uCAAuC,IAAI,0HAE7C;E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jC;EAEA,OAAO,gBACL,cACA,aACF;CACF;CAWA,SAASA,iBAAe,SAAiD;EACvE,OAAOC,eAAqB,UAAU,SAAS,OAAO,OAAO,EAAE,GAAG,QAAQ,CAAC,CAAC;CAI9E;CAKA,SAAS,MAAS;EAChB,IAAI,OAAO,WAAW,aACpB,MAAM,IAAI,MACR,8FAEF;EAGF,OAAO,UADK,uBACK,CAAG;CACtB;CAcA,OAAO;EAXL;EACA;EACA,gBAAA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR,SAAS,OAAO,OAAO,EAAE,GAAG,QAAQ,CAAC;CAGhC;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACtmBA,SAAgB,YACd,OACA,cACkC;CAQlC,MAAM,UAA4C;EAChD,MAAM,OAAsD;GAC1D,MAAM,SAAS,WAAW,OAAO,KAAK;GACtC,OAAO,WAAW,QAAQ,WAAW,KAAA,IAAY,eAAe;EAClE;EACA,UAAU,OAAiD;GACzD,OAAO,MAAM,UAAU,KAAK;EAC9B;CACF;CACA,IAAI,MAAM,WAAW,KAAA,GAAW,QAAQ,SAAS,MAAM;CACvD,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,WACd,eACA,QAC2C;CAM3C,MAAM,QAA6B,QAAQ,aAAa,IACnD,gBACD,iBAAiB,aAAa,IAC3B,WAAW,aAAa,IACxB;CAaP,MAAM,UAAyC;EAC7C,OAAO,MAAM,MAAM,KAAK,KAAK;EAC7B,WAAW,MAAM,UAAU,KAAK,KAAK;EACrC;CACF;CACA,IAAI,OAAO,MAAM,oBAAoB,YACnC,QAAQ,kBAAkB,MAAM,gBAAgB,KAAK,KAAK;CAE5D,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["useQueryStates","clientUseQueryStates"],"sources":["../../src/search-params/define.ts","../../src/search-params/wrappers.ts"],"sourcesContent":["/**\n * defineSearchParams — factory for SearchParamsDefinition<T>.\n *\n * Creates a typed, composable definition for a route's search parameters.\n * Accepts both SearchParamCodec values and Standard Schema objects (Zod,\n * Valibot, ArkType) with auto-detection. Supports URL key aliasing via\n * withUrlKey(), default-omission serialization, and composition via\n * .extend() / .pick().\n *\n * Design doc: design/23-search-params.md §\"defineSearchParams — The Factory\"\n */\n\nimport { useQueryStates as clientUseQueryStates } from '../client/use-query-states.ts';\nimport { fromSchema, isStandardSchema, isCodec } from '../schema-bridge.ts';\nimport type { StandardSchemaV1 } from '../schema-bridge.ts';\nimport type { Codec } from '../codec.ts';\nimport type { Options as NuqsOptions } from 'nuqs';\n// Server-only reference for .get() — avoids pulling server ALS into client\n// bundles. In client environments, .get() throws before reaching this code\n// path. The slot lives in its own leaf module so that `request-context.ts`\n// can register the getter without importing this file, which would drag\n// `nuqs` into every server entry (TIM-1298). See shared/als-slots.ts.\nimport { getSearchParamsFromAls } from '../shared/als-slots.ts';\nimport { parseTotal } from './parse-total.ts';\nimport { serializedEqual } from './serialize-equal.ts';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A codec that converts between URL string values and typed values.\n *\n * `parse` receives the RAW url value: `string | string[] | undefined`.\n * A codec must be TOTAL over that domain — return a default rather than\n * throwing on an absent or repeated param.\n *\n * A codec whose own `parse` covers only a PRESENT, SINGLE-VALUED param\n * may publish `parseServerSide` instead, and timber calls that. nuqs\n * parsers do exactly this, which is how they become total here: absent →\n * `null` (or their `withDefault` value), repeated → the first value, and\n * a throw from the inner parse → `null`. See\n * design/23-search-params.md §'nuqs parsers, made total',\n * `parse-total.ts`, and tests/nuqs-codec-boundary.test.ts (TIM-1350).\n *\n * Standard Schema objects (Zod, Valibot, ArkType) are auto-detected\n * by defineSearchParams and wrapped via fromSchema; those ARE total\n * through `parse` and are called that way.\n */\nexport interface SearchParamCodec<T> extends Omit<Codec<T>, 'serialize'> {\n /**\n * Typed value → URL string(s). Return `null` to omit/clear.\n *\n * A codec MAY return `string[]` to emit repeated keys (`?tag=a&tag=b`).\n * `buildSearchParams` appends one `key=value` entry per array element;\n * the nuqs bridge forwards the array to nuqs, which does the same.\n * Codecs that always produce a single value return a plain string.\n *\n * Wider than `Codec<T>.serialize` (`string | null`) because search params\n * have a repeated-key concept that cookies and segment params do not.\n */\n serialize(value: T): string | string[] | null;\n /** Optional URL key alias, set by withUrlKey(). */\n urlKey?: string;\n /**\n * Optional TOTAL entry point over `string | string[] | undefined`,\n * preferred over `parse` wherever timber invokes a codec. Declared here\n * so the protocol is typed rather than duck-checked at each wrapper:\n * anything that reconstructs a codec has to carry it, and a wrapper\n * cannot carry a property the interface does not admit.\n *\n * It returns `T`, not `T | null`. This is the entry point timber calls,\n * so whatever it returns IS the field's type — admitting a `null` the\n * field type did not carry would let `SearchParamCodec<string>` produce\n * `null` for an absent param under a non-nullable annotation. A codec\n * whose absent-case answer is `null` declares that in `T`, exactly as a\n * bare nuqs parser does: `parseAsString` is a `SearchParamCodec<string |\n * null>` here, never a `SearchParamCodec<string>`.\n *\n * nuqs parser builders satisfy this. See parse-total.ts.\n */\n parseServerSide?(value: string | string[] | undefined): T;\n}\n\n/** A codec with a URL key alias attached via withUrlKey(). */\nexport interface SearchParamCodecWithUrlKey<T> extends SearchParamCodec<T> {\n urlKey: string;\n}\n\n/** Infer the output type of a codec. */\nexport type InferCodec<C> = C extends SearchParamCodec<infer T> ? T : never;\n\n/** Map of property names to codecs. */\nexport type CodecMap<T extends Record<string, unknown>> = {\n [K in keyof T]: SearchParamCodec<T[K]>;\n};\n\n/**\n * Options for a `setParams` call: nuqs's own `Options`, passed through\n * whole. Not a hand-copied subset — a whitelist silently dropped\n * `limitUrlUpdates` (debounce/throttle) and `clearOnDefault`, and would drop\n * whatever nuqs adds next (TIM-1623).\n *\n * `urlKeys` is not here: nuqs's `Options` does not carry it (it lives on\n * the hook-only `UseQueryStatesOptions`), and timber owns it — the aliases\n * come from the codecs (`withUrlKey`).\n *\n * The fields re-listed below are not a second declaration: each takes its\n * type from nuqs (`NuqsOptions['shallow']`), and is re-listed only because\n * nuqs's own JSDoc, which an editor shows on hover, is wrong for timber.\n * See design/23-search-params.md §\"Options pass through to nuqs\".\n */\nexport interface SetParamsOptions extends NuqsOptions {\n /**\n * `false` (timber's default): the write is an RSC navigation, so the server\n * renders the new params. `true`: the URL changes with no server request.\n */\n shallow?: NuqsOptions['shallow'];\n /** Scroll to the top after the write. Defaults to `true` in timber. */\n scroll?: NuqsOptions['scroll'];\n /**\n * Forwarded to nuqs, but it does not track the server request in timber.\n * timber runs navigations outside any transition, so `isPending` ends\n * before the RSC fetch does. Use `usePendingNavigation()` for a loading\n * state.\n */\n startTransition?: NuqsOptions['startTransition'];\n}\n\n/** Setter function returned by useQueryStates. */\nexport type SetParams<T> = (values: Partial<T>, options?: SetParamsOptions) => void;\n\n/**\n * Options for the `useQueryStates` hook — the defaults for every setter call\n * from that hook instance. Same shape as {@link SetParamsOptions}; a per-call\n * option overrides the hook's.\n */\nexport type QueryStatesOptions = SetParamsOptions;\n\n/**\n * A fully typed, composable search params definition.\n *\n * Returned by defineSearchParams(). Carries a phantom _type property\n * for build-time type extraction.\n */\nexport interface SearchParamsDefinition<T extends Record<string, unknown>> {\n /** Parse raw URL search params into typed values. */\n parse(raw: URLSearchParams | Record<string, string | string[] | undefined>): T;\n /** Parse a Promise of URLSearchParams (e.g., from the ALS `searchParams()` API). */\n parse(raw: Promise<URLSearchParams | Record<string, string | string[] | undefined>>): Promise<T>;\n\n /**\n * Get typed search params from the current request context (ALS-backed).\n *\n * Server-only, sync. Reads getSearchParams() from ALS and parses through codecs.\n * Throws on client.\n *\n * ```tsx\n * // app/products/page.tsx\n * import { searchParams } from './search-params'\n * export default function Page() {\n * const { page, category } = searchParams.get()\n * }\n * ```\n */\n get(): T;\n\n /** Client hook — reads current URL params and returns typed values + setter. */\n useQueryStates(options?: QueryStatesOptions): [T, SetParams<T>];\n\n /** Extend with additional codecs or Standard Schema objects. */\n extend<U extends Record<string, SearchParamField>>(\n codecs: U\n ): SearchParamsDefinition<T & { [K in keyof U]: InferField<U[K]> }>;\n\n /** Pick a subset of keys. Preserves codecs and aliases. */\n pick<K extends keyof T & string>(...keys: K[]): SearchParamsDefinition<Pick<T, K>>;\n\n /**\n * Serialize values to a query string (no leading '?'), omitting defaults\n * and applying `withUrlKey` aliases. This is the value to pass to\n * `<Link searchParams={...}>`.\n *\n * Returns a **string**, not a `URLSearchParams`. A `<Link>` prop crosses\n * the RSC Flight boundary, and `URLSearchParams` is iterable — React\n * serializes it as an entries array, which arrives as `[['pg','2'], …]`\n * and renders as `?0=pg&0=2`. A string survives intact.\n */\n buildSearchParams(values: Partial<T>): string;\n\n /** Build a full path with query string, omitting defaults. */\n href(pathname: string, values: Partial<T>): string;\n\n /** Read-only codec map for spreading into .extend(). */\n codecs: { [K in keyof T]: SearchParamCodec<T[K]> };\n\n /** Read-only URL key alias map. Maps property names to URL query parameter keys. */\n readonly urlKeys: Readonly<Record<string, string>>;\n\n /**\n * Phantom property for build-time type extraction.\n * Never set at runtime — exists only in the type system.\n */\n readonly _type?: T;\n}\n\n// StandardSchemaV1 is imported from schema-bridge.ts — single source of truth.\n// Re-export for consumers that import it from this module.\nexport type { StandardSchemaV1 } from '../schema-bridge.ts';\n\n// ---------------------------------------------------------------------------\n// Type-level helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Extract a Standard Schema's declared *input* type from its optional\n * `~standard.types` property (part of the Standard Schema spec; Zod, Valibot,\n * and ArkType all declare it at the type level). Falls back to `never` when\n * the schema doesn't declare types (e.g. hand-written schemas): with no\n * metadata we can't know whether the schema handles `undefined`, so InferField\n * widens conservatively rather than risk a type lie.\n */\ntype InferSchemaInput<V> = V extends { '~standard': { types?: infer TS } }\n ? [NonNullable<TS>] extends [{ input: infer I }]\n ? I\n : never\n : never;\n\n/**\n * Infer the output type from either a SearchParamCodec or a StandardSchemaV1.\n *\n * A codec publishing `parseServerSide` is read through THAT signature, not\n * through `parse` — it is the entry point timber actually calls, and it is\n * the one that tells the truth about absent input. A bare `parseAsString`\n * declares `parse(value: string): string` but answers `null` for a missing\n * param, so the field is `string | null`; `parseAsInteger.withDefault(1)`\n * narrows its own `parseServerSide` to `NonNullable<number>` and the field\n * stays `number`. Reading `parse` instead produced a non-nullable type for\n * a nullable field (TIM-1350).\n *\n * The match is structural, not nuqs-specific: any codec declaring that\n * signature opts into being read through it, which is exactly the contract\n * `parseTotal` applies at runtime. The two must stay in step — a type\n * inferred from `parse` while the runtime calls `parseServerSide` is the\n * lie this branch exists to remove.\n *\n * Schemas whose input type rejects `undefined` (e.g. bare `z.string()`, whose\n * input is `string`) are implicitly optional: the URL might not contain the\n * param, and fromSchema returns `undefined` when the schema rejects absent\n * input and has no default. The output type widens to `T | undefined` so the\n * type doesn't lie. Schemas that accept `undefined` input (`.optional()`,\n * `.default()`) keep their declared output type.\n *\n * Limitation: `z.coerce.*` schemas declare input `unknown`, which accepts\n * `undefined` at the type level — so a coerce schema without `.default()`\n * keeps its narrow output type even though absent input yields `undefined`\n * at runtime. Add `.default()` to coerce schemas for accurate types.\n */\nexport type InferField<V> = V extends {\n parseServerSide(value: string | string[] | undefined): infer R;\n}\n ? R\n : V extends SearchParamCodec<infer T>\n ? T\n : V extends StandardSchemaV1<infer T>\n ? undefined extends InferSchemaInput<V>\n ? T\n : T | undefined\n : never;\n\n/**\n * A codec whose total entry point is `parseServerSide`, even when `parse`\n * has a narrower signature. nuqs multi parsers (`parseAsNativeArrayOf`) have\n * `parse(value: readonly string[])` — too narrow for `SearchParamCodec`'s\n * `parse(string | string[] | undefined)` — but their `parseServerSide`\n * covers the full domain. Timber never calls `parse` directly on these;\n * `parseTotal` always reaches `parseServerSide` first (TIM-1355).\n */\nexport interface TotalSearchParamCodec<T> {\n parseServerSide(value: string | string[] | undefined): T;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parse(...args: any[]): any;\n serialize(value: T): string | string[] | null;\n urlKey?: string;\n}\n\n/** Acceptable field value for defineSearchParams: a codec, a total codec, or a Standard Schema. */\nexport type SearchParamField<T = unknown> =\n | SearchParamCodec<T>\n | TotalSearchParamCodec<T>\n | StandardSchemaV1<T>;\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert URLSearchParams or a plain record to a normalized record\n * where repeated keys produce arrays.\n */\nfunction normalizeRaw(\n raw: URLSearchParams | Record<string, string | string[] | undefined>\n): Record<string, string | string[] | undefined> {\n if (raw instanceof URLSearchParams) {\n const result: Record<string, string | string[] | undefined> = Object.create(null);\n for (const key of new Set(raw.keys())) {\n const values = raw.getAll(key);\n result[key] = values.length === 1 ? values[0] : values;\n }\n return result;\n }\n return raw;\n}\n\n/**\n * Compute the serialized default value for a codec. Used for\n * default-omission: when serialize(value) === serialize(parse(undefined)),\n * the field is omitted from the URL.\n *\n * Goes through `parseTotal` for the same reason request-time parsing does:\n * a nuqs parser's own `parse` throws on absent input, and this is the\n * absent case by construction.\n *\n * **A codec with no value for an absent param has no default to omit**,\n * and `null` is returned rather than `serialize(null)`. Serializing it\n * makes the \"no value\" case collide with a real one: `parseAsInteger`\n * serializes `null` as the string `'null'`, so `buildSearchParams({ q:\n * 'null' })` would silently drop a legitimate value (before TIM-1350 the\n * absent parse was `undefined` and the swallowed input was the string\n * `'undefined'` — same defect, a less likely input). Nothing is lost:\n * `buildSearchParams` already skips a field whose `serialize` returns\n * `null`, so a codec that encodes \"no value\" as an omission behaves\n * identically, and one that encodes it as a real query value now writes\n * it instead of dropping it.\n *\n * Codecs are documented to return a default rather than throw, but a\n * hand-written codec that throws on absent input must not turn definition\n * into a crash — treat its default as null (nothing to omit). `serialize`\n * is inside the try for the same reason.\n *\n * Typed `SearchParamCodec<unknown>` rather than generic on purpose: the\n * absent-input value is whatever the codec's total entry point returns,\n * which for a nuqs parser is `T | null` while its `serialize` declares\n * `T`. Widening to `unknown` states that honestly instead of casting.\n */\nfunction getDefaultSerialized(codec: SearchParamCodec<unknown>): string | string[] | null {\n try {\n const absent = parseTotal(codec, undefined);\n return absent === null || absent === undefined ? null : codec.serialize(absent);\n } catch {\n return null;\n }\n}\n\n// isStandardSchema and isCodec are imported from schema-bridge.ts.\n\n/**\n * Resolve a field value to a SearchParamCodec. Auto-detects Standard Schema\n * objects and wraps them with fromSchema. Reads .urlKey from codecs.\n *\n * The returned codec is typed as `SearchParamCodec<unknown>` because the\n * codec map uses that type. Both `fromSchema` results and nuqs parsers may\n * serialize to `string | string[] | null`; `buildSearchParams` handles the\n * union.\n */\nfunction resolveField(\n fieldName: string,\n value: SearchParamField\n): { codec: SearchParamCodec<unknown>; urlKey?: string } {\n // Check for codec first (codecs may also have '~standard' if they're nuqs parsers)\n if (isCodec(value)) {\n const urlKey = (value as SearchParamCodec<unknown>).urlKey;\n return { codec: value as SearchParamCodec<unknown>, urlKey };\n }\n\n // Auto-detect Standard Schema. Schemas that reject undefined input and\n // have no default are implicitly optional: fromSchema returns undefined\n // for absent params, and InferField widens the output type to\n // T | undefined. design/23-search-params.md §\"Implicit Optionality\"\n if (isStandardSchema(value)) {\n return { codec: fromSchema(value) };\n }\n\n throw new Error(\n `[timber] defineSearchParams: field '${fieldName}' is not a valid codec or Standard Schema. ` +\n `Expected an object with { parse, serialize } methods, or a Standard Schema object ` +\n `(Zod, Valibot, ArkType).`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a SearchParamsDefinition from a map of codecs and/or Standard Schema\n * objects. Accepts both SearchParamCodec values and raw Zod/Valibot/ArkType\n * schemas with auto-detection.\n *\n * ```ts\n * import { defineSearchParams, withDefault, withUrlKey } from '@timber-js/app/search-params'\n * import { parseAsString, parseAsStringEnum } from 'nuqs/server'\n * import { z } from 'zod/v4'\n *\n * export const searchParams = defineSearchParams({\n * page: z.coerce.number().int().min(1).default(1), // Standard Schema — auto-wrapped\n * q: withUrlKey(parseAsString, 'search'), // nuqs codec with URL alias\n * sort: withDefault(parseAsStringEnum(['price', 'name']), 'price'),\n * })\n * ```\n */\n/**\n * Overload: accept a Standard Schema object schema (e.g., z.object({...})).\n *\n * The schema must have a `.shape` property whose values are themselves\n * Standard Schema objects. Each shape property becomes a field codec\n * via fromSchema().\n *\n * ```ts\n * const searchParams = defineSearchParams(\n * z.object({ page: z.coerce.number().default(1), q: z.string().optional() })\n * )\n * ```\n */\nexport function defineSearchParams<\n S extends StandardSchemaV1<Record<string, unknown>> & {\n shape: Record<string, StandardSchemaV1<unknown>>;\n },\n>(\n schema: S\n): SearchParamsDefinition<{ [K in keyof S['shape'] & string]: InferField<S['shape'][K]> }>;\n\n/**\n * Overload: accept a map of codecs and/or Standard Schema objects.\n */\nexport function defineSearchParams<C extends Record<string, SearchParamField>>(\n codecs: C\n): SearchParamsDefinition<{ [K in keyof C]: InferField<C[K]> }>;\n\nexport function defineSearchParams(\n codecsOrSchema:\n | Record<string, SearchParamField>\n | (StandardSchemaV1<unknown> & { shape: Record<string, StandardSchemaV1<unknown>> })\n): SearchParamsDefinition<Record<string, unknown>> {\n // Detect Standard Schema object with .shape (e.g., z.object(...))\n if (isStandardSchema(codecsOrSchema) && hasShape(codecsOrSchema)) {\n const fieldCodecs: Record<string, SearchParamField> = {};\n for (const [key, fieldSchema] of Object.entries(codecsOrSchema.shape)) {\n if (isStandardSchema(fieldSchema)) {\n fieldCodecs[key] = fieldSchema;\n } else {\n throw new Error(\n `[timber] defineSearchParams: field '${key}' in schema.shape is not a Standard Schema. ` +\n `All shape properties must be Standard Schema objects (Zod, Valibot, ArkType).`\n );\n }\n }\n return defineSearchParamsFromMap(fieldCodecs);\n }\n\n return defineSearchParamsFromMap(codecsOrSchema as Record<string, SearchParamField>);\n}\n\n/** Check if a schema has a .shape property with object-type values. */\nfunction hasShape(schema: unknown): schema is { shape: Record<string, unknown> } {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n 'shape' in schema &&\n typeof (schema as { shape: unknown }).shape === 'object' &&\n (schema as { shape: unknown }).shape !== null\n );\n}\n\nfunction defineSearchParamsFromMap(\n codecs: Record<string, SearchParamField>\n): SearchParamsDefinition<Record<string, unknown>> {\n const resolvedCodecs: Record<string, SearchParamCodec<unknown>> = {};\n const urlKeys: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(codecs)) {\n const resolved = resolveField(key, value as SearchParamField);\n resolvedCodecs[key] = resolved.codec;\n if (resolved.urlKey) {\n urlKeys[key] = resolved.urlKey;\n }\n }\n\n return buildDefinition(resolvedCodecs as unknown as CodecMap<Record<string, unknown>>, urlKeys);\n}\n\n// ---------------------------------------------------------------------------\n// Internal: build the definition object\n// ---------------------------------------------------------------------------\n\n/**\n * Internal: build a SearchParamsDefinition from a typed codec map and url keys.\n */\nfunction buildDefinition<T extends Record<string, unknown>>(\n codecMap: CodecMap<T>,\n urlKeys: Record<string, string>\n): SearchParamsDefinition<T> {\n // Pre-compute default serialized values for omission check\n const defaultSerialized: Record<string, string | string[] | null> = {};\n for (const key of Object.keys(codecMap)) {\n defaultSerialized[key] = getDefaultSerialized(codecMap[key as keyof T]);\n }\n\n function getUrlKey(prop: string): string {\n return urlKeys[prop] ?? prop;\n }\n\n // ---- parse ----\n function parseSync(raw: URLSearchParams | Record<string, string | string[] | undefined>): T {\n const normalized = normalizeRaw(raw);\n const result: Record<string, unknown> = {};\n\n for (const prop of Object.keys(codecMap)) {\n const urlKey = getUrlKey(prop);\n const rawValue = normalized[urlKey];\n result[prop] = parseTotal(codecMap[prop as keyof T] as SearchParamCodec<unknown>, rawValue);\n }\n\n return result as T;\n }\n\n // Overloaded parse: sync when given raw params, async when given a Promise.\n // This enables the ergonomic pattern: await def.parse(searchParams())\n function parse(raw: URLSearchParams | Record<string, string | string[] | undefined>): T;\n function parse(\n raw: Promise<URLSearchParams | Record<string, string | string[] | undefined>>\n ): Promise<T>;\n function parse(\n raw:\n | URLSearchParams\n | Record<string, string | string[] | undefined>\n | Promise<URLSearchParams | Record<string, string | string[] | undefined>>\n ): T | Promise<T> {\n if (raw instanceof Promise) {\n return raw.then(parseSync);\n }\n return parseSync(raw);\n }\n\n // ---- buildSearchParams ----\n //\n // Returns a query string. It used to have a URLSearchParams-returning\n // sibling (`toSearchParams`) that `<Link>` consumed; that shape cannot\n // cross the RSC Flight boundary (see the interface docstring), and having\n // two methods produce the same query two ways was a drift waiting to\n // happen. One method now.\n function buildSearchParams(values: Partial<T>): string {\n const parts: string[] = [];\n\n for (const prop of Object.keys(codecMap)) {\n if (!(prop in values)) continue;\n const codec = codecMap[prop as keyof T] as SearchParamCodec<unknown>;\n\n // TIM-1354: serialize may not be total over null — nuqs parsers like\n // parseAsIsoDate throw TypeError on null (null.toISOString()). Catch\n // TypeError and omit, matching what setParams does on the client.\n // Only TypeError — a deliberate throw (redirect(), notFound()) from a\n // codec's serialize must propagate, not be silently swallowed.\n let serialized: string | string[] | null;\n try {\n serialized = codec.serialize(values[prop as keyof T] as unknown);\n } catch (error) {\n if (error instanceof TypeError) continue;\n throw error;\n }\n\n if (serialized === null) continue;\n // Omit if serialized value matches the default\n if (serializedEqual(serialized, defaultSerialized[prop])) continue;\n\n // TIM-1353: string[] → repeated keys (?tag=a&tag=b)\n const urlKey = encodeURIComponent(getUrlKey(prop));\n if (Array.isArray(serialized)) {\n for (const entry of serialized) {\n parts.push(`${urlKey}=${encodeURIComponent(entry)}`);\n }\n } else {\n parts.push(`${urlKey}=${encodeURIComponent(serialized)}`);\n }\n }\n\n return parts.join('&');\n }\n\n // ---- href ----\n function href(pathname: string, values: Partial<T>): string {\n const qs = buildSearchParams(values);\n return qs ? `${pathname}?${qs}` : pathname;\n }\n\n // ---- extend ----\n function extend<U extends Record<string, SearchParamField>>(\n newCodecs: U\n ): SearchParamsDefinition<T & { [K in keyof U]: InferField<U[K]> }> {\n type Combined = T & { [K in keyof U]: InferField<U[K]> };\n\n // Resolve any Standard Schema objects in the extension\n const resolvedNewCodecs: Record<string, SearchParamCodec<unknown>> = {};\n const newUrlKeys: Record<string, string> = {};\n for (const [key, value] of Object.entries(newCodecs)) {\n const resolved = resolveField(key, value as SearchParamField);\n resolvedNewCodecs[key] = resolved.codec;\n if (resolved.urlKey) {\n newUrlKeys[key] = resolved.urlKey;\n }\n }\n\n const combinedCodecs = {\n ...codecMap,\n ...resolvedNewCodecs,\n } as unknown as CodecMap<Combined>;\n\n // Merge URL keys: base keys + new codec urlKeys from withUrlKey\n const combinedUrlKeys: Record<string, string> = { ...urlKeys, ...newUrlKeys };\n\n return buildDefinition<Combined>(combinedCodecs, combinedUrlKeys);\n }\n\n // ---- pick ----\n function pick<K extends keyof T & string>(...keys: K[]): SearchParamsDefinition<Pick<T, K>> {\n const pickedCodecs: Record<string, SearchParamCodec<unknown>> = {};\n const pickedUrlKeys: Record<string, string> = {};\n\n for (const key of keys) {\n // Explicit guard — TypeScript prevents this, but JS callers and\n // casts reach here, and \"Cannot read properties of undefined\n // (reading 'serialize')\" is no help (TIM-1066).\n if (!(key in codecMap)) {\n throw new Error(\n `[timber] pick('${key}'): unknown key. ` +\n `Available keys: ${Object.keys(codecMap)\n .map((k) => `'${k}'`)\n .join(', ')}.`\n );\n }\n pickedCodecs[key] = codecMap[key] as SearchParamCodec<unknown>;\n if (key in urlKeys) {\n pickedUrlKeys[key] = urlKeys[key];\n }\n }\n\n return buildDefinition<Pick<T, K>>(\n pickedCodecs as unknown as CodecMap<Pick<T, K>>,\n pickedUrlKeys\n );\n }\n\n // ---- useQueryStates ----\n // Delegates to the 'use client' implementation from use-query-states.ts.\n //\n // In the RSC environment: use-query-states.ts is transformed by the RSC\n // plugin into a client reference proxy. Calling it throws — correct,\n // because hooks can't run during server component rendering.\n // In SSR: use-query-states.ts is the real nuqs-backed function. Hooks\n // work during SSR's renderToReadableStream, so this works correctly.\n // On the client: same as SSR — the real function is available.\n function useQueryStates(options?: QueryStatesOptions): [T, SetParams<T>] {\n return clientUseQueryStates(codecMap, options, Object.freeze({ ...urlKeys })) as [\n T,\n SetParams<T>,\n ];\n }\n\n // ---- get ----\n // ALS-backed: reads getSearchParams() from the current request context\n // and parses through codecs. Server-only, sync.\n function get(): T {\n if (typeof window !== 'undefined') {\n throw new Error(\n '[timber] searchParams.get() is server-only. ' +\n 'Use searchParams.useQueryStates() on the client.'\n );\n }\n const raw = getSearchParamsFromAls();\n return parseSync(raw);\n }\n\n const definition: SearchParamsDefinition<T> = {\n parse,\n get,\n useQueryStates,\n extend,\n pick,\n href,\n buildSearchParams,\n codecs: codecMap,\n urlKeys: Object.freeze({ ...urlKeys }),\n };\n\n return definition;\n}\n","/**\n * Codec wrappers — withDefault and withUrlKey.\n *\n * These are timber-specific utilities that work with any SearchParamCodec.\n * For actual codecs (string, integer, boolean, etc.), use nuqs parsers\n * or Standard Schema objects (Zod, Valibot, ArkType) with auto-detection.\n *\n * Design doc: design/23-search-params.md\n */\n\nimport type {\n InferField,\n SearchParamCodec,\n SearchParamCodecWithUrlKey,\n SearchParamField,\n} from './define.ts';\nimport { isCodec, isStandardSchema, fromSchema } from '../schema-bridge.ts';\nimport { parseTotal } from './parse-total.ts';\n\n// ---------------------------------------------------------------------------\n// withDefault\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap a nullable codec with a default value. The output type becomes\n * non-nullable, and the wrapper is TOTAL over `string | string[] |\n * undefined` even when the inner codec is not.\n *\n * The default is substituted for `null` — the documented \"no value\"\n * answer — and for `undefined`, which is what an implicitly-optional\n * Standard Schema field and a bare `parseAsString` produce for an absent\n * param. Substituting only for `null` left a field typed non-nullable\n * `string` holding `undefined` (TIM-1350).\n *\n * The inner codec is invoked through `parseTotal`, so a nuqs parser gets\n * its own normalization (absent → null, repeated → first value, inner\n * throw → null) before either check applies. That is what makes\n * `withDefault(parseAsBoolean, false)` total; the wrapper itself does NOT\n * catch. A throw from a codec is a deliberate signal — `fromSchema` throws\n * on an async schema, and an app codec may `redirect()` or `notFound()` on\n * a value it refuses — and swallowing it would convert a loud failure into\n * a permanently-default field. design/09 §\"The SearchParamCodec Protocol\":\n * a codec that throws bubbles as a render-phase error, by design.\n *\n * Works with any codec — nuqs parsers, custom codecs, fromSchema results.\n *\n * ```ts\n * import { parseAsInteger } from 'nuqs/server'\n * import { withDefault } from '@timber-js/app/search-params'\n *\n * const page = withDefault(parseAsInteger, 1)\n * // page.parse(undefined) → 1 (not null)\n * // page.parse('5') → 5\n * ```\n *\n * The signature strips BOTH nullish constituents from the result, not just\n * `null`, because the runtime substitutes for both. An implicitly-optional\n * schema field is a `SearchParamCodec<string | undefined>`, and wrapping it\n * used to yield `SearchParamCodec<string | undefined>` — a field the\n * wrapper guarantees is always present, still typed as maybe-absent.\n */\nexport function withDefault<T>(\n codec: SearchParamCodec<T | null | undefined>,\n defaultValue: NonNullable<T>\n): SearchParamCodec<NonNullable<T>> {\n // A wrapper that rebuilds a codec from two methods drops everything else\n // the codec carries. `withUrlKey` lost `parseServerSide` that way; this\n // one lost `urlKey`, so `withDefault(withUrlKey(parseAsInteger, 'p'), 1)`\n // silently read `?page=` instead of `?p=`. Carry it explicitly rather\n // than spreading: this wrapper's own `parse` IS the total entry point,\n // and re-publishing the inner `parseServerSide` would let `parseTotal`\n // reach past it and skip the default entirely.\n const wrapped: SearchParamCodec<NonNullable<T>> = {\n parse(value: string | string[] | undefined): NonNullable<T> {\n const result = parseTotal(codec, value);\n return result === null || result === undefined ? defaultValue : result;\n },\n serialize(value: NonNullable<T>): string | string[] | null {\n return codec.serialize(value);\n },\n };\n if (codec.urlKey !== undefined) wrapped.urlKey = codec.urlKey;\n return wrapped;\n}\n\n// ---------------------------------------------------------------------------\n// withUrlKey\n// ---------------------------------------------------------------------------\n\n/**\n * Attach a URL key alias to a codec. The alias determines what query\n * parameter key is used in the URL, while the TypeScript property name\n * stays descriptive.\n *\n * Aliases travel with codecs through object spread composition — when\n * you spread a bundle containing aliased codecs into defineSearchParams,\n * the aliases come along automatically.\n *\n * ```ts\n * import { parseAsString } from 'nuqs/server'\n * import { withUrlKey } from '@timber-js/app/search-params'\n *\n * export const searchable = {\n * q: withUrlKey(parseAsString, 'search'),\n * // ?search=shoes → { q: 'shoes' }\n * }\n * ```\n *\n * Composes with withDefault:\n * ```ts\n * import { parseAsInteger } from 'nuqs/server'\n * withUrlKey(withDefault(parseAsInteger, 1), 'p')\n * ```\n */\nexport function withUrlKey<F extends SearchParamField>(\n codecOrSchema: F,\n urlKey: string\n): SearchParamCodecWithUrlKey<InferField<F>> {\n type T = InferField<F>;\n // Auto-detect Standard Schema (Zod, Valibot, ArkType) and wrap. Schemas\n // that reject undefined input are implicitly optional — fromSchema returns\n // undefined for absent params, and InferField widens the type to include\n // undefined. design/23-search-params.md §\"Implicit Optionality\"\n const codec: SearchParamCodec<T> = isCodec(codecOrSchema)\n ? (codecOrSchema as SearchParamCodec<T>)\n : isStandardSchema(codecOrSchema)\n ? (fromSchema(codecOrSchema) as SearchParamCodec<T>)\n : (codecOrSchema as SearchParamCodec<T>);\n // Carry the total entry point, bound like the other two methods. A\n // codec's totality lives in a THIRD property, `parseServerSide` (see\n // parse-total.ts); picking only `parse`/`serialize` silently produced a\n // non-total alias, so `withUrlKey(parseAsBoolean, 'b')` threw on an\n // absent param while the bare parser did not (TIM-1350).\n //\n // Bound explicitly rather than spread: a spread copies own enumerable\n // properties only, so a class-based codec — whose `parse` and\n // `serialize` this wrapper already reaches through the prototype —\n // would have kept its methods and lost exactly the one that makes it\n // total. Three properties, one rule, no dependence on how the inner\n // codec was constructed.\n const wrapped: SearchParamCodecWithUrlKey<T> = {\n parse: codec.parse.bind(codec),\n serialize: codec.serialize.bind(codec),\n urlKey,\n };\n if (typeof codec.parseServerSide === 'function') {\n wrapped.parseServerSide = codec.parseServerSide.bind(codec);\n }\n return wrapped;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4SA,SAAS,aACP,KAC+C;CAC/C,IAAI,eAAe,iBAAiB;EAClC,MAAM,SAAwD,OAAO,OAAO,IAAI;EAChF,KAAK,MAAM,OAAO,IAAI,IAAI,IAAI,KAAK,CAAC,GAAG;GACrC,MAAM,SAAS,IAAI,OAAO,GAAG;GAC7B,OAAO,OAAO,OAAO,WAAW,IAAI,OAAO,KAA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AA4C;EAChD,MAAM,OAAsD;GAC1D,MAAM,SAAS,WAAW,OAAO,KAAK;GACtC,OAAO,WAAW,QAAQ,WAAW,KAAA,IAAY,eAAe;EAClE;EACA,UAAU,OAAiD;GACzD,OAAO,MAAM,UAAU,KAAK;EAC9B;CACF;CACA,IAAI,MAAM,WAAW,KAAA,GAAW,QAAQ,SAAS,MAAM;CACvD,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,WACd,eACA,QAC2C;CAM3C,MAAM,QAA6B,QAAQ,aAAa,IACnD,gBACD,iBAAiB,aAAa,IAC3B,WAAW,aAAa,IACxB;CAaP,MAAM,UAAyC;EAC7C,OAAO,MAAM,MAAM,KAAK,KAAK;EAC7B,WAAW,MAAM,UAAU,KAAK,KAAK;EACrC;CACF;CACA,IAAI,OAAO,MAAM,oBAAoB,YACnC,QAAQ,kBAAkB,MAAM,gBAAgB,KAAK,KAAK;CAE5D,OAAO;AACT"}
|
|
@@ -168,6 +168,39 @@ export function ProductFilters() {
|
|
|
168
168
|
|
|
169
169
|
By default, `.useQueryStates()` triggers an RSC navigation when params change. Set `shallow: true` to update the URL without a server roundtrip.
|
|
170
170
|
|
|
171
|
+
### Debouncing and Other Options
|
|
172
|
+
|
|
173
|
+
`.useQueryStates(options)` and `setParams(values, options)` accept every [nuqs option](https://nuqs.dev/docs/options), and timber passes them through. Options you pass to `setParams` override the ones you pass to the hook.
|
|
174
|
+
|
|
175
|
+
Without a limit, a search box asks the server for a new page on every keystroke. Debounce it, and it sends one request after the user stops typing:
|
|
176
|
+
|
|
177
|
+
```tsx title="app/products/search-box.tsx" use="search-params"
|
|
178
|
+
'use client';
|
|
179
|
+
import { debounce, defaultRateLimit } from '@timber-js/app/search-params';
|
|
180
|
+
import { searchParams } from './search-params';
|
|
181
|
+
|
|
182
|
+
const query = searchParams.pick('q');
|
|
183
|
+
|
|
184
|
+
export function SearchBox() {
|
|
185
|
+
const [{ q }, setParams] = query.useQueryStates({ limitUrlUpdates: debounce(300) });
|
|
186
|
+
|
|
187
|
+
return (
|
|
188
|
+
<input
|
|
189
|
+
value={q ?? ''}
|
|
190
|
+
onChange={(e) => setParams({ q: e.target.value || null })}
|
|
191
|
+
// Enter searches now instead of waiting for the debounce.
|
|
192
|
+
onKeyDown={(e) => {
|
|
193
|
+
if (e.key === 'Enter') setParams({ q }, { limitUrlUpdates: defaultRateLimit });
|
|
194
|
+
}}
|
|
195
|
+
/>
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
The input updates as the user types. Only the URL write, and the server request that follows it, waits. If the user goes to another page before a pending write lands, timber drops the write, so it can't pull them back. Use `throttle(ms)` to allow at most one write per interval. `debounce`, `throttle` and `defaultRateLimit` come from nuqs. `@timber-js/app/search-params` re-exports them, so you don't import nuqs yourself.
|
|
201
|
+
|
|
202
|
+
timber changes two nuqs defaults: `shallow: false`, so every write fetches fresh server data, and `scroll: true`. It also sets `urlKeys` from your `withUrlKey` aliases, so `urlKeys` isn't an option you can pass. Pass options to the hook or to `setParams`. Options set on a nuqs parser with `.withOptions()` are ignored. `startTransition` doesn't give you a loading state for the server request; use `usePendingNavigation()` for that.
|
|
203
|
+
|
|
171
204
|
## Cookies
|
|
172
205
|
|
|
173
206
|
Define typed cookies with `defineCookie()`:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@timber-js/app",
|
|
3
|
-
"version": "0.2.0-alpha.
|
|
3
|
+
"version": "0.2.0-alpha.232",
|
|
4
4
|
"description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare-workers",
|
|
@@ -172,7 +172,7 @@
|
|
|
172
172
|
"@typescript/native-preview": "^7.0.0-dev.0",
|
|
173
173
|
"@vitejs/plugin-react": "^6.1.0",
|
|
174
174
|
"@vitejs/plugin-rsc": "^0.5.39",
|
|
175
|
-
"nuqs": "^2.
|
|
175
|
+
"nuqs": "^2.7.0",
|
|
176
176
|
"react": "19.3.1",
|
|
177
177
|
"react-dom": "19.3.1",
|
|
178
178
|
"satteri": "^0.10.5 || ^0.11.5",
|
|
@@ -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
|
|
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:
|
|
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];
|