@oxog/querystring 1.0.0 → 1.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.
Files changed (102) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +54 -72
  3. package/dist/index.d.mts +343 -0
  4. package/dist/index.d.ts +333 -39
  5. package/dist/index.js +2333 -88
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +2284 -49
  8. package/dist/index.mjs.map +1 -0
  9. package/package.json +36 -18
  10. package/dist/builder.d.ts +0 -42
  11. package/dist/builder.d.ts.map +0 -1
  12. package/dist/builder.js +0 -216
  13. package/dist/builder.js.map +0 -1
  14. package/dist/esm/builder.d.ts +0 -42
  15. package/dist/esm/builder.d.ts.map +0 -1
  16. package/dist/esm/builder.js.map +0 -1
  17. package/dist/esm/builder.mjs +0 -212
  18. package/dist/esm/index.d.ts +0 -49
  19. package/dist/esm/index.d.ts.map +0 -1
  20. package/dist/esm/index.js.map +0 -1
  21. package/dist/esm/index.mjs +0 -49
  22. package/dist/esm/parser.d.ts +0 -7
  23. package/dist/esm/parser.d.ts.map +0 -1
  24. package/dist/esm/parser.js.map +0 -1
  25. package/dist/esm/parser.mjs +0 -170
  26. package/dist/esm/plugins.d.ts +0 -25
  27. package/dist/esm/plugins.d.ts.map +0 -1
  28. package/dist/esm/plugins.js.map +0 -1
  29. package/dist/esm/plugins.mjs +0 -223
  30. package/dist/esm/schema.d.ts +0 -23
  31. package/dist/esm/schema.d.ts.map +0 -1
  32. package/dist/esm/schema.js.map +0 -1
  33. package/dist/esm/schema.mjs +0 -674
  34. package/dist/esm/security.d.ts +0 -14
  35. package/dist/esm/security.d.ts.map +0 -1
  36. package/dist/esm/security.js.map +0 -1
  37. package/dist/esm/security.mjs +0 -224
  38. package/dist/esm/stringifier.d.ts +0 -4
  39. package/dist/esm/stringifier.d.ts.map +0 -1
  40. package/dist/esm/stringifier.js.map +0 -1
  41. package/dist/esm/stringifier.mjs +0 -193
  42. package/dist/esm/types/index.d.ts +0 -184
  43. package/dist/esm/types/index.d.ts.map +0 -1
  44. package/dist/esm/types/index.js.map +0 -1
  45. package/dist/esm/types/index.mjs +0 -2
  46. package/dist/esm/types/schema.d.ts +0 -37
  47. package/dist/esm/types/schema.d.ts.map +0 -1
  48. package/dist/esm/types/schema.js.map +0 -1
  49. package/dist/esm/types/schema.mjs +0 -2
  50. package/dist/esm/utils/array.d.ts +0 -11
  51. package/dist/esm/utils/array.d.ts.map +0 -1
  52. package/dist/esm/utils/array.js.map +0 -1
  53. package/dist/esm/utils/array.mjs +0 -116
  54. package/dist/esm/utils/encoding.d.ts +0 -13
  55. package/dist/esm/utils/encoding.d.ts.map +0 -1
  56. package/dist/esm/utils/encoding.js.map +0 -1
  57. package/dist/esm/utils/encoding.mjs +0 -126
  58. package/dist/esm/utils/object.d.ts +0 -12
  59. package/dist/esm/utils/object.d.ts.map +0 -1
  60. package/dist/esm/utils/object.js.map +0 -1
  61. package/dist/esm/utils/object.mjs +0 -140
  62. package/dist/index.d.ts.map +0 -1
  63. package/dist/parser.d.ts +0 -7
  64. package/dist/parser.d.ts.map +0 -1
  65. package/dist/parser.js +0 -174
  66. package/dist/parser.js.map +0 -1
  67. package/dist/plugins.d.ts +0 -25
  68. package/dist/plugins.d.ts.map +0 -1
  69. package/dist/plugins.js +0 -229
  70. package/dist/plugins.js.map +0 -1
  71. package/dist/schema.d.ts +0 -23
  72. package/dist/schema.d.ts.map +0 -1
  73. package/dist/schema.js +0 -680
  74. package/dist/schema.js.map +0 -1
  75. package/dist/security.d.ts +0 -14
  76. package/dist/security.d.ts.map +0 -1
  77. package/dist/security.js +0 -233
  78. package/dist/security.js.map +0 -1
  79. package/dist/stringifier.d.ts +0 -4
  80. package/dist/stringifier.d.ts.map +0 -1
  81. package/dist/stringifier.js +0 -197
  82. package/dist/stringifier.js.map +0 -1
  83. package/dist/types/index.d.ts +0 -184
  84. package/dist/types/index.d.ts.map +0 -1
  85. package/dist/types/index.js +0 -3
  86. package/dist/types/index.js.map +0 -1
  87. package/dist/types/schema.d.ts +0 -37
  88. package/dist/types/schema.d.ts.map +0 -1
  89. package/dist/types/schema.js +0 -3
  90. package/dist/types/schema.js.map +0 -1
  91. package/dist/utils/array.d.ts +0 -11
  92. package/dist/utils/array.d.ts.map +0 -1
  93. package/dist/utils/array.js +0 -127
  94. package/dist/utils/array.js.map +0 -1
  95. package/dist/utils/encoding.d.ts +0 -13
  96. package/dist/utils/encoding.d.ts.map +0 -1
  97. package/dist/utils/encoding.js +0 -137
  98. package/dist/utils/encoding.js.map +0 -1
  99. package/dist/utils/object.d.ts +0 -12
  100. package/dist/utils/object.d.ts.map +0 -1
  101. package/dist/utils/object.js +0 -150
  102. package/dist/utils/object.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,79 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.1.0] - 2026-11-30
