zustand-querystring 0.0.20-beta.0 → 0.2.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,19 @@
1
+ import {
2
+ stringify
3
+ } from "./chunk-OEB5LU3Z.mjs";
4
+
5
+ // src/utils.ts
6
+ var createURL = ({
7
+ baseUrl,
8
+ key,
9
+ state
10
+ }) => {
11
+ const url = new URL(baseUrl);
12
+ const stringified = stringify(state);
13
+ url.searchParams.set(key, stringified);
14
+ return url.href;
15
+ };
16
+
17
+ export {
18
+ createURL
19
+ };
@@ -0,0 +1,144 @@
1
+ import {
2
+ parse,
3
+ stringify
4
+ } from "./chunk-OEB5LU3Z.mjs";
5
+
6
+ // src/middleware.ts
7
+ import { isEqual, mergeWith } from "lodash-es";
8
+ var compact = (newState, initialState) => {
9
+ const output = {};
10
+ Object.keys(newState).forEach((key) => {
11
+ if (newState[key] !== null && newState[key] !== void 0 && typeof newState[key] !== "function" && !isEqual(newState[key], initialState[key])) {
12
+ if (typeof newState[key] === "object" && !Array.isArray(newState[key])) {
13
+ const value = compact(newState[key], initialState[key]);
14
+ if (value && Object.keys(value).length > 0) {
15
+ output[key] = value;
16
+ }
17
+ } else {
18
+ output[key] = newState[key];
19
+ }
20
+ }
21
+ });
22
+ return output;
23
+ };
24
+ var translateSelectionToState = (selection, state) => {
25
+ if (typeof state !== "object" || !state) {
26
+ return {};
27
+ }
28
+ return Object.keys(selection).reduce((acc, key) => {
29
+ if (!(key in state)) {
30
+ return acc;
31
+ }
32
+ const value = selection[key];
33
+ if (typeof value === "boolean") {
34
+ if (value) {
35
+ acc[key] = state[key];
36
+ }
37
+ } else {
38
+ acc[key] = translateSelectionToState(value, state[key]);
39
+ }
40
+ return acc;
41
+ }, {});
42
+ };
43
+ var queryStringImpl = (fn, options) => (set, get, api) => {
44
+ const defaultedOptions = {
45
+ key: "state",
46
+ format: {
47
+ stringify,
48
+ parse
49
+ },
50
+ ...options
51
+ };
52
+ const getStateFromUrl = (url) => {
53
+ const match = url.searchParams.get(defaultedOptions.key);
54
+ if (match) {
55
+ return defaultedOptions.format.parse(match);
56
+ }
57
+ return null;
58
+ };
59
+ const getSelectedState = (state, pathname) => {
60
+ if (defaultedOptions.select) {
61
+ const selection = defaultedOptions.select(pathname);
62
+ const selectedState = translateSelectionToState(selection, state);
63
+ return selectedState;
64
+ }
65
+ return state != null ? state : {};
66
+ };
67
+ const initialize = (url, initialState) => {
68
+ try {
69
+ const stateFromURl = getStateFromUrl(url);
70
+ if (!stateFromURl) {
71
+ return initialState;
72
+ }
73
+ const merged = mergeWith(
74
+ {},
75
+ initialState,
76
+ getSelectedState(stateFromURl, url.pathname)
77
+ );
78
+ return merged;
79
+ } catch (error) {
80
+ console.error(error);
81
+ return initialState;
82
+ }
83
+ };
84
+ if (typeof window !== "undefined") {
85
+ const initialState = fn(
86
+ (...args) => {
87
+ set(...args);
88
+ setQuery();
89
+ },
90
+ get,
91
+ api
92
+ );
93
+ const setQuery = () => {
94
+ const url = new URL(window.location.href);
95
+ const selectedState = getSelectedState(get(), url.pathname);
96
+ const newCompacted = compact(selectedState, initialState);
97
+ const previous = url.search;
98
+ if (Object.keys(newCompacted).length) {
99
+ url.searchParams.set(
100
+ defaultedOptions.key,
101
+ defaultedOptions.format.stringify(newCompacted)
102
+ );
103
+ } else {
104
+ url.searchParams.delete(defaultedOptions.key);
105
+ }
106
+ if (url.search !== previous) {
107
+ history.replaceState(history.state, "", url);
108
+ }
109
+ };
110
+ if (!api.__ZUSTAND_QUERYSTRING_INIT__) {
111
+ api.__ZUSTAND_QUERYSTRING_INIT__ = true;
112
+ let previousPathname = "";
113
+ const cb = () => {
114
+ if (location.pathname !== previousPathname) {
115
+ previousPathname = location.pathname;
116
+ setTimeout(setQuery, 100);
117
+ }
118
+ requestAnimationFrame(cb);
119
+ };
120
+ requestAnimationFrame(cb);
121
+ }
122
+ const originalSetState = api.setState;
123
+ api.setState = (...args) => {
124
+ originalSetState(...args);
125
+ setQuery();
126
+ };
127
+ const initialized = initialize(new URL(window.location.href), initialState);
128
+ api.getInitialState = () => initialized;
129
+ return initialized;
130
+ } else if (defaultedOptions.url) {
131
+ const initialized = initialize(
132
+ new URL(defaultedOptions.url, "http://localhost"),
133
+ fn(set, get, api)
134
+ );
135
+ api.getInitialState = () => initialized;
136
+ return initialized;
137
+ }
138
+ return fn(set, get, api);
139
+ };
140
+ var querystring = queryStringImpl;
141
+
142
+ export {
143
+ querystring
144
+ };
@@ -0,0 +1,12 @@
1
+ // src/parser.ts
2
+ function stringify(input) {
3
+ return encodeURIComponent(JSON.stringify(input));
4
+ }
5
+ function parse(str) {
6
+ return JSON.parse(decodeURIComponent(str));
7
+ }
8
+
9
+ export {
10
+ stringify,
11
+ parse
12
+ };
@@ -0,0 +1,4 @@
1
+ export { QueryStringOptions, querystring } from './middleware.mjs';
2
+ export { parse, stringify } from './parser.mjs';
3
+ export { createURL } from './utils.mjs';
4
+ import 'zustand/vanilla';
package/dist/index.js CHANGED
@@ -17,144 +17,27 @@ var __copyProps = (to, from, except, desc) => {
17
17
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
18
 
19
19
  // src/index.ts
20
- var src_exports = {};
21
- __export(src_exports, {
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
22
  createURL: () => createURL,
23
23
  parse: () => parse,
24
24
  querystring: () => querystring,
25
25
  stringify: () => stringify
26
26
  });
27
- module.exports = __toCommonJS(src_exports);
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/middleware.ts
30
+ var import_lodash_es = require("lodash-es");
28
31
 
29
32
  // src/parser.ts
30
- var keyStringifyRegexp = /([=:@$/])/g;
31
- var valueStringifyRegexp = /([&;/])/g;
32
- var keyParseRegexp = /[=:@$]/;
33
- var valueParseRegexp = /[&;]/;
34
- function encodeString(str, regexp) {
35
- return encodeURI(str.replace(regexp, "/$1"));
36
- }
37
- function trim(res) {
38
- return typeof res === "string" ? res.replace(/;+$/g, "").replace(/^\$/, "") : res;
39
- }
40
- function stringify(input, recursive) {
41
- if (!recursive) {
42
- return trim(stringify(input, true));
43
- }
44
- if (typeof input === "function") {
45
- return;
46
- }
47
- if (typeof input === "number" || input === true || input === false || input === null) {
48
- return ":" + input;
49
- }
50
- const res = [];
51
- if (Array.isArray(input)) {
52
- for (const elem of input) {
53
- typeof elem === "undefined" ? res.push(":null") : res.push(stringify(elem, true));
54
- }
55
- return "@" + res.join("&") + ";";
56
- }
57
- if (input instanceof Date) {
58
- return "=!Date:" + encodeString(input.toISOString(), valueStringifyRegexp);
59
- }
60
- if (typeof input === "object") {
61
- for (const [key, value] of Object.entries(input)) {
62
- const stringifiedValue = stringify(value, true);
63
- if (stringifiedValue) {
64
- res.push(encodeString(key, keyStringifyRegexp) + stringifiedValue);
65
- }
66
- }
67
- return "$" + res.join("&") + ";";
68
- }
69
- if (typeof input === "undefined") {
70
- return;
71
- }
72
- return "=" + encodeString(input.toString(), valueStringifyRegexp);
33
+ function stringify(input) {
34
+ return encodeURIComponent(JSON.stringify(input));
73
35
  }
74
36
  function parse(str) {
75
- if (!str.startsWith("$")) {
76
- str = "$" + str;
77
- }
78
- let pos = 0;
79
- str = decodeURI(str);
80
- function readToken(regexp) {
81
- let token = "";
82
- for (; pos !== str.length; ++pos) {
83
- if (str.charAt(pos) === "/") {
84
- pos += 1;
85
- if (pos === str.length) {
86
- token += ";";
87
- break;
88
- }
89
- } else if (str.charAt(pos).match(regexp)) {
90
- break;
91
- }
92
- token += str.charAt(pos);
93
- }
94
- return token;
95
- }
96
- function parseToken() {
97
- const type = str.charAt(pos++);
98
- if (type === "=") {
99
- const value = readToken(valueParseRegexp);
100
- if (value.startsWith("!Date:")) {
101
- return new Date(value.slice("!Date:".length));
102
- }
103
- return value;
104
- }
105
- if (type === ":") {
106
- const value = readToken(valueParseRegexp);
107
- if (value === "true") {
108
- return true;
109
- }
110
- if (value === "false") {
111
- return false;
112
- }
113
- const parsedValue = parseFloat(value);
114
- return isNaN(parsedValue) ? null : parsedValue;
115
- }
116
- if (type === "@") {
117
- const res = [];
118
- loop: {
119
- if (pos >= str.length || str.charAt(pos) === ";") {
120
- break loop;
121
- }
122
- while (1) {
123
- res.push(parseToken());
124
- if (pos >= str.length || str.charAt(pos) === ";") {
125
- break loop;
126
- }
127
- pos += 1;
128
- }
129
- }
130
- pos += 1;
131
- return res;
132
- }
133
- if (type === "$") {
134
- const res = {};
135
- loop: {
136
- if (pos >= str.length || str.charAt(pos) === ";") {
137
- break loop;
138
- }
139
- while (1) {
140
- var name = readToken(keyParseRegexp);
141
- res[name] = parseToken();
142
- if (pos >= str.length || str.charAt(pos) === ";") {
143
- break loop;
144
- }
145
- pos += 1;
146
- }
147
- }
148
- pos += 1;
149
- return res;
150
- }
151
- throw new Error("Unexpected char " + type);
152
- }
153
- return parseToken();
37
+ return JSON.parse(decodeURIComponent(str));
154
38
  }
155
39
 
156
40
  // src/middleware.ts
157
- var import_lodash_es = require("lodash-es");
158
41
  var compact = (newState, initialState) => {
159
42
  const output = {};
160
43
  Object.keys(newState).forEach((key) => {
@@ -190,32 +73,22 @@ var translateSelectionToState = (selection, state) => {
190
73
  return acc;
191
74
  }, {});
192
75
  };
193
- var escapeStringRegexp = (string) => {
194
- if (typeof string !== "string") {
195
- throw new TypeError("Expected a string");
196
- }
197
- return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
198
- };
199
76
  var queryStringImpl = (fn, options) => (set, get, api) => {
200
77
  const defaultedOptions = {
201
- key: "$",
78
+ key: "state",
79
+ format: {
80
+ stringify,
81
+ parse
82
+ },
202
83
  ...options
203
84
  };
204
- if (encodeURIComponent(defaultedOptions.key) === defaultedOptions.key) {
205
- defaultedOptions.key = `:${defaultedOptions.key}`;
206
- }
207
- const escapedKey = escapeStringRegexp(defaultedOptions.key);
208
- const stateMatcher = new RegExp(`${escapedKey}=(.*);;|${escapedKey}=(.*)$`);
209
- const splitMatcher = new RegExp(`${escapedKey}=.*;;|${escapedKey}=.*$`);
210
- const parseQueryString2 = (querystring2) => {
211
- var _a;
212
- const match = querystring2.match(stateMatcher);
85
+ const getStateFromUrl = (url) => {
86
+ const match = url.searchParams.get(defaultedOptions.key);
213
87
  if (match) {
214
- return parse((_a = match[1]) != null ? _a : match[2]);
88
+ return defaultedOptions.format.parse(match);
215
89
  }
216
90
  return null;
217
91
  };
218
- let url = defaultedOptions.url;
219
92
  const getSelectedState = (state, pathname) => {
220
93
  if (defaultedOptions.select) {
221
94
  const selection = defaultedOptions.select(pathname);
@@ -224,22 +97,17 @@ var queryStringImpl = (fn, options) => (set, get, api) => {
224
97
  }
225
98
  return state != null ? state : {};
226
99
  };
227
- const initialize = (url2, initialState) => {
100
+ const initialize = (url, initialState) => {
228
101
  try {
229
- const queryString = url2.search.substring(1);
230
- const pathname = url2.pathname;
231
- if (!queryString) {
232
- return initialState;
233
- }
234
- const parsed = parseQueryString2(queryString);
235
- if (!parsed) {
102
+ const stateFromURl = getStateFromUrl(url);
103
+ if (!stateFromURl) {
236
104
  return initialState;
237
105
  }
238
106
  const merged = (0, import_lodash_es.mergeWith)(
239
- (0, import_lodash_es.cloneDeep)(initialState),
240
- getSelectedState(parsed, pathname)
107
+ {},
108
+ initialState,
109
+ getSelectedState(stateFromURl, url.pathname)
241
110
  );
242
- set(merged, true);
243
111
  return merged;
244
112
  } catch (error) {
245
113
  console.error(error);
@@ -247,70 +115,29 @@ var queryStringImpl = (fn, options) => (set, get, api) => {
247
115
  }
248
116
  };
249
117
  if (typeof window !== "undefined") {
250
- const decodeHref = () => {
251
- let href = location.href;
252
- let decoded = decodeURIComponent(href);
253
- if (decoded.indexOf(`?${defaultedOptions.key}=`) !== href.indexOf(`?${defaultedOptions.key}=`)) {
254
- href = decoded;
255
- decoded = decodeURIComponent(href);
256
- }
257
- return href;
258
- };
259
- const initialState = (0, import_lodash_es.cloneDeep)(
260
- fn(
261
- (...args) => {
262
- set(...args);
263
- setQuery();
264
- },
265
- get,
266
- api
267
- )
118
+ const initialState = fn(
119
+ (...args) => {
120
+ set(...args);
121
+ setQuery();
122
+ },
123
+ get,
124
+ api
268
125
  );
269
126
  const setQuery = () => {
270
- const url2 = new URL(decodeHref());
271
- const selectedState = getSelectedState(get(), url2.pathname);
272
- const currentQueryString = url2.search;
273
- const currentParsed = parseQueryString2(currentQueryString);
274
- const newMerged = {
275
- ...currentParsed,
276
- ...selectedState
277
- };
278
- const splitIgnored = currentQueryString.split(splitMatcher);
279
- let ignored = "";
280
- for (let str of splitIgnored) {
281
- if (!str || str === "?" || str === "&") {
282
- continue;
283
- }
284
- if (str.startsWith("&") || str.startsWith("?")) {
285
- str = str.substring(1);
286
- }
287
- if (str.endsWith("&")) {
288
- str = str.substring(0, str.length - 1);
289
- }
290
- ignored += (ignored ? "&" : "?") + str;
291
- }
292
- const newCompacted = compact(newMerged, initialState);
293
- let newQueryString = "";
127
+ const url = new URL(window.location.href);
128
+ const selectedState = getSelectedState(get(), url.pathname);
129
+ const newCompacted = compact(selectedState, initialState);
130
+ const previous = url.search;
294
131
  if (Object.keys(newCompacted).length) {
295
- const stringified = stringify(newCompacted);
296
- const newQueryState = `${defaultedOptions.key}=${stringified};;`;
297
- if (currentParsed) {
298
- newQueryString = currentQueryString.replace(
299
- splitMatcher,
300
- newQueryState
301
- );
302
- } else if (ignored) {
303
- newQueryString = ignored + "&" + newQueryState;
304
- } else {
305
- newQueryString = "?" + newQueryState;
306
- }
132
+ url.searchParams.set(
133
+ defaultedOptions.key,
134
+ defaultedOptions.format.stringify(newCompacted)
135
+ );
307
136
  } else {
308
- newQueryString = ignored;
137
+ url.searchParams.delete(defaultedOptions.key);
309
138
  }
310
- const currentUrl = location.pathname + location.search;
311
- const newUrl = location.pathname + newQueryString;
312
- if (newUrl !== currentUrl) {
313
- history.replaceState(history.state, "", newUrl);
139
+ if (url.search !== previous) {
140
+ history.replaceState(history.state, "", url);
314
141
  }
315
142
  };
316
143
  if (!api.__ZUSTAND_QUERYSTRING_INIT__) {
@@ -330,74 +157,31 @@ var queryStringImpl = (fn, options) => (set, get, api) => {
330
157
  originalSetState(...args);
331
158
  setQuery();
332
159
  };
333
- return initialize(new URL(decodeHref()), initialState);
334
- } else if (url) {
335
- url = decodeURIComponent(url);
336
- const idx = url.indexOf(`?${defaultedOptions.key}=`);
337
- const decoded = decodeURIComponent(url);
338
- if (decoded.indexOf(`?${defaultedOptions.key}=`) !== idx) {
339
- url = decoded;
340
- }
341
- return initialize(new URL(url, "http://localhost"), fn(set, get, api));
160
+ const initialized = initialize(new URL(window.location.href), initialState);
161
+ api.getInitialState = () => initialized;
162
+ return initialized;
163
+ } else if (defaultedOptions.url) {
164
+ const initialized = initialize(
165
+ new URL(defaultedOptions.url, "http://localhost"),
166
+ fn(set, get, api)
167
+ );
168
+ api.getInitialState = () => initialized;
169
+ return initialized;
342
170
  }
343
171
  return fn(set, get, api);
344
172
  };
345
173
  var querystring = queryStringImpl;
346
174
 
347
175
  // src/utils.ts
348
- var escapeStringRegexp2 = (string) => {
349
- if (typeof string !== "string") {
350
- throw new TypeError("Expected a string");
351
- }
352
- return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
353
- };
354
- var parseQueryString = (key, querystring2) => {
355
- var _a;
356
- const stateMatcher = new RegExp(`${key}=(.*);;|${key}=(.*)$`);
357
- const match = querystring2.match(stateMatcher);
358
- if (match) {
359
- return parse((_a = match[1]) != null ? _a : match[2]);
360
- }
361
- return null;
362
- };
363
176
  var createURL = ({
364
177
  baseUrl,
365
178
  key,
366
179
  state
367
180
  }) => {
368
- const escapedKey = escapeStringRegexp2(key);
181
+ const url = new URL(baseUrl);
369
182
  const stringified = stringify(state);
370
- const newQueryState = `${key}=${stringified};;`;
371
- const match = baseUrl.indexOf("?");
372
- const currentQueryString = match >= 0 ? baseUrl.substring(match) : "";
373
- const currentParsed = parseQueryString(escapedKey, currentQueryString);
374
- const splitMatcher = new RegExp(`${escapedKey}=.*;;|${escapedKey}=.*$`);
375
- const splitIgnored = currentQueryString.split(splitMatcher);
376
- let ignored = "";
377
- for (let str of splitIgnored) {
378
- if (!str || str === "?" || str === "&") {
379
- continue;
380
- }
381
- if (str.startsWith("&") || str.startsWith("?")) {
382
- str = str.substring(1);
383
- }
384
- if (str.endsWith("&")) {
385
- str = str.substring(0, str.length - 1);
386
- }
387
- ignored += (ignored ? "&" : "?") + str;
388
- }
389
- let newQueryString = "";
390
- if (currentParsed) {
391
- newQueryString = currentQueryString.replace(splitMatcher, newQueryState);
392
- } else if (ignored) {
393
- newQueryString = ignored + "&" + newQueryState;
394
- } else {
395
- newQueryString = "?" + newQueryState;
396
- }
397
- if (currentQueryString) {
398
- return baseUrl.replace(currentQueryString, newQueryString);
399
- }
400
- return baseUrl + newQueryString;
183
+ url.searchParams.set(key, stringified);
184
+ return url.href;
401
185
  };
402
186
  // Annotate the CommonJS export names for ESM import in node:
403
187
  0 && (module.exports = {
package/dist/index.mjs CHANGED
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  querystring
3
- } from "./chunk-C7RA6OH5.mjs";
3
+ } from "./chunk-L542GMLN.mjs";
4
4
  import {
5
5
  createURL
6
- } from "./chunk-PYA77ZUK.mjs";
6
+ } from "./chunk-HC4H2XL3.mjs";
7
7
  import {
8
8
  parse,
9
9
  stringify
10
- } from "./chunk-ZM24AXRE.mjs";
10
+ } from "./chunk-OEB5LU3Z.mjs";
11
11
  export {
12
12
  createURL,
13
13
  parse,
@@ -0,0 +1,21 @@
1
+ import { StoreMutatorIdentifier, StateCreator } from 'zustand/vanilla';
2
+
3
+ type DeepSelect<T> = T extends object ? {
4
+ [P in keyof T]?: DeepSelect<T[P]> | boolean;
5
+ } : boolean;
6
+ type DeepPartial<T> = T extends object ? {
7
+ [P in keyof T]?: DeepPartial<T[P]>;
8
+ } : T;
9
+ interface QueryStringOptions<T> {
10
+ url?: string;
11
+ select?: (pathname: string) => DeepSelect<T>;
12
+ key?: string;
13
+ format?: {
14
+ stringify: (value: DeepPartial<T>) => string;
15
+ parse: (value: string) => DeepPartial<T>;
16
+ };
17
+ }
18
+ type QueryString = <T, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, Mps, Mcs>, options?: QueryStringOptions<T>) => StateCreator<T, Mps, Mcs>;
19
+ declare const querystring: QueryString;
20
+
21
+ export { type QueryStringOptions, querystring };
@@ -3,12 +3,19 @@ import { StoreMutatorIdentifier, StateCreator } from 'zustand/vanilla';
3
3
  type DeepSelect<T> = T extends object ? {
4
4
  [P in keyof T]?: DeepSelect<T[P]> | boolean;
5
5
  } : boolean;
6
+ type DeepPartial<T> = T extends object ? {
7
+ [P in keyof T]?: DeepPartial<T[P]>;
8
+ } : T;
6
9
  interface QueryStringOptions<T> {
7
10
  url?: string;
8
11
  select?: (pathname: string) => DeepSelect<T>;
9
12
  key?: string;
13
+ format?: {
14
+ stringify: (value: DeepPartial<T>) => string;
15
+ parse: (value: string) => DeepPartial<T>;
16
+ };
10
17
  }
11
18
  type QueryString = <T, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs extends [StoreMutatorIdentifier, unknown][] = []>(initializer: StateCreator<T, Mps, Mcs>, options?: QueryStringOptions<T>) => StateCreator<T, Mps, Mcs>;
12
19
  declare const querystring: QueryString;
13
20
 
14
- export { QueryStringOptions, querystring };
21
+ export { type QueryStringOptions, querystring };