@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.
package/src/loader.ts ADDED
@@ -0,0 +1,154 @@
1
+ import type { UrlKeys } from './defs';
2
+ import { isAbsentFromUrl } from './lib/search-params';
3
+ import type { inferParserType, ParserMap } from './parsers';
4
+
5
+ export type LoaderInput =
6
+ | URL
7
+ | Request
8
+ | URLSearchParams
9
+ | Record<string, string | string[] | undefined>
10
+ | string;
11
+
12
+ /**
13
+ * @deprecated Use `CreateLoaderOptions` instead.
14
+ */
15
+ export type LoaderOptions<Parsers extends ParserMap> = {
16
+ urlKeys?: UrlKeys<Parsers>;
17
+ };
18
+ export type CreateLoaderOptions<P extends ParserMap> = LoaderOptions<P>;
19
+ export type LoaderFunctionOptions = {
20
+ /**
21
+ * Whether to use strict parsing. If true, the loader will throw an error if
22
+ * any of the parsers fail to parse their respective values. If false, the
23
+ * loader will return null or their default value for any failed parsers.
24
+ */
25
+ strict?: boolean;
26
+ };
27
+
28
+ export type LoaderFunction<Parsers extends ParserMap> = {
29
+ /**
30
+ * Load & parse search params from (almost) any input.
31
+ *
32
+ * While loaders are typically used in the context of a React Router / Remix
33
+ * loader function, it can also be used in Next.js API routes or
34
+ * getServerSideProps functions, or even with the app router `searchParams`
35
+ * page prop (sync or async), if you don't need the cache behaviours.
36
+ */
37
+ (input: LoaderInput, options?: LoaderFunctionOptions): inferParserType<Parsers>;
38
+ /**
39
+ * Load & parse search params from (almost) any input.
40
+ *
41
+ * While loaders are typically used in the context of a React Router / Remix
42
+ * loader function, it can also be used in Next.js API routes or
43
+ * getServerSideProps functions, or even with the app router `searchParams`
44
+ * page prop (sync or async), if you don't need the cache behaviours.
45
+ *
46
+ * Note: this async overload makes it easier to use against the `searchParams`
47
+ * page prop in Next.js 15 app router:
48
+ *
49
+ * ```tsx
50
+ * export default async function Page({ searchParams }) {
51
+ * const parsedSearchParamsPromise = loadSearchParams(searchParams)
52
+ * return (
53
+ * // Pre-render & stream the shell immediately
54
+ * <StaticShell>
55
+ * <Suspense>
56
+ * // Stream the Promise down
57
+ * <DynamicComponent searchParams={parsedSearchParamsPromise} />
58
+ * </Suspense>
59
+ * </StaticShell>
60
+ * )
61
+ * }
62
+ * ```
63
+ */
64
+ (input: Promise<LoaderInput>, options?: LoaderFunctionOptions): Promise<inferParserType<Parsers>>;
65
+ };
66
+
67
+ export function createLoader<Parsers extends ParserMap>(
68
+ parsers: Parsers,
69
+ { urlKeys = {} }: CreateLoaderOptions<Parsers> = {},
70
+ ): LoaderFunction<Parsers> {
71
+ type ParsedSearchParams = inferParserType<Parsers>;
72
+
73
+ function loadSearchParams(
74
+ input: LoaderInput,
75
+ options?: LoaderFunctionOptions,
76
+ ): ParsedSearchParams;
77
+
78
+ function loadSearchParams(
79
+ input: Promise<LoaderInput>,
80
+ options?: LoaderFunctionOptions,
81
+ ): Promise<ParsedSearchParams>;
82
+
83
+ function loadSearchParams(
84
+ input: LoaderInput | Promise<LoaderInput>,
85
+ { strict = false }: LoaderFunctionOptions = {},
86
+ ) {
87
+ if (input instanceof Promise) {
88
+ return input.then((i) => loadSearchParams(i, { strict }));
89
+ }
90
+ const searchParams = extractSearchParams(input);
91
+ const result = {} as any;
92
+ for (const [key, parser] of Object.entries(parsers)) {
93
+ const urlKey = urlKeys[key] ?? key;
94
+ const query =
95
+ parser.type === 'multi' ? searchParams.getAll(urlKey) : searchParams.get(urlKey);
96
+ if (isAbsentFromUrl(query)) {
97
+ result[key] = parser.defaultValue ?? null;
98
+ continue;
99
+ }
100
+ let parsedValue;
101
+ try {
102
+ // we have properly narrowed `query` here, but TS doesn't keep track of that
103
+ parsedValue = parser.parse(query as string & Array<string>);
104
+ } catch (error) {
105
+ if (strict) {
106
+ throw new Error(
107
+ `[nuqs] Error while parsing query \`${query}\` for key \`${key}\`: ${error}`,
108
+ );
109
+ }
110
+ parsedValue = null;
111
+ }
112
+ if (strict && query && parsedValue === null) {
113
+ throw new Error(`[nuqs] Failed to parse query \`${query}\` for key \`${key}\` (got null)`);
114
+ }
115
+ result[key] = parsedValue ?? parser.defaultValue ?? null;
116
+ }
117
+ return result;
118
+ }
119
+ return loadSearchParams;
120
+ }
121
+
122
+ function extractSearchParams(input: LoaderInput): URLSearchParams {
123
+ try {
124
+ if (input instanceof Request) {
125
+ return input.url ? new URL(input.url).searchParams : new URLSearchParams();
126
+ }
127
+ if (input instanceof URL) {
128
+ return input.searchParams;
129
+ }
130
+ if (input instanceof URLSearchParams) {
131
+ return input;
132
+ }
133
+ if (typeof input === 'object') {
134
+ const searchParams = new URLSearchParams();
135
+ for (const [key, value] of Object.entries(input)) {
136
+ if (Array.isArray(value)) {
137
+ for (const v of value) {
138
+ searchParams.append(key, v);
139
+ }
140
+ } else if (value !== undefined) {
141
+ searchParams.set(key, value);
142
+ }
143
+ }
144
+ return searchParams;
145
+ }
146
+ if (typeof input === 'string') {
147
+ if (URL.canParse(input)) {
148
+ return new URL(input).searchParams;
149
+ }
150
+ return new URLSearchParams(input);
151
+ }
152
+ } catch {}
153
+ return new URLSearchParams();
154
+ }