9
+
10
+ ### Fixed
11
+ - **ESM import was broken**: `import ... from '@oxog/querystring'` failed with `ERR_MODULE_NOT_FOUND`
12
+ (`dist/index.mjs` imported extensionless files that did not exist). The package is now built with tsup
13
+ into self-contained `index.mjs` (ESM) and `index.js` (CommonJS) bundles.
14
+ - **Prototype pollution in `parse()`**: `a=1&a[__proto__][x]=1` wrote `x` onto `String.prototype`
15
+ (`Number.prototype`/`Boolean.prototype` with `parseNumbers`/`parseBooleans`), and
16
+ `a=1&a[__proto__][__proto__][x]=1` replaced the prototype of `String.prototype`.
17
+ `__proto__[x]=1` and `a[__proto__][b]=1` replaced the prototype of the returned objects.
18
+ `__proto__` segments are now always dropped.
19
+ - `parse('a=1&a[b]=2')` threw `TypeError: Cannot create property 'b' on string '1'`.
20
+ - **Parameter injection in `stringify()`**: array items were not percent-encoded, so
21
+ `stringify({ role: ['user&admin=true'] })` produced `role=user&admin=true`. Items are now encoded in
22
+ every array format.
23
+ - `a[999999999]=1` created an array with length 1,000,000,000 (and `JSON.stringify` of the result hung).
24
+ Indices of `arrayLimit` (new option, default 20) and above now become object keys, as in `qs`.
25
+ - Quadratic-time regular expressions (ReDoS): `sanitizeInput`, `detectXSS`, `validateSecurity` and
26
+ `createSecureParser({ sanitize: true })` took seconds on ~100-200 KB inputs such as `'on'.repeat(n)` or
27
+ `'data:'.repeat(n)`, and `q.string().email()` was quadratic on long dotted input. All now run in linear time.
28
+ - `compressPlugin` un-escaped `%26` and `%3D` (and turned `+` into raw spaces), so its output parsed to
29
+ different data (`q=a%26admin%3D1` became `q=a&admin=1`). It now only un-escapes `/ : ? @` and writes
30
+ spaces as `+`.
31
+ - `lowercaseKeysPlugin` turned a `__PROTO__` key into a prototype replacement; `QueryBuilder.merge()`
32
+ / `add()` with a `__proto__` key changed the builder's query prototype; `QueryBuilder.has('toString')`
33
+ returned `true`.
34
+ - Malformed percent escapes made the whole value undecoded (`a=100%+off` gave `'100%+off'`); valid
35
+ escapes and `+` around a malformed one are now decoded (`'100% off'`). Decoding never throws.
36
+ - `charset: 'iso-8859-1'` was ignored by `parse` and `stringify`; the `utf8=` charset sentinel was only
37
+ stripped (and matched inside other keys) but never switched the charset.
38
+ - `interpretNumericEntities` deleted entities above U+FFFF (`😀` became `''`).
39
+ - `stringify` threw `Invalid UTF-8` on a trailing lone surrogate and silently corrupted a lone surrogate
40
+ followed by another character; lone surrogates are now encoded as U+FFFD, like `URLSearchParams`.
41
+ - Arrays of objects were written as JSON inside the value (`a[0]=%7B%22b%22%3A1%7D`); they are now
42
+ written as `a[0][b]=1` and parse back to the same data.
43
+ - `depth` built empty objects and silently discarded the value; segments beyond `depth` are now kept as
44
+ one literal key (`qs` semantics).
45
+ - `arrayFormat: 'indices'` ignored the indices (`a[1]=y&a[0]=x` gave `['y', 'x']`).
46
+ - `allowDots: true` stopped bracket keys from being parsed (`a[b]=1` gave `{ 'a[b]': '1' }`).
47
+ - Options that were accepted but ignored now work: `allowPrototypes`, `allowSparse`, `parseArrays: false`
48
+ for bracket indices, `comma` (parse and stringify), `indices` (stringify), `commaRoundTrip`, and the
49
+ return value of a `filter` function.
50
+ - Comma/separator formats split values after decoding, so an encoded `%2C` inside a value was split.
51
+ Elements are no longer trimmed and type coercion (`parseNumbers`, ...) now applies to each element.
52
+ - `q.number()` accepted `''`, `' '`, `null` and `[]` as `0`.
53
+ - `q.object().strict()` accepted keys such as `toString`.
54
+ - Named export `createSecureParser(options)` threw `baseParser is not a function`; it now uses the
55
+ built-in parser when no parser is passed (the `(parser, options)` form still works).
56
+ - `stringifyUrl` put the query after a `#fragment` and doubled `?` with `addQueryPrefix`;
57
+ `parseUrl` included the fragment in the last value.
58
+
59
+ ### Added
60
+ - `arrayLimit` parse option.
61
+ - `exports` entries with separate type declarations for `import` (`index.d.mts`) and `require`
62
+ (`index.d.ts`), and `./package.json`.
63
+ - Property-based round-trip tests and comparison tests against `qs` and `URLSearchParams`; packed-archive
64
+ smoke tests (ESM, CommonJS, TypeScript NodeNext) including the README examples.
65
+ - GitHub Actions CI (Node 18-24) and a manual trusted-publishing release workflow.
66
+
67
+ ### Changed
68
+ - Behaviour changes you may notice:
69
+ - Keys named like `Object.prototype` members (`toString`, `hasOwnProperty`, `constructor`, ...) are
70
+ dropped by `parse()` unless `allowPrototypes` or `plainObjects` is set (as in `qs`).
71
+ - A trailing `[]` always yields an array: `a[]=x` parses to `{ a: ['x'] }`.
72
+ - Sparse arrays are compacted (`a[2]=x` gives `['x']`) unless `allowSparse` is set.
73
+ - `a=1&a[b]=2` gives `{ a: { b: '2' } }` (with `duplicates: 'first'` the scalar is kept).
74
+ - `createSecureParser` without `sanitize` rejects keys with `__proto__`/`constructor`/`prototype` segments.
75
+ - `RFC1738` output now also encodes `!'()*`.
76
+ - README: removed the CLI section (no CLI was ever shipped), the unverified "2x faster" table, the
77
+ "100% coverage" claim and examples that did not compile (`parse<T>()`, `QueryBuilder<T>`).
78
+ - Removed the local publish scripts (`publish:npm`, `publish:bump`, `publish:check`); releases run in
79
+ GitHub Actions. `npm test` runs once; coverage is `npm run test:coverage`.
80
+
8
81
  ## [1.0.0] - 2025-07-19
