@octanejs/nuqs 0.1.0

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.
@@ -0,0 +1,167 @@
1
+ import { createElement, useCallback, useEffect, useRef, useState, type OctaneNode } from 'octane';
2
+ import { resetQueues } from '../lib/queues/reset';
3
+ import { renderQueryString } from './custom';
4
+ import { context, type AdapterProps } from './lib/context';
5
+ import type { AdapterInterface, AdapterOptions } from './lib/defs';
6
+
7
+ export type UrlUpdateEvent = {
8
+ searchParams: URLSearchParams;
9
+ queryString: string;
10
+ options: Required<AdapterOptions>;
11
+ };
12
+
13
+ export type OnUrlUpdateFunction = (event: UrlUpdateEvent) => void;
14
+
15
+ type TestingAdapterProps = Pick<AdapterInterface, 'autoResetQueueOnUpdate'> & {
16
+ /**
17
+ * An initial value for the search params.
18
+ */
19
+ searchParams?: string | Record<string, string> | URLSearchParams;
20
+
21
+ /**
22
+ * A function that will be called whenever the URL is updated.
23
+ * Connect that to a spy in your tests to assert the URL updates.
24
+ */
25
+ onUrlUpdate?: OnUrlUpdateFunction;
26
+
27
+ /**
28
+ * Internal: enable throttling during tests.
29
+ *
30
+ * @default 0 (no throttling)
31
+ */
32
+ rateLimitFactor?: number;
33
+
34
+ /**
35
+ * Internal: Whether to reset the url update queue on mount.
36
+ *
37
+ * Since the update queue is a shared global, each test clears
38
+ * it on mount to avoid interference between tests.
39
+ *
40
+ * @default true
41
+ */
42
+ resetUrlUpdateQueueOnMount?: boolean;
43
+
44
+ /**
45
+ * If true, the adapter will store the search params in memory and
46
+ * update that memory on each updateUrl call, to simulate a real adapter.
47
+ *
48
+ * Otherwise, the search params will be frozen to the initial value.
49
+ *
50
+ * @default false
51
+ */
52
+ hasMemory?: boolean;
53
+
54
+ children: OctaneNode;
55
+ } & AdapterProps;
56
+
57
+ function renderInitialSearchParams(searchParams: TestingAdapterProps['searchParams']): string {
58
+ if (!searchParams) {
59
+ return '';
60
+ }
61
+ if (typeof searchParams === 'string') {
62
+ return searchParams;
63
+ }
64
+ if (searchParams instanceof URLSearchParams) {
65
+ return searchParams.toString();
66
+ }
67
+ return new URLSearchParams(searchParams).toString();
68
+ }
69
+
70
+ export function NuqsTestingAdapter({
71
+ resetUrlUpdateQueueOnMount = true,
72
+ autoResetQueueOnUpdate = true,
73
+ defaultOptions,
74
+ processUrlSearchParams,
75
+ rateLimitFactor = 0,
76
+ hasMemory = false,
77
+ onUrlUpdate,
78
+ children,
79
+ searchParams: initialSearchParams = '',
80
+ }: TestingAdapterProps): OctaneNode {
81
+ const renderedInitialSearchParams = renderInitialSearchParams(initialSearchParams);
82
+ // Simulate a central location.search in memory
83
+ // for the getSearchParamsSnapshot to be referentially stable.
84
+ const locationSearchRef = useRef(renderedInitialSearchParams);
85
+ // Reset the shared update queue ONCE per mount, during the first render, so a
86
+ // previous test's leftover queued updates can't leak into this tree's initial
87
+ // parse. It must run during render (not a mount effect): child useQueryStates
88
+ // reads the queue via useQueuedQueries during its OWN first render, which
89
+ // happens after this provider renders — an effect would run too late and the
90
+ // first child render would parse a dirty queue. The ref guard keeps it to the
91
+ // first render only, so re-renders (e.g. hasMemory's setSearchParams after a
92
+ // flush) don't re-abort the queue and drop in-flight/follow-up URL writes.
93
+ // DIVERGENCE FROM nuqs: upstream runs resetQueues() on every render; the guard
94
+ // is octane-side only and is safe because octane has no StrictMode
95
+ // double-invoke of render, so the reset still fires exactly once on mount.
96
+ const didResetQueueRef = useRef(false);
97
+ if (resetUrlUpdateQueueOnMount && !didResetQueueRef.current) {
98
+ didResetQueueRef.current = true;
99
+ resetQueues();
100
+ }
101
+ const [searchParams, setSearchParams] = useState(
102
+ () => new URLSearchParams(locationSearchRef.current),
103
+ );
104
+ useEffect(() => {
105
+ if (!hasMemory) {
106
+ return;
107
+ }
108
+ const synced = new URLSearchParams(initialSearchParams);
109
+ setSearchParams(synced);
110
+ locationSearchRef.current = synced.toString();
111
+ }, [hasMemory, renderedInitialSearchParams]);
112
+ const updateUrl = useCallback<AdapterInterface['updateUrl']>(
113
+ (search, options) => {
114
+ const queryString = renderQueryString(search);
115
+ const searchParams = new URLSearchParams(search); // make a copy
116
+ if (hasMemory) {
117
+ setSearchParams(searchParams);
118
+ locationSearchRef.current = queryString;
119
+ }
120
+ onUrlUpdate?.({
121
+ searchParams,
122
+ queryString,
123
+ options,
124
+ });
125
+ },
126
+ [onUrlUpdate, hasMemory],
127
+ );
128
+ const getSearchParamsSnapshot = useCallback(() => {
129
+ return new URLSearchParams(locationSearchRef.current);
130
+ }, [renderedInitialSearchParams]);
131
+ const useAdapter = (): AdapterInterface => ({
132
+ searchParams,
133
+ updateUrl,
134
+ getSearchParamsSnapshot,
135
+ rateLimitFactor,
136
+ autoResetQueueOnUpdate,
137
+ });
138
+ return createElement(
139
+ context.Provider,
140
+ { value: { useAdapter, defaultOptions, processUrlSearchParams } },
141
+ children,
142
+ );
143
+ }
144
+
145
+ /**
146
+ * A higher order component that wraps the children with the NuqsTestingAdapter
147
+ *
148
+ * It allows creating wrappers for testing purposes by providing only the
149
+ * necessary props to the NuqsTestingAdapter.
150
+ *
151
+ * Usage:
152
+ * ```tsx
153
+ * render(<MyComponent />, {
154
+ * wrapper: withNuqsTestingAdapter({ searchParams: '?foo=bar' })
155
+ * })
156
+ * ```
157
+ */
158
+ export function withNuqsTestingAdapter(props: Omit<TestingAdapterProps, 'children'> = {}) {
159
+ return function NuqsTestingAdapterWrapper({ children }: { children: OctaneNode }): OctaneNode {
160
+ return createElement(
161
+ NuqsTestingAdapter,
162
+ // @ts-expect-error - Ignore missing children error
163
+ props,
164
+ children,
165
+ );
166
+ };
167
+ }
package/src/debug.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { isDebugFlagSet, setDebugSink } from './lib/debug';
2
+ import { debugMessages, sprintf } from './lib/debug-messages';
3
+
4
+ // Side-effect-only entry point (`nuqs/debug`): importing it opts client-side
5
+ // debug logging into the bundle. The format-string catalog and formatting logic
6
+ // live here rather than in the core, so they only ship when a consumer imports
7
+ // this module.
8
+ //
9
+ // Logging stays gated behind the `debug=nuqs` key in localStorage — set it and
10
+ // reload, as before. Server-side, `nuqs/server` wires this in automatically,
11
+ // gated by the `DEBUG=nuqs` env var (the server bundle has more headroom).
12
+ //
13
+ // @example
14
+ // ```ts
15
+ // import 'nuqs/debug' // once, anywhere in your app
16
+ // // Enable logs at runtime:
17
+ // localStorage.debug = 'nuqs' // on the client
18
+ // process.env.DEBUG = 'nuqs' // on the server
19
+ // ```
20
+ function installDebugSink(): void {
21
+ setDebugSink((code, args, isWarn) => {
22
+ const message = debugMessages[code];
23
+ if (isWarn) {
24
+ console.warn(message, ...args);
25
+ return;
26
+ }
27
+ const formatted = sprintf(message, ...args);
28
+ performance.mark(formatted);
29
+ try {
30
+ // Handle React Devtools not being able to console.log('%s', null)
31
+ console.log(message, ...args);
32
+ } catch {
33
+ console.log(formatted);
34
+ }
35
+ });
36
+ }
37
+
38
+ // Respect the localStorage/DEBUG flag as soon as this entry loads, so
39
+ // `import 'nuqs/debug'` is all that's needed to turn logging on.
40
+ if (isDebugFlagSet()) {
41
+ installDebugSink();
42
+ }
package/src/defs.ts ADDED
@@ -0,0 +1,129 @@
1
+ // Ported from react's `TransitionStartFunction`. Octane's `useTransition`
2
+ // returns a function of this shape (a Promise-returning scope turns the
3
+ // transition into an async action). Declared locally so the framework-agnostic
4
+ // core carries no `react` type dependency — the octane binding never imports
5
+ // `@types/react`.
6
+ export type TransitionStartFunction = (callback: () => void | Promise<void>) => void;
7
+
8
+ export type SearchParams = Record<string, string | string[] | undefined>;
9
+ export type HistoryOptions = 'replace' | 'push';
10
+ export type LimitUrlUpdates =
11
+ | { method: 'debounce'; timeMs: number }
12
+ | { method: 'throttle'; timeMs: number };
13
+
14
+ export type Options = {
15
+ /**
16
+ * How the query update affects page history
17
+ *
18
+ * `push` will create a new history entry, allowing to use the back/forward
19
+ * buttons to navigate state updates.
20
+ * `replace` (default) will keep the current history point and only replace
21
+ * the query string.
22
+ */
23
+ history?: HistoryOptions;
24
+
25
+ /**
26
+ * Scroll to top after a query state update
27
+ *
28
+ * Defaults to `false`, unlike the Next.js router page navigation methods.
29
+ */
30
+ scroll?: boolean;
31
+
32
+ /**
33
+ * Shallow mode (true by default) keeps query states update client-side only,
34
+ * meaning there won't be calls to the server.
35
+ *
36
+ * Setting it to `false` will trigger a network request to the server with
37
+ * the updated querystring.
38
+ */
39
+ shallow?: boolean;
40
+
41
+ /**
42
+ * Maximum amount of time (ms) to wait between updates of the URL query string.
43
+ *
44
+ * This is to alleviate rate-limiting of the Web History API in browsers,
45
+ * and defaults to 50ms. Safari requires a higher value of around 120ms.
46
+ *
47
+ * Note: the value will be limited to a minimum of 50ms, anything lower
48
+ * will not have any effect.
49
+ *
50
+ * @deprecated use `limitUrlUpdates: { 'method': 'throttle', timeMs: number }`
51
+ * or use the shorthand:
52
+ * ```ts
53
+ * import { throttle } from 'nuqs'
54
+ *
55
+ * limitUrlUpdates: throttle(100) // time in ms
56
+ * ```
57
+ */
58
+ throttleMs?: number;
59
+
60
+ /**
61
+ * Limit the rate of URL updates to prevent spamming the browser history,
62
+ * and the server if `shallow: false`.
63
+ *
64
+ * This is to alleviate rate-limiting of the Web History API in browsers,
65
+ * and defaults to 50ms. Safari requires a higher value of around 120ms.
66
+ *
67
+ * Note: the value will be limited to a minimum of 50ms, anything lower
68
+ * will not have any effect.
69
+ *
70
+ * If both `throttleMs` and `limitUrlUpdates` are set, `limitUrlUpdates` will
71
+ * take precedence.
72
+ */
73
+ limitUrlUpdates?: LimitUrlUpdates;
74
+
75
+ /**
76
+ * In RSC frameworks, opt-in to observing Server Component loading states when
77
+ * doing non-shallow updates by passing a `startTransition` from the
78
+ * `React.useTransition()` hook.
79
+ *
80
+ * In other frameworks, navigation events triggered by a query update can also
81
+ * be wrapped in a transition this way (e.g. `React.startTransition`).
82
+ */
83
+ startTransition?: TransitionStartFunction;
84
+
85
+ /**
86
+ * Clear the key-value pair from the URL query string when setting the state
87
+ * to the default value.
88
+ *
89
+ * Defaults to `true` to keep URLs clean.
90
+ *
91
+ * Set it to `false` to keep backwards-compatiblity when the default value
92
+ * changes (prefer explicit URLs whose meaning don't change).
93
+ */
94
+ clearOnDefault?: boolean;
95
+ };
96
+
97
+ export type Nullable<T> = {
98
+ [K in keyof T]: T[K] | null;
99
+ } & {};
100
+
101
+ /**
102
+ * Helper type to define and reuse urlKey options to rename search params keys
103
+ *
104
+ * Usage:
105
+ * ```ts
106
+ * import { type UrlKeys } from 'nuqs' // or 'nuqs/server'
107
+ *
108
+ * export const coordinatesSearchParams = {
109
+ * latitude: parseAsFloat.withDefault(0),
110
+ * longitude: parseAsFloat.withDefault(0),
111
+ * }
112
+ * export const coordinatesUrlKeys: UrlKeys<typeof coordinatesSearchParams> = {
113
+ * latitude: 'lat',
114
+ * longitude: 'lng',
115
+ * }
116
+ *
117
+ * // Later in the code:
118
+ * useQueryStates(coordinatesSearchParams, {
119
+ * urlKeys: coordinatesUrlKeys
120
+ * })
121
+ * createSerializer(coordinatesSearchParams, {
122
+ * urlKeys: coordinatesUrlKeys
123
+ * })
124
+ * createSearchParamsCache(coordinatesSearchParams, {
125
+ * urlKeys: coordinatesUrlKeys
126
+ * })
127
+ * ```
128
+ */
129
+ export type UrlKeys<Parsers extends Record<string, any>> = Partial<Record<keyof Parsers, string>>;
@@ -0,0 +1,23 @@
1
+ // `@octanejs/nuqs/server` — the server-safe surface: parsers, serializer and
2
+ // loader for reading/writing search params outside of a component (SSR data
3
+ // loading, link building, tests). It ships NONE of the octane hooks, so it is
4
+ // safe to import from server-only modules.
5
+ //
6
+ // DIVERGENCE FROM nuqs/server: `createSearchParamsCache` is NOT exported. It is
7
+ // built on React Server Components' `React.cache()`, which octane does not
8
+ // implement (no Server Components — see octane's "differences from React").
9
+ // Use `createLoader` for equivalent request-scoped parsing.
10
+ import './debug';
11
+
12
+ export type { HistoryOptions, Nullable, Options, SearchParams, UrlKeys } from './defs';
13
+ export { debounce, defaultRateLimit, throttle } from './lib/queues/rate-limiting';
14
+ export {
15
+ createLoader,
16
+ type LoaderFunction,
17
+ type LoaderInput,
18
+ type LoaderOptions,
19
+ type CreateLoaderOptions,
20
+ } from './loader';
21
+ export * from './parsers';
22
+ export { createSerializer, type CreateSerializerOptions } from './serializer';
23
+ export { createStandardSchemaV1, type CreateStandardSchemaV1Options } from './standard-schema';
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ export type { HistoryOptions, Nullable, Options, SearchParams, UrlKeys } from './defs';
2
+ export { debounce, defaultRateLimit, throttle } from './lib/queues/rate-limiting';
3
+ export {
4
+ createLoader,
5
+ type LoaderFunction,
6
+ type LoaderInput,
7
+ type LoaderOptions,
8
+ type CreateLoaderOptions,
9
+ } from './loader';
10
+ export * from './parsers';
11
+ export { createSerializer, type CreateSerializerOptions } from './serializer';
12
+ export { createStandardSchemaV1, type CreateStandardSchemaV1Options } from './standard-schema';
13
+ export * from './useQueryState';
14
+ export * from './useQueryStates';
@@ -0,0 +1,20 @@
1
+ import type { Query } from './search-params';
2
+
3
+ export function compareQuery<T extends Query>(a: T | null, b: T | null): boolean {
4
+ if (a === b) {
5
+ return true; // Referentially stable
6
+ }
7
+ if (a === null || b === null) {
8
+ return false;
9
+ }
10
+ // we expect either strings or arrays, not a mix of both
11
+ if (typeof a === 'string' || typeof b === 'string') {
12
+ return false;
13
+ }
14
+
15
+ if (a.length !== b.length) {
16
+ return false;
17
+ }
18
+
19
+ return a.every((value, index) => value === b[index]!);
20
+ }
@@ -0,0 +1,18 @@
1
+ import type { TransitionStartFunction } from '../defs';
2
+
3
+ export function compose(
4
+ fns: TransitionStartFunction[],
5
+ // A Promise return turns the innermost transition into an async action
6
+ // (React 19), keeping its isPending true until the promise settles.
7
+ final: () => void | Promise<void>,
8
+ ): void {
9
+ // Build a nested callback chain iteratively (avoids recursion helper)
10
+ let next: () => void | Promise<void> = final;
11
+ for (let i = fns.length - 1; i >= 0; i--) {
12
+ const fn = fns[i];
13
+ if (!fn) continue;
14
+ const prev = next;
15
+ next = () => fn(prev);
16
+ }
17
+ next();
18
+ }
@@ -0,0 +1,92 @@
1
+ // Debug log messages, keyed by the numeric code passed to `debug`/`warn`.
2
+ //
3
+ // Kept out of the client main bundle on purpose: only the `nuqs/debug` entry
4
+ // (`src/debug.ts`) and the server entry (`src/index.server.ts`) import these
5
+ // values, so the format strings never reach the client `index.js` unless logging
6
+ // is opted into via `import 'nuqs/debug'`. The server bundle pulls them in
7
+ // eagerly (it has more headroom). Call sites in the core pass the code only —
8
+ // mirroring the `errors.ts` code-catalog pattern.
9
+ export const debugMessages = {
10
+ // useQueryStates
11
+ 1: '[nuq+ %s `%s`] State changed: %O',
12
+ 2: '[nuq+ %s `%s`] Cross-hook key sync %s: %O (default: %O). no change, skipping, resolved: %O',
13
+ 3: '[nuq+ %s `%s`] Cross-hook key sync %s: %O (default: %O). updateInternalState, resolved: %O',
14
+ 4: '[nuq+ %s `%s`] Subscribing to sync for `%s`',
15
+ 5: '[nuq+ %s `%s`] Unsubscribing to sync for `%s`',
16
+ 6: '[nuq+ %s `%s`] setState: %O',
17
+ // Throttle queue (gtq)
18
+ 7: '[nuqs gtq] Enqueueing %s=%s %O',
19
+ 8: '[nuqs gtq] Skipping flush due to throttleMs=Infinity',
20
+ 9: '[nuqs gtq] Scheduling flush in %f ms. Throttled at %f ms (x%f)',
21
+ 10: '[nuqs gtq] Resetting queue %s',
22
+ 11: '[nuqs gtq] Applying %d pending update(s) on top of %s',
23
+ 12: '[nuqs gtq] Flushing queue %O with options %O',
24
+ // Debounce queue (dq / dqc)
25
+ 13: '[nuqs dq] Flushing debounce queue %O',
26
+ 14: '[nuqs dq] Reset debounce queue %O',
27
+ 15: '[nuqs dqc] Creating debounce queue for `%s`',
28
+ 16: '[nuqs dqc] Cleaning up empty queue for `%s`',
29
+ 17: '[nuqs dqc] Enqueueing debounce update %O',
30
+ 18: '[nuqs dqc] Aborting debounce queue %s=%s',
31
+ // Queue reset
32
+ 19: '[nuqs] Aborting queues',
33
+ // Adapters
34
+ 20: '[nuqs %s] Updating url: %s',
35
+ 21: '[nuqs %s] Patching history (%s adapter)',
36
+ 22: '[nuqs `%s`] no change, returning previous: %O',
37
+ 23: `[nuqs \`%s\`] subbed search params change
38
+ from %O
39
+ to %O`,
40
+ // safe-parse
41
+ 24: '[nuqs] Error while parsing value `%s`: %O',
42
+ 25: '[nuqs] Error while parsing value `%s`: %O (for key `%s`)',
43
+ } as const;
44
+
45
+ /**
46
+ * The set of valid debug codes — the keys of {@link debugMessages}.
47
+ *
48
+ * This makes the catalog the single source of truth for which codes exist:
49
+ * `debug`/`warn` only accept a `DebugCode`, so an out-of-range code is a type
50
+ * error at the call site.
51
+ */
52
+ export type DebugCode = keyof typeof debugMessages;
53
+
54
+ // The type of a `%s` argument. `sprintf` (and the browser console) coerce with
55
+ // `String(arg)`, so anything with a `toString` — `URL`, `URLSearchParams`,
56
+ // primitives… — is valid. (`%d`/`%f` narrow to `number`; `%O` accepts `unknown`.)
57
+ type Stringifiable = { toString(): string } | null | undefined;
58
+ type ArgType<Spec extends string> = Spec extends 'O'
59
+ ? unknown
60
+ : Spec extends 'd' | 'f'
61
+ ? number
62
+ : Spec extends 's'
63
+ ? Stringifiable
64
+ : never;
65
+
66
+ // Walk a format string left → right, accumulating one tuple slot per
67
+ // %s/%d/%f/%O placeholder — mirroring `sprintf`'s `/%[sfdO]/g`. The `infer`-led
68
+ // prefix matches the *first* `%`, so placeholders are parsed in order.
69
+ type ParseArgs<
70
+ S extends string,
71
+ Acc extends unknown[] = [],
72
+ > = S extends `${infer _Pre}%${infer Rest}`
73
+ ? Rest extends `${infer Spec}${infer Tail}`
74
+ ? Spec extends 's' | 'd' | 'f' | 'O'
75
+ ? ParseArgs<Tail, [...Acc, ArgType<Spec>]>
76
+ : ParseArgs<Rest, Acc>
77
+ : Acc
78
+ : Acc;
79
+
80
+ /**
81
+ * The argument tuple a debug code requires, derived from the `%` placeholders in
82
+ * its message. The catalog string is therefore the single source of truth for
83
+ * both the set of codes ({@link DebugCode}) and the shape of their arguments.
84
+ */
85
+ export type DebugArgs<Code extends DebugCode> = ParseArgs<(typeof debugMessages)[Code]>;
86
+
87
+ export function sprintf(base: string, ...args: any[]): string {
88
+ return base.replace(/%[sfdO]/g, (match) => {
89
+ const arg = args.shift();
90
+ return match === '%O' && arg ? JSON.stringify(arg).replace(/"([^"]+)":/g, '$1:') : String(arg);
91
+ });
92
+ }
@@ -0,0 +1,49 @@
1
+ // Type-only import: erased at build time (verbatimModuleSyntax), so the message
2
+ // catalog's *types* constrain the call sites here while its *values* stay out of
3
+ // the core bundle (they only ship via the opt-in `nuqs/debug` entry).
4
+ import type { DebugArgs, DebugCode } from './debug-messages';
5
+
6
+ export type DebugSink = (code: DebugCode, args: unknown[], isWarn?: boolean) => void;
7
+
8
+ let sink: DebugSink | null = null;
9
+
10
+ /**
11
+ * Install (or remove, with `null`) the function that renders debug logs.
12
+ */
13
+ export function setDebugSink(newSink: DebugSink | null): void {
14
+ sink = newSink;
15
+ }
16
+
17
+ export function debug<Code extends DebugCode>(code: Code, ...args: DebugArgs<Code>): void {
18
+ sink?.(code, args);
19
+ }
20
+
21
+ export function warn<Code extends DebugCode>(code: Code, ...args: DebugArgs<Code>): void {
22
+ sink?.(code, args, true);
23
+ }
24
+
25
+ export function isDebugFlagSet(): boolean {
26
+ // Issue: https://github.com/47ng/nuqs/issues/1336
27
+ // Backend (Node/server): use DEBUG env var, never touch localStorage.
28
+ // --localstorage-file triggers a warning.
29
+ if (typeof window === 'undefined') {
30
+ return (process.env.DEBUG || '').includes('nuqs');
31
+ }
32
+
33
+ // Check if localStorage is available.
34
+ // It may be unavailable in some environments,
35
+ // like Safari in private browsing mode.
36
+ // See https://github.com/47ng/nuqs/pull/588
37
+ try {
38
+ const test = 'nuqs-localStorage-test';
39
+ if (typeof localStorage === 'undefined') {
40
+ return false;
41
+ }
42
+ localStorage.setItem(test, test);
43
+ const isStorageAvailable = localStorage.getItem(test) === test;
44
+ localStorage.removeItem(test);
45
+ return isStorageAvailable && (localStorage.getItem('debug') || '').includes('nuqs');
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
@@ -0,0 +1,36 @@
1
+ export type Emitter<Events extends Record<string, unknown>> = {
2
+ on<Key extends keyof Events>(type: Key, handler: (event: Events[Key]) => any): () => void;
3
+ off<Key extends keyof Events>(type: Key, handler?: (event: Events[Key]) => any): void;
4
+ emit<Key extends keyof Events>(
5
+ type: Key,
6
+ event?: Events[Key] extends undefined ? never : Events[Key],
7
+ ): void;
8
+ };
9
+
10
+ export function createEmitter<Events extends Record<string, unknown>>(): Emitter<Events> {
11
+ const all: Map<keyof Events, Array<(event: Events[keyof Events]) => any>> = new Map();
12
+ return {
13
+ on<Key extends keyof Events>(type: Key, handler: (event: Events[Key]) => any): () => void {
14
+ const handlers = all.get(type) || [];
15
+ handlers.push(handler as (event: Events[keyof Events]) => any);
16
+ all.set(type, handlers);
17
+ return () => this.off(type, handler);
18
+ },
19
+ off<Key extends keyof Events>(type: Key, handler: (event: Events[Key]) => any): void {
20
+ const handlers = all.get(type);
21
+ if (handlers) {
22
+ all.set(
23
+ type,
24
+ handlers.filter((h) => h !== handler),
25
+ );
26
+ }
27
+ },
28
+ emit<Key extends keyof Events>(
29
+ type: Key,
30
+ event?: Events[Key] extends undefined ? never : Events[Key],
31
+ ): void {
32
+ const handlers = all.get(type);
33
+ handlers?.forEach((handler) => handler(event as Events[keyof Events]));
34
+ },
35
+ };
36
+ }
@@ -0,0 +1,14 @@
1
+ export const errors = {
2
+ 303: 'Multiple adapter contexts detected. This might happen in monorepos.',
3
+ 404: 'nuqs requires an adapter to work with your framework.',
4
+ 409: 'Multiple versions of the library are loaded. This may lead to unexpected behavior. Currently using `%s`, but `%s` (via the %s adapter) was about to load on top.',
5
+ 414: 'Max safe URL length exceeded. Some browsers may not be able to accept this URL. Consider limiting the amount of state stored in the URL.',
6
+ 429: 'URL update rate-limited by the browser. Consider increasing `throttleMs` for key(s) `%s`. %O',
7
+ 500: "Empty search params cache. Search params can't be accessed in Layouts.",
8
+ 501: 'Search params cache already populated. Have you called `parse` twice?',
9
+ } as const;
10
+
11
+ export function error(code: keyof typeof errors) {
12
+ return `[nuqs] ${errors[code]}
13
+ See https://nuqs.dev/NUQS-${code}`;
14
+ }
@@ -0,0 +1,37 @@
1
+ import { version } from './version';
2
+
3
+ type GlobalRegistry = {
4
+ [key: symbol]: unknown;
5
+ };
6
+
7
+ const fallbackRegistry: GlobalRegistry = {};
8
+
9
+ /**
10
+ * Store a module-level singleton on globalThis, keyed by library version,
11
+ * so that duplicate copies of the library loaded side by side (e.g. in
12
+ * monorepos, see issue #798) share the same instance instead of each
13
+ * creating their own. Copies of different versions deliberately keep
14
+ * separate instances, as internal state shapes may differ across versions.
15
+ */
16
+ export function globalSingleton<T>(scope: string, create: () => T): T {
17
+ const key = Symbol.for(`nuqs.${version}.${scope}`);
18
+ const registry = globalThis as GlobalRegistry;
19
+ if (registry[key] != null) {
20
+ return registry[key] as T;
21
+ }
22
+ const target = Object.isExtensible(registry) ? registry : fallbackRegistry;
23
+ return (target[key] ??= create()) as T;
24
+ }
25
+
26
+ /**
27
+ * Like globalSingleton, but additionally keyed by the identity of a
28
+ * runtime object, for singletons that must not be shared across distinct
29
+ * runtimes (e.g. one React context per React instance).
30
+ */
31
+ export function globalWeakSingleton<T>(scope: string, key: WeakKey, create: () => T): T {
32
+ const instances = globalSingleton(scope, () => new WeakMap<WeakKey, unknown>());
33
+ if (!instances.has(key)) {
34
+ instances.set(key, create());
35
+ }
36
+ return instances.get(key) as T;
37
+ }