9
82
 
10
83
  ### Added
package/README.md CHANGED
@@ -5,21 +5,21 @@
5
5
  [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
6
6
  [![Zero Dependencies](https://img.shields.io/badge/Dependencies-Zero-green.svg)]()
7
7
 
8
- High-performance, type-safe query string parser and stringifier with zero dependencies. Built from the ground up to surpass existing solutions in performance, security, and developer experience.
8
+ Fast, type-safe query string parser and stringifier with zero runtime dependencies, with `qs`-compatible nesting rules and safe defaults for untrusted input.
9
9
 
10
10
  ## Features
11
11
 
12
- - 🚀 **Blazing Fast** - 2x faster than popular alternatives
13
- - 🔒 **Security First** - Built-in XSS and prototype pollution protection
12
+ - 🚀 **Fast** - see [Performance](#performance)
13
+ - 🔒 **Safe defaults** - prototype pollution protection and DoS limits (`parameterLimit`, `depth`, `arrayLimit`)
14
14
  - 📦 **Zero Dependencies** - No external runtime dependencies
15
15
  - 🎯 **Full TypeScript Support** - Complete type definitions with generics
16
16
  - 🔧 **Flexible Array Formats** - Multiple array serialization options
17
17
  - 🏗️ **QueryBuilder API** - Fluent interface for building queries
18
18
  - 📐 **Schema Validation** - Runtime type validation with detailed errors
19
19
  - 🔌 **Plugin System** - Extensible architecture
20
- - 🛡️ **Security Features** - DoS protection, input sanitization
21
- - 📋 **100% Test Coverage** - Comprehensive test suite
22
- - 🎨 **Multiple Formats** - CommonJS and ESM support
20
+ - 🛡️ **Security Helpers** - secure parser, best-effort input sanitization
21
+ - 📋 **Well tested** - unit, property-based and `qs`/`URLSearchParams` comparison tests
22
+ - 🎨 **Multiple Formats** - CommonJS and ESM builds with TypeScript declarations for both
23
23
 
24
24
  ## Installation
25
25
 
@@ -66,14 +66,22 @@ querystring.parse(query: string, options?: ParseOptions): ParsedQuery
66
66
  #### ParseOptions
67
67
 
68
68
  - `delimiter` (string): Delimiter to use (default: '&')
69
- - `depth` (number): Maximum object depth (default: 5)
69
+ - `depth` (number): Maximum nesting depth (default: 5). Segments beyond it are kept as one literal key, as in `qs`: `a[b][c][d][e][f][g]=x` → `{ a: { b: { c: { d: { e: { f: { '[g]': 'x' } } } } } } }`
70
70
  - `arrayFormat` (string): How to parse arrays (default: 'repeat')
71
+ - `arrayLimit` (number): Indices below this build arrays; `a[20]=x` and larger indices become object keys, so `a[999999999]=1` cannot create a huge sparse array (default: 20)
72
+ - `parameterLimit` (number): Maximum number of `&`-separated parts; more throws `Parameter limit exceeded` (default: 1000)
71
73
  - `parseNumbers` (boolean): Parse numeric values (default: false)
72
74
  - `parseBooleans` (boolean): Parse boolean values (default: false)
73
75
  - `parseDates` (boolean): Parse ISO date strings (default: false)
74
- - `allowDots` (boolean): Enable dot notation (default: false)
75
- - `decode` (boolean): Decode values (default: true)
76
- - `charset` ('utf-8' | 'iso-8859-1'): Character encoding
76
+ - `allowDots` (boolean): Enable dot notation in addition to brackets (default: false)
77
+ - `allowPrototypes` (boolean): Keep keys named like `Object.prototype` members (`toString`, `hasOwnProperty`, `constructor`, ...). By default they are dropped, as in `qs`. `__proto__` is always dropped (default: false)
78
+ - `plainObjects` (boolean): Build objects with a `null` prototype (default: false)
79
+ - `allowSparse` (boolean): Keep holes in arrays such as `a[1]=x` (default: false, arrays are compacted)
80
+ - `strictNullHandling` (boolean): `a` (no `=`) parses to `null` instead of `''` (default: false)
81
+ - `duplicates` ('combine' | 'first' | 'last'): What to do with repeated keys (default: 'combine')
82
+ - `decode` (boolean): Decode values (default: true). `+` is a space; malformed escapes such as `%`, `%zz` or invalid UTF-8 are kept as written and never throw
83
+ - `charset` ('utf-8' | 'iso-8859-1'): Character encoding (default: 'utf-8')
84
+ - `charsetSentinel` (boolean): Detect the charset from a leading `utf8=✓` parameter and drop it (default: false)
77
85
 
78
86
  #### Examples
79
87
 
@@ -109,15 +117,17 @@ querystring.stringify(obj: object, options?: StringifyOptions): string
109
117
  - `delimiter` (string): Delimiter to use (default: '&')
110
118
  - `encode` (boolean): Encode values (default: true)
111
119
  - `encodeValuesOnly` (boolean): Only encode values, not keys
112
- - `arrayFormat` (string): How to stringify arrays
113
- - `indices` (boolean): Include array indices
120
+ - `arrayFormat` (string): How to stringify arrays (default: 'repeat'). Arrays that contain objects or arrays are always written with indices (`a[0][b]=1`) so they parse back
121
+ - `indices` (boolean): `true` selects the `indices` format when no `arrayFormat` is given
114
122
  - `sort` (boolean | function): Sort keys
115
123
  - `filter` (array | function): Filter keys
116
- - `skipNulls` (boolean): Skip null values
124
+ - `skipNulls` (boolean): Skip `null` and `undefined` values (otherwise they are written as `key=`)
125
+ - `strictNullHandling` (boolean): Write `null` as a bare `key`
117
126
  - `addQueryPrefix` (boolean): Add '?' prefix
118
127
  - `allowDots` (boolean): Use dot notation
119
128
  - `charset` ('utf-8' | 'iso-8859-1'): Character encoding
120
- - `format` ('RFC1738' | 'RFC3986'): URI encoding format
129
+ - `format` ('RFC1738' | 'RFC3986'): URI encoding format (default: 'RFC3986', spaces as `%20`; RFC1738 writes spaces as `+`). Keys and values, including array items, are always percent-encoded unless `encode: false`
130
+ - `serializeDate` (function): How to write `Date` values (default: `toISOString()`)
121
131
 
122
132
  #### Examples
123
133
 
@@ -208,7 +218,7 @@ const searchSchema = schema({
208
218
  });
209
219
 
210
220
  // Parse and validate
211
- const query = querystring.parse(req.url);
221
+ const { query } = querystring.parseUrl(req.url);
212
222
  const validated = searchSchema.parse(query);
213
223
  // Throws detailed errors if validation fails
214
224
 
@@ -261,8 +271,11 @@ querystring.stringify(obj, {
261
271
  arrayFormatSeparator: '|'
262
272
  });
263
273
 
264
- // json: items=["a","b","c"]
274
+ // json: items=%5B%22a%22%2C%22b%22%2C%22c%22%5D (items=["a","b","c"], encoded)
265
275
  querystring.stringify(obj, { arrayFormat: 'json' });
276
+
277
+ // Parse with the same arrayFormat to read the arrays back
278
+ querystring.parse('items=a,b,c', { arrayFormat: 'comma' }); // { items: ['a', 'b', 'c'] }
266
279
  ```
267
280
 
268
281
  ## Plugin System
@@ -303,7 +316,7 @@ const result = querystring.stringify(
303
316
  - `lowercaseKeysPlugin` - Convert keys to lowercase
304
317
  - `filterEmptyPlugin` - Remove empty values
305
318
  - `base64Plugin` - Base64 encode/decode
306
- - `compressPlugin` - URL compression
319
+ - `compressPlugin` - Shorter URLs: leaves `/ : ? @` unescaped and writes spaces as `+` (the output still parses back to the same data)
307
320
  - `normalizePlugin` - Type normalization
308
321
 
309
322
  ## Security Features
@@ -333,49 +346,22 @@ try {
333
346
 
334
347
  - `maxKeys` - Maximum number of keys (DoS protection)
335
348
  - `maxDepth` - Maximum object depth
336
- - `allowPrototypes` - Allow __proto__, constructor, prototype keys
337
- - `sanitize` - Enable XSS sanitization
338
-
339
- ## CLI Usage
340
-
341
- Command-line interface for quick operations:
342
-
343
- ```bash
344
- # Install globally
345
- npm install -g @oxog/querystring
346
-
347
- # Parse a query string
348
- querystring parse "name=John&age=30"
349
-
350
- # Stringify JSON
351
- querystring stringify '{"name":"John","age":30}'
352
-
353
- # Convert between formats
354
- querystring convert brackets "items=1&items=2" --format comma
355
- # Output: items=1,2
349
+ - `allowPrototypes` - Allow __proto__, constructor, prototype keys. When `false` (and `sanitize` is off) input that uses them is rejected
350
+ - `sanitize` - Strip common XSS patterns and HTML-escape values
356
351
 
357
- # Validate against schema
358
- querystring validate 'q.object().shape({name: q.string()})' "name=John"
359
-
360
- # Read from stdin
361
- echo "foo=bar" | querystring parse --from-stdin
362
- ```
352
+ `parse()` itself never writes to `Object.prototype` or changes the prototype of the objects it returns,
353
+ whatever the options. `sanitizeInput()` / `detectXSS()` are best-effort pattern filters, not a complete
354
+ XSS defence: always escape values for the context you output them in (HTML, attributes, SQL, ...).
363
355
 
364
356
  ## Performance
365
357
 
366
- Benchmarked against popular alternatives:
367
-
368
- | Operation | @oxog/querystring | qs | query-string |
369
- |-----------|-------------------|-------|--------------|
370
- | Parse (simple) | 1.00x | 0.45x | 0.62x |
371
- | Parse (complex) | 1.00x | 0.38x | 0.55x |
372
- | Stringify (simple) | 1.00x | 0.52x | 0.71x |
373
- | Stringify (complex) | 1.00x | 0.41x | 0.63x |
358
+ A quick local comparison with `qs` 6.17 on Node 24 (mixed flat/nested query, 200k iterations) measured
359
+ `parse` about 1.5x and `stringify` about 1.4x faster. Results depend on input and runtime; measure with your own data.
374
360
 
375
361
  Run benchmarks locally:
376
362
 
377
363
  ```bash
378
- npm run benchmark
364
+ npm run build && npm run benchmark # measures this package only
379
365
  ```
380
366
 
381
367
  ## Migration Guides
@@ -409,31 +395,27 @@ const parsed = querystring.parse('?foo=bar', {
409
395
 
410
396
  ## TypeScript
411
397
 
412
- Full TypeScript support with generics:
398
+ `parse()` returns `ParsedQuery` (values are strings, arrays and nested objects unless type coercion is
399
+ enabled). To get typed, validated data, run the result through a schema:
413
400
 
414
401
  ```typescript
415
- interface SearchParams {
416
- q: string;
417
- page: number;
418
- filters?: {
419
- category: string;
420
- price: { min: number; max: number };
421
- };
422
- }
402
+ import querystring, { q, schema } from '@oxog/querystring';
423
403
 
424
- // Type-safe parsing
425
- const params = querystring.parse<SearchParams>(url);
426
- params.q // string
427
- params.page // number
428
- params.filters?.category // string | undefined
429
-
430
- // Type-safe builder
431
- const builder = new QueryBuilder<SearchParams>();
432
- builder.add('q', 'search term');
433
- builder.add('page', 1);
434
- // TypeScript ensures type safety
404
+ const searchParams = schema({
405
+ q: q.string(),
406
+ page: q.number().default(1),
407
+ filters: q.object().shape({
408
+ category: q.string(),
409
+ }).optional(),
410
+ });
411
+
412
+ const params = searchParams.parse(querystring.parse('q=shoes&page=2&filters[category]=sport'));
413
+ params.q; // 'shoes'
414
+ params.page; // 2
435
415
  ```
436
416
 
417
+ Both the ESM (`import`) and CommonJS (`require`) entry points ship their own type declarations.
418
+
437
419
  ## Contributing
438
420
 
439
421
  Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.
@@ -0,0 +1,343 @@
1
+ type Primitive = string | number | boolean | null | undefined;
2
+ type QueryValue = Primitive | Primitive[] | {
3
+ [key: string]: QueryValue;
4
+ };
5
+ type ParsedQuery = Record<string, QueryValue>;
6
+ interface ParseOptions {
7
+ delimiter?: string;
8
+ /** Maximum nesting depth of bracket/dot segments; deeper segments are kept as one literal key (default 5). */
9
+ depth?: number;
10
+ arrayFormat?: ArrayFormat;
11
+ arrayFormatSeparator?: string;
12
+ /** Array indices must be below this to build an array; `a[20]=x` and above become object keys (default 20, as in qs). */
13
+ arrayLimit?: number;
14
+ decode?: boolean;
15
+ decoder?: (str: string, defaultDecoder: (str: string) => string, charset: 'utf-8' | 'iso-8859-1') => string;
16
+ charset?: 'utf-8' | 'iso-8859-1';
17
+ charsetSentinel?: boolean;
18
+ interpretNumericEntities?: boolean;
19
+ parameterLimit?: number;
20
+ parseArrays?: boolean;
21
+ allowDots?: boolean;
22
+ plainObjects?: boolean;
23
+ allowPrototypes?: boolean;
24
+ allowSparse?: boolean;
25
+ strictNullHandling?: boolean;
26
+ comma?: boolean;
27
+ commaRoundTrip?: boolean;
28
+ ignoreQueryPrefix?: boolean;
29
+ duplicates?: 'combine' | 'first' | 'last';
30
+ parseNumbers?: boolean;
31
+ parseBooleans?: boolean;
32
+ parseDates?: boolean;
33
+ typeCoercion?: boolean | TypeCoercionOptions;
34
+ }
35
+ interface StringifyOptions {
36
+ delimiter?: string;
37
+ strictNullHandling?: boolean;
38
+ skipNulls?: boolean;
39
+ encode?: boolean;
40
+ encoder?: (str: string, defaultEncoder: (str: string) => string, charset: string, type: 'key' | 'value') => string;
41
+ filter?: Array<string | number> | ((prefix: string, value: unknown) => unknown);
42
+ arrayFormat?: ArrayFormat;
43
+ arrayFormatSeparator?: string;
44
+ indices?: boolean;
45
+ sort?: ((a: string, b: string) => number) | boolean;
46
+ serializeDate?: (date: Date) => string;
47
+ format?: 'RFC1738' | 'RFC3986';
48
+ encodeValuesOnly?: boolean;
49
+ addQueryPrefix?: boolean;
50
+ allowDots?: boolean;
51
+ charset?: 'utf-8' | 'iso-8859-1';
52
+ charsetSentinel?: boolean;
53
+ commaRoundTrip?: boolean;
54
+ comma?: boolean;
55
+ }
56
+ type ArrayFormat = 'brackets' | 'indices' | 'repeat' | 'comma' | 'separator' | 'json' | 'bracket-separator';
57
+ interface TypeCoercionOptions {
58
+ numbers?: boolean;
59
+ booleans?: boolean;
60
+ dates?: boolean;
61
+ arrays?: boolean;
62
+ objects?: boolean;
63
+ }
64
+ interface SecurityOptions {
65
+ maxKeys?: number;
66
+ maxDepth?: number;
67
+ allowPrototypes?: boolean;
68
+ sanitize?: boolean;
69
+ }
70
+ interface QueryStringPlugin {
71
+ name: string;
72
+ beforeParse?: (input: string, options: ParseOptions) => string;
73
+ afterParse?: (result: ParsedQuery, options: ParseOptions) => ParsedQuery;
74
+ beforeStringify?: (obj: ParsedQuery, options: StringifyOptions) => ParsedQuery;
75
+ afterStringify?: (result: string, options: StringifyOptions) => string;
76
+ }
77
+ interface QueryBuilderOptions extends StringifyOptions {
78
+ baseUrl?: string;
79
+ }
80
+ interface ParsedUrl {
81
+ url: string;
82
+ query: ParsedQuery;
83
+ }
84
+ interface SchemaValidationResult<T> {
85
+ success: boolean;
86
+ data?: T;
87
+ errors?: Array<{
88
+ path: string;
89
+ message: string;
90
+ value?: unknown;
91
+ }>;
92
+ }
93
+ type SchemaType = StringSchema | NumberSchema | BooleanSchema | DateSchema | ArraySchema<any> | ObjectSchema<any> | EnumSchema<any> | UnionSchema<any> | OptionalSchema<any> | NullableSchema<any>;
94
+ interface BaseSchema<T = unknown> {
95
+ type: string;
96
+ parse(value: unknown): T;
97
+ safeParse(value: unknown): SchemaValidationResult<T>;
98
+ optional(): OptionalSchema<T>;
99
+ nullable(): NullableSchema<T>;
100
+ default(value: T): this;
101
+ transform<U>(fn: (value: T) => U): BaseSchema<U>;
102
+ refine(fn: (value: T) => boolean, message?: string): this;
103
+ }
104
+ interface StringSchema extends BaseSchema<string> {
105
+ type: 'string';
106
+ min(length: number): this;
107
+ max(length: number): this;
108
+ length(length: number): this;
109
+ email(): this;
110
+ url(): this;
111
+ uuid(): this;
112
+ regex(pattern: RegExp): this;
113
+ startsWith(prefix: string): this;
114
+ endsWith(suffix: string): this;
115
+ includes(substring: string): this;
116
+ trim(): this;
117
+ toLowerCase(): this;
118
+ toUpperCase(): this;
119
+ }
120
+ interface NumberSchema extends BaseSchema<number> {
121
+ type: 'number';
122
+ min(value: number): this;
123
+ max(value: number): this;
124
+ int(): this;
125
+ positive(): this;
126
+ negative(): this;
127
+ nonpositive(): this;
128
+ nonnegative(): this;
129
+ multipleOf(value: number): this;
130
+ finite(): this;
131
+ safe(): this;
132
+ }
133
+ interface BooleanSchema extends BaseSchema<boolean> {
134
+ type: 'boolean';
135
+ }
136
+ interface DateSchema extends BaseSchema<Date> {
137
+ type: 'date';
138
+ min(date: Date): this;
139
+ max(date: Date): this;
140
+ }
141
+ interface ArraySchema<T = unknown> extends BaseSchema<T[]> {
142
+ type: 'array';
143
+ min(length: number): this;
144
+ max(length: number): this;
145
+ length(length: number): this;
146
+ nonempty(): this;
147
+ }
148
+ interface ObjectSchema<T = Record<string, unknown>> extends BaseSchema<T> {
149
+ type: 'object';
150
+ shape<S extends Record<string, SchemaType>>(shape: S): ObjectSchema<{
151
+ [K in keyof S]: S[K] extends BaseSchema<infer U> ? U : never;
152
+ }>;
153
+ strict(): this;
154
+ passthrough(): this;
155
+ strip(): this;
156
+ catchall(schema: SchemaType): this;
157
+ pick<K extends keyof T>(keys: K[]): ObjectSchema<Pick<T, K>>;
158
+ omit<K extends keyof T>(keys: K[]): ObjectSchema<Omit<T, K>>;
159
+ extend<S extends Record<string, SchemaType>>(schema: S): ObjectSchema<T & {
160
+ [K in keyof S]: S[K] extends BaseSchema<infer U> ? U : never;
161
+ }>;
162
+ merge<S extends Record<string, unknown>>(schema: ObjectSchema<S>): ObjectSchema<T & S>;
163
+ partial(): ObjectSchema<Partial<T>>;
164
+ deepPartial(): ObjectSchema<DeepPartial<T>>;
165
+ required(): ObjectSchema<Required<T>>;
166
+ }
167
+ interface EnumSchema<T extends readonly [string, ...string[]]> extends BaseSchema<T[number]> {
168
+ type: 'enum';
169
+ options: T;
170
+ }
171
+ interface UnionSchema<T extends readonly SchemaType[]> extends BaseSchema<T[number] extends BaseSchema<infer U> ? U : never> {
172
+ type: 'union';
173
+ options: T;
174
+ }
175
+ interface OptionalSchema<T> extends BaseSchema<T | undefined> {
176
+ type: 'optional';
177
+ innerType: BaseSchema<T>;
178
+ }
179
+ interface NullableSchema<T> extends BaseSchema<T | null> {
180
+ type: 'nullable';
181
+ innerType: BaseSchema<T>;
182
+ }
183
+ type DeepPartial<T> = T extends object ? {
184
+ [P in keyof T]?: DeepPartial<T[P]>;
185
+ } : T;
186
+
187
+ declare function parse(input: string, options?: ParseOptions): ParsedQuery;
188
+ declare function parseUrl(url: string, options?: ParseOptions): {
189
+ url: string;
190
+ query: ParsedQuery;
191
+ };
192
+
193
+ declare function stringify(obj: unknown, options?: StringifyOptions): string;
194
+ declare function stringifyUrl(url: string, query: unknown, options?: StringifyOptions): string;
195
+
196
+ declare class QueryBuilder {
197
+ private query;
198
+ private options;
199
+ constructor(options?: QueryBuilderOptions);
200
+ static from(input: string | ParsedQuery | QueryBuilder, options?: QueryBuilderOptions): QueryBuilder;
201
+ add(key: string, value: unknown): this;
202
+ addMultiple(obj: Record<string, unknown>): this;
203
+ addArray(key: string, values: unknown[]): this;
204
+ addObject(key: string, obj: Record<string, unknown>): this;
205
+ append(key: string, value: unknown): this;
206
+ set(key: string, value: unknown): this;
207
+ get(key: string): unknown;
208
+ has(key: string): boolean;
209
+ delete(key: string): this;
210
+ clear(): this;
211
+ keys(): string[];
212
+ values(): unknown[];
213
+ entries(): Array<[string, unknown]>;
214
+ forEach(callback: (value: unknown, key: string, builder: QueryBuilder) => void): this;
215
+ map<T>(callback: (value: unknown, key: string, builder: QueryBuilder) => T): T[];
216
+ filter(predicate: (value: unknown, key: string, builder: QueryBuilder) => boolean): QueryBuilder;
217
+ merge(other: string | ParsedQuery | QueryBuilder): this;
218
+ clone(): QueryBuilder;
219
+ isEmpty(): boolean;
220
+ size(): number;
221
+ toObject(): ParsedQuery;
222
+ toString(options?: StringifyOptions): string;
223
+ toUrl(url?: string, options?: StringifyOptions): string;
224
+ build(options?: StringifyOptions): string;
225
+ buildUrl(url?: string, options?: StringifyOptions): string;
226
+ pick(...keys: string[]): QueryBuilder;
227
+ omit(...keys: string[]): QueryBuilder;
228
+ transform(transformer: (query: ParsedQuery) => ParsedQuery): this;
229
+ validate(validator: (query: ParsedQuery) => boolean | string): this;
230
+ when(condition: boolean | ((builder: QueryBuilder) => boolean), callback: (builder: QueryBuilder) => void): this;
231
+ unless(condition: boolean | ((builder: QueryBuilder) => boolean), callback: (builder: QueryBuilder) => void): this;
232
+ tap(callback: (builder: QueryBuilder) => void): this;
233
+ static parse(input: string, options?: QueryBuilderOptions): QueryBuilder;
234
+ static create(query?: ParsedQuery, options?: QueryBuilderOptions): QueryBuilder;
235
+ }
236
+
237
+ declare const q: {
238
+ string: () => StringSchema;
239
+ number: () => NumberSchema;
240
+ boolean: () => BooleanSchema;
241
+ date: () => DateSchema;
242
+ array: <T>(schema?: BaseSchema<T>) => ArraySchema<T>;
243
+ object: <T extends Record<string, unknown> = Record<string, unknown>>() => ObjectSchema<T>;
244
+ enum: <T extends readonly [string, ...string[]]>(...values: T) => EnumSchema<T>;
245
+ union: <T extends readonly SchemaType[]>(...schemas: T) => UnionSchema<T>;
246
+ literal: <T extends string | number | boolean>(value: T) => BaseSchema<T>;
247
+ any: () => BaseSchema<any>;
248
+ unknown: () => BaseSchema<unknown>;
249
+ null: () => BaseSchema<null>;
250
+ undefined: () => BaseSchema<undefined>;
251
+ void: () => BaseSchema<void>;
252
+ };
253
+ declare function schema<T extends Record<string, SchemaType>>(shape: T): ObjectSchema<{
254
+ [K in keyof T]: T[K] extends BaseSchema<infer U> ? U : never;
255
+ }>;
256
+ declare function validate<T>(schema: BaseSchema<T>, value: unknown): T;
257
+ declare function isValid<T>(schema: BaseSchema<T>, value: unknown): boolean;
258
+
259
+ declare class PluginManager {
260
+ private plugins;
261
+ register(plugin: QueryStringPlugin): this;
262
+ unregister(pluginName: string): boolean;
263
+ has(pluginName: string): boolean;
264
+ get(pluginName: string): QueryStringPlugin | undefined;
265
+ list(): string[];
266
+ clear(): void;
267
+ applyBeforeParse(input: string, options: ParseOptions): string;
268
+ applyAfterParse(result: ParsedQuery, options: ParseOptions): ParsedQuery;
269
+ applyBeforeStringify(obj: ParsedQuery, options: StringifyOptions): ParsedQuery;
270
+ applyAfterStringify(result: string, options: StringifyOptions): string;
271
+ static create(plugins?: QueryStringPlugin[]): PluginManager;
272
+ }
273
+ declare const createPlugin: (plugin: QueryStringPlugin) => QueryStringPlugin;
274
+ declare const timestampPlugin: QueryStringPlugin;
275
+ declare const sortKeysPlugin: QueryStringPlugin;
276
+ declare const lowercaseKeysPlugin: QueryStringPlugin;
277
+ declare const filterEmptyPlugin: QueryStringPlugin;
278
+ declare const base64Plugin: QueryStringPlugin;
279
+ /**
280
+ * Shortens a stringified query by un-escaping characters that are allowed verbatim inside a query
281
+ * component (`/ : ? @`) and writing spaces as `+`. Escapes that carry meaning for the parser
282
+ * (`%26` = `&`, `%3D` = `=`, `%2B` = `+`, `%25` = `%`) are kept, so the result parses back to the same data.
283
+ */
284
+ declare const compressPlugin: QueryStringPlugin;
285
+ declare const normalizePlugin: QueryStringPlugin;
286
+ declare const createCustomPlugin: (name: string, handlers: Partial<Omit<QueryStringPlugin, "name">>) => QueryStringPlugin;
287
+
288
+ declare function sanitizeInput(input: string, options?: {
289
+ aggressive?: boolean;
290
+ }): string;
291
+ declare function validateSecurity(obj: ParsedQuery, options?: SecurityOptions): {
292
+ valid: boolean;
293
+ errors: string[];
294
+ };
295
+ declare function countKeys(obj: unknown, count?: number): number;
296
+ declare function hasPrototypePollution(obj: unknown): boolean;
297
+ declare function detectXSS(obj: unknown, path?: string): string[];
298
+ declare function secureStringify(obj: unknown, options?: SecurityOptions): string;
299
+ type Parser = (input: string, options?: ParseOptions) => ParsedQuery;
300
+ /**
301
+ * Creates a parser that validates its result. Call it as `createSecureParser(options)` (uses the
302
+ * built-in `parse`, like `querystring.createSecureParser(options)`) or
303
+ * `createSecureParser(baseParser, options)` to wrap another parser.
304
+ */
305
+ declare function createSecureParser(securityOptions?: SecurityOptions): Parser;
306
+ declare function createSecureParser(baseParser: Parser, securityOptions?: SecurityOptions): Parser;
307
+
308
+ declare const querystring: {
309
+ parse: (input: string, options?: ParseOptions & {
310
+ plugins?: boolean | PluginManager;
311
+ }) => ParsedQuery;
312
+ stringify: (obj: unknown, options?: StringifyOptions & {
313
+ plugins?: boolean | PluginManager;
314
+ }) => string;
315
+ parseUrl: typeof parseUrl;
316
+ stringifyUrl: typeof stringifyUrl;
317
+ QueryBuilder: typeof QueryBuilder;
318
+ builder: (options?: QueryBuilderOptions) => QueryBuilder;
319
+ q: {
320
+ string: () => StringSchema;
321
+ number: () => NumberSchema;
322
+ boolean: () => BooleanSchema;
323
+ date: () => DateSchema;
324
+ array: <T>(schema?: BaseSchema<T>) => ArraySchema<T>;
325
+ object: <T extends Record<string, unknown> = Record<string, unknown>>() => ObjectSchema<T>;
326
+ enum: <T extends readonly [string, ...string[]]>(...values: T) => EnumSchema<T>;
327
+ union: <T extends readonly SchemaType[]>(...schemas: T) => UnionSchema<T>;
328
+ literal: <T extends string | number | boolean>(value: T) => BaseSchema<T>;
329
+ any: () => BaseSchema<any>;
330
+ unknown: () => BaseSchema<unknown>;
331
+ null: () => BaseSchema<null>;
332
+ undefined: () => BaseSchema<undefined>;
333
+ void: () => BaseSchema<void>;
334
+ };
335
+ schema: typeof schema;
336
+ validate: typeof validate;
337
+ isValid: typeof isValid;
338
+ plugins: PluginManager;
339
+ createSecureParser: (options?: SecurityOptions) => ((input: string, options?: ParseOptions) => ParsedQuery);
340
+ version: string;
341
+ };
342
+
343
+ export { type ArrayFormat, type ArraySchema, type BaseSchema, type BooleanSchema, type DateSchema, type EnumSchema, type NullableSchema, type NumberSchema, type ObjectSchema, type OptionalSchema, type ParseOptions, type ParsedQuery, type ParsedUrl, PluginManager, type Primitive, QueryBuilder, type QueryBuilderOptions, type QueryStringPlugin, type QueryValue, type SchemaType, type SchemaValidationResult, type SecurityOptions, type StringSchema, type StringifyOptions, type TypeCoercionOptions, type UnionSchema, base64Plugin, compressPlugin, countKeys, createCustomPlugin, createPlugin, createSecureParser, querystring as default, detectXSS, filterEmptyPlugin, hasPrototypePollution, isValid, lowercaseKeysPlugin, normalizePlugin, parse, parseUrl, q, querystring, sanitizeInput, schema, secureStringify, sortKeysPlugin, stringify, stringifyUrl, timestampPlugin, validate, validateSecurity };