parse-nested-form-data 1.0.1 → 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.
- package/README.md +309 -174
- package/dist/index.d.ts +131 -36
- package/dist/parse-nested-form-data.cjs.js +576 -445
- package/dist/parse-nested-form-data.esm.js +571 -442
- package/dist/parse-nested-form-data.umd.js +607 -475
- package/dist/parse-nested-form-data.umd.js.map +1 -1
- package/dist/parse-nested-form-data.umd.min.js +7 -7
- package/dist/parse-nested-form-data.umd.min.js.map +1 -1
- package/package.json +108 -54
- package/CHANGELOG.md +0 -13
- package/dist/__tests__/index.d.ts +0 -1
|
@@ -1,476 +1,608 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @name parse-nested-form-data
|
|
3
|
+
* @license MIT license.
|
|
4
|
+
* @copyright (c) 2022 Christian Schurr
|
|
5
|
+
* @author Christian Schurr <chris@schurr.dev>
|
|
6
|
+
*/
|
|
7
|
+
(function(global, factory) {
|
|
8
|
+
typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.parseNestedFormData = {}));
|
|
9
|
+
})(this, function(exports) {
|
|
10
|
+
Object.defineProperties(exports, {
|
|
11
|
+
__esModule: { value: true },
|
|
12
|
+
[Symbol.toStringTag]: { value: "Module" }
|
|
13
|
+
});
|
|
14
|
+
// src/errors.ts
|
|
15
|
+
/**
|
|
16
|
+
* Thrown when a path is used multiple times or has mismatching path parts.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* const formData = new FormData()
|
|
21
|
+
* formData.append('a[0]', 'b')
|
|
22
|
+
* formData.append('a[0]', 'c')
|
|
23
|
+
* parseFormData(formData)
|
|
24
|
+
* // throws DuplicateKeyError('a[0]')
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* const formData = new FormData()
|
|
30
|
+
* formData.append('a', 'b')
|
|
31
|
+
* formData.append('a', 'c')
|
|
32
|
+
* parseFormData(formData)
|
|
33
|
+
* // throws DuplicateKeyError('a')
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* const formData = new FormData()
|
|
39
|
+
* formData.append('a', 'b')
|
|
40
|
+
* formData.append('a[]', 'c')
|
|
41
|
+
* parseFormData(formData)
|
|
42
|
+
* // throws DuplicateKeyError('a[]')
|
|
43
|
+
* ```
|
|
44
|
+
*
|
|
45
|
+
*/
|
|
46
|
+
var DuplicateKeyError = class extends Error {
|
|
47
|
+
constructor(key) {
|
|
48
|
+
super(`Duplicate key at path part ${key}`);
|
|
49
|
+
this.name = "DuplicateKeyError";
|
|
50
|
+
this.key = key;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Thrown when an array is used at the same path with an order parameter and
|
|
55
|
+
* without an order parameter.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```ts
|
|
59
|
+
* const formData = new FormData()
|
|
60
|
+
* formData.append('a[0]', 'a')
|
|
61
|
+
* formData.append('a[]', 'b')
|
|
62
|
+
* parseFormData(formData)
|
|
63
|
+
* // => throws `MixedArrayError(a[])`
|
|
64
|
+
* ```
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```ts
|
|
68
|
+
* const formData = new FormData()
|
|
69
|
+
* formData.append('a[]', 'a')
|
|
70
|
+
* formData.append('a[0]', 'b')
|
|
71
|
+
* parseFormData(formData)
|
|
72
|
+
* // => throws `MixedArrayError(a[0])`
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
var MixedArrayError = class extends Error {
|
|
76
|
+
constructor(key) {
|
|
77
|
+
super(`Mixed array at path part ${key}`);
|
|
78
|
+
this.name = "MixedArrayError";
|
|
79
|
+
this.key = key;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Cuts a path to 100 characters plus `...`, so a huge path from a client
|
|
84
|
+
* doesn't end up in full in logs or error responses.
|
|
85
|
+
*/
|
|
86
|
+
function shortKey(key) {
|
|
87
|
+
return key.length > 100 ? `${key.slice(0, 100)}...` : key;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Thrown when an object path part is `__proto__`, `constructor` or
|
|
91
|
+
* `prototype`, which could modify `Object.prototype`. The names are rejected
|
|
92
|
+
* at any position in the path. Entries with other names on `Object.prototype`
|
|
93
|
+
* (`toString`, ...) are removed instead (see `parseFormData`).
|
|
94
|
+
* `key` is the path up to the forbidden part, cut to 100 characters plus `...`
|
|
95
|
+
* when it's longer.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* const formData = new FormData()
|
|
100
|
+
* formData.append('__proto__.polluted', 'yes')
|
|
101
|
+
* parseFormData(formData)
|
|
102
|
+
* // throws ForbiddenKeyError('__proto__')
|
|
103
|
+
* ```
|
|
104
|
+
*/
|
|
105
|
+
var ForbiddenKeyError = class extends Error {
|
|
106
|
+
constructor(key) {
|
|
107
|
+
key = shortKey(key);
|
|
108
|
+
super(`Forbidden key at path part ${key}`);
|
|
109
|
+
this.name = "ForbiddenKeyError";
|
|
110
|
+
this.key = key;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
/**
|
|
114
|
+
* Thrown when a path has more path parts than the `depth` option allows.
|
|
115
|
+
* `key` is the path up to the first path part over the limit, cut to
|
|
116
|
+
* 100 characters plus `...` when it's longer.
|
|
117
|
+
* Within one entry the depth is checked first, so a path that's too deep throws
|
|
118
|
+
* `DepthLimitError` even if it would also throw another error, like a
|
|
119
|
+
* `ForbiddenKeyError` for `__proto__`.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```ts
|
|
123
|
+
* const formData = new FormData()
|
|
124
|
+
* formData.append('a.b[0].c', 'x')
|
|
125
|
+
* parseFormData(formData, {depth: 2})
|
|
126
|
+
* // throws DepthLimitError('a.b[0]')
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
var DepthLimitError = class extends Error {
|
|
130
|
+
constructor(key) {
|
|
131
|
+
key = shortKey(key);
|
|
132
|
+
super(`Depth limit exceeded at path part ${key}`);
|
|
133
|
+
this.name = "DepthLimitError";
|
|
134
|
+
this.key = key;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Thrown when an array index in a path is larger than `4294967294`, the
|
|
139
|
+
* largest index a JavaScript array can hold.
|
|
140
|
+
* `key` is the path up to that array part, cut to 100 characters plus `...`
|
|
141
|
+
* when it's longer.
|
|
142
|
+
*
|
|
143
|
+
* @example
|
|
144
|
+
* ```ts
|
|
145
|
+
* const formData = new FormData()
|
|
146
|
+
* formData.append('a[4294967295]', 'b')
|
|
147
|
+
* parseFormData(formData)
|
|
148
|
+
* // throws InvalidPathError('a[4294967295]')
|
|
149
|
+
* ```
|
|
150
|
+
*/
|
|
151
|
+
var InvalidPathError = class extends Error {
|
|
152
|
+
constructor(key) {
|
|
153
|
+
key = shortKey(key);
|
|
154
|
+
super(`Invalid path at path part ${key}`);
|
|
155
|
+
this.name = "InvalidPathError";
|
|
156
|
+
this.key = key;
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
// src/path-parts.ts
|
|
160
|
+
/**
|
|
161
|
+
* Finds the `]` that ends the bracket part starting at the `[` at `open`.
|
|
162
|
+
* Returns -1 if this `[` is not a bracket part but a normal character of the key.
|
|
163
|
+
*
|
|
164
|
+
* Brackets can be nested: in `a[b[c]]` the last `]` belongs to
|
|
165
|
+
* the first `[`.
|
|
166
|
+
*
|
|
167
|
+
* Special cases:
|
|
168
|
+
* - Some `[` are never closed. The part then ends at the last `]`:
|
|
169
|
+
* `a[[0]` => key `[0`.
|
|
170
|
+
* - If there is no `]` after the `[` at all, the `[` is a normal character:
|
|
171
|
+
* `a[0` => key `a[0`.
|
|
172
|
+
* - The same goes for a `]` without a `[`: `a]b` => key `a]b`, and
|
|
173
|
+
* `a[b]]` => key `]` inside `b`.
|
|
174
|
+
*
|
|
175
|
+
* The scan stops at the returned `]`. The caller continues from there, so no
|
|
176
|
+
* character of the path is scanned twice.
|
|
177
|
+
*/
|
|
178
|
+
function closeOf(path, open, lastClose) {
|
|
179
|
+
if (open > lastClose) return -1;
|
|
180
|
+
let nesting = 0;
|
|
181
|
+
for (let idx = open; idx < lastClose; idx++) if (path[idx] === "[") nesting++;
|
|
182
|
+
else if (path[idx] === "]" && --nesting === 0) return idx;
|
|
183
|
+
return lastClose;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
*
|
|
187
|
+
* Transforms a FormData path into an array of `PathPart`s.
|
|
188
|
+
*
|
|
189
|
+
* @param path - the path to extract the path parts from
|
|
190
|
+
* @param depth - the maximum number of path parts (default: `Infinity`)
|
|
191
|
+
* @returns {Array<PathPart>} the extracted path parts
|
|
192
|
+
* @throws `DepthLimitError` if the path has more path parts than `depth`, at
|
|
193
|
+
* the first part over the limit
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* ```ts
|
|
197
|
+
* const path = 'a[0].b'
|
|
198
|
+
* const result = extractPathParts(path)
|
|
199
|
+
* // => [{path: 'a', type: 'object', default: [], pathToPart: 'a'},
|
|
200
|
+
* // {path: '0', type: 'array', default: {}, pathToPart: 'a[0]'},
|
|
201
|
+
* // {path: 'b', type: 'object', default: {}, pathToPart: 'a[0].b'}]
|
|
202
|
+
* ```
|
|
203
|
+
*
|
|
204
|
+
* @example
|
|
205
|
+
* ```ts
|
|
206
|
+
* const path = 'a.b'
|
|
207
|
+
* const result = extractPathParts(path)
|
|
208
|
+
* // => [{path: 'a', type: 'object', default: {}, pathToPart: 'a'},
|
|
209
|
+
* // {path: 'b', type: 'object', default: {}, pathToPart: 'a.b'}]
|
|
210
|
+
* ```
|
|
211
|
+
*
|
|
212
|
+
* @example
|
|
213
|
+
* ```ts
|
|
214
|
+
* const path = 'a[b][0]'
|
|
215
|
+
* const result = extractPathParts(path)
|
|
216
|
+
* // => [{path: 'a', type: 'object', default: {}, pathToPart: 'a'},
|
|
217
|
+
* // {path: 'b', type: 'object', default: [], pathToPart: 'a[b]'},
|
|
218
|
+
* // {path: '0', type: 'array', default: {}, pathToPart: 'a[b][0]'}]
|
|
219
|
+
* ```
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```ts
|
|
223
|
+
* const path = 'a[][0]'
|
|
224
|
+
* const result = extractPathParts(path)
|
|
225
|
+
* // => [{path: 'a', type: 'object', default: [], pathToPart: 'a'},
|
|
226
|
+
* // {path: '', type: 'array', default: [], pathToPart: 'a[]'},
|
|
227
|
+
* // {path: '0', type: 'array', default: {}, pathToPart: 'a[][0]'}]
|
|
228
|
+
* ```
|
|
229
|
+
*
|
|
230
|
+
*
|
|
231
|
+
*/
|
|
232
|
+
function extractPathParts(path, depth = Infinity) {
|
|
233
|
+
const lastClose = path.lastIndexOf("]");
|
|
234
|
+
const parts = [];
|
|
235
|
+
const addPart = (key, type, end) => {
|
|
236
|
+
if (key === "" && type === "object") return;
|
|
237
|
+
if (parts.length === depth) throw new DepthLimitError(path.slice(0, end));
|
|
238
|
+
parts.push({
|
|
239
|
+
path: key,
|
|
240
|
+
type,
|
|
241
|
+
default: {},
|
|
242
|
+
pathToPart: path.slice(0, end)
|
|
243
|
+
});
|
|
244
|
+
};
|
|
245
|
+
let start = 0;
|
|
246
|
+
for (let idx = 0; idx < path.length; idx++) {
|
|
247
|
+
const close = path[idx] === "[" ? closeOf(path, idx, lastClose) : -1;
|
|
248
|
+
if (path[idx] !== "." && close < idx) continue;
|
|
249
|
+
addPart(path.slice(start, idx), "object", idx);
|
|
250
|
+
if (close > idx) {
|
|
251
|
+
const key = path.slice(idx + 1, close);
|
|
252
|
+
addPart(key, /^\d*$/.test(key) ? "array" : "object", close + 1);
|
|
253
|
+
idx = close;
|
|
254
|
+
}
|
|
255
|
+
start = idx + 1;
|
|
256
|
+
}
|
|
257
|
+
addPart(path.slice(start), "object", path.length);
|
|
258
|
+
parts.forEach((part, idx) => {
|
|
259
|
+
if (parts[idx + 1]?.type === "array") part.default = [];
|
|
260
|
+
});
|
|
261
|
+
return parts;
|
|
262
|
+
}
|
|
263
|
+
// src/transform.ts
|
|
264
|
+
/**
|
|
265
|
+
* Default Transformer for `parseFormData`.
|
|
266
|
+
*
|
|
267
|
+
* Transforms a FormData Entry into a path and a `JsonLeafValue`.
|
|
268
|
+
*
|
|
269
|
+
* - `path` starts with `+` -> transform value to `number`
|
|
270
|
+
* - `path` starts with `&` -> transform value to `boolean`
|
|
271
|
+
* - `path` starts with `-` -> transform value to `null`
|
|
272
|
+
*
|
|
273
|
+
* @example
|
|
274
|
+
* ```ts
|
|
275
|
+
* const entry = ['a[0]', 'b']
|
|
276
|
+
* const result = defaultTransform(entry)
|
|
277
|
+
* // => {path: 'a[0]', value: 'b'}
|
|
278
|
+
* ```
|
|
279
|
+
*
|
|
280
|
+
* @example
|
|
281
|
+
* ```ts
|
|
282
|
+
* const entry = ['+a[0]', '1']
|
|
283
|
+
* const result = defaultTransform(entry)
|
|
284
|
+
* // => {path: 'a[0]', value: 1}
|
|
285
|
+
* ```
|
|
286
|
+
*
|
|
287
|
+
* @example
|
|
288
|
+
* ```ts
|
|
289
|
+
* const entry = ['&a[0]', 'true']
|
|
290
|
+
* const result = defaultTransform(entry)
|
|
291
|
+
* // => {path: 'a[0]', value: true}
|
|
292
|
+
* ```
|
|
293
|
+
*
|
|
294
|
+
* @example
|
|
295
|
+
* ```ts
|
|
296
|
+
* const entry = ['-a[0]', 'null']
|
|
297
|
+
* const result = defaultTransform(entry)
|
|
298
|
+
* // => {path: 'a[0]', value: null}
|
|
299
|
+
* ```
|
|
300
|
+
*
|
|
301
|
+
* @example
|
|
302
|
+
* ```ts
|
|
303
|
+
* const entry = ['a[0]', new File([''], 'file.txt')]
|
|
304
|
+
* const result = defaultTransform(entry)
|
|
305
|
+
* // => {path: 'a[0]', value: File}
|
|
306
|
+
* ```
|
|
307
|
+
*
|
|
308
|
+
*
|
|
309
|
+
* @param entry [path, value]: the FormData entry
|
|
310
|
+
* @returns the path and the transformed value
|
|
311
|
+
*/
|
|
312
|
+
function defaultTransform(entry) {
|
|
313
|
+
let path = entry[0];
|
|
314
|
+
let value = entry[1];
|
|
315
|
+
if (path.startsWith("+")) {
|
|
316
|
+
path = path.slice(1);
|
|
317
|
+
value = Number(value);
|
|
318
|
+
} else if (path.startsWith("&")) {
|
|
319
|
+
path = path.slice(1);
|
|
320
|
+
value = value === "on" || value === "true" || Boolean(Number(value));
|
|
321
|
+
} else if (path.startsWith("-")) {
|
|
322
|
+
path = path.slice(1);
|
|
323
|
+
value = null;
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
path,
|
|
327
|
+
value
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
// src/index.ts
|
|
331
|
+
const FORBIDDEN_OBJECT_KEYS = /* @__PURE__ */ new Set([
|
|
332
|
+
"__proto__",
|
|
333
|
+
"constructor",
|
|
334
|
+
"prototype"
|
|
335
|
+
]);
|
|
336
|
+
const MAX_ARRAY_INDEX = 4294967294;
|
|
337
|
+
function isPrototypeKey(key) {
|
|
338
|
+
return Object.getOwnPropertyDescriptor(Object.prototype, key) !== void 0;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Detects `File` and `Blob` values by their `Symbol.toStringTag`, which works
|
|
342
|
+
* for native instances, polyfills (e.g. `@remix-run/web-file`) and values from
|
|
343
|
+
* other realms, where `instanceof` would fail.
|
|
344
|
+
*/
|
|
345
|
+
function isFileLike(val) {
|
|
346
|
+
const tag = Object.prototype.toString.call(val);
|
|
347
|
+
return tag === "[object File]" || tag === "[object Blob]";
|
|
348
|
+
}
|
|
349
|
+
function isJsonObject(val) {
|
|
350
|
+
return typeof val === "object" && !Array.isArray(val) && val !== null && !isFileLike(val);
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
*
|
|
354
|
+
* Returns the value accessed via `pathPart` in the `currentPathObject`,
|
|
355
|
+
* a setter function to set the value in the `currentPathObject` via the
|
|
356
|
+
* provided `pathPart`, and the key (object key or array index) it uses.
|
|
357
|
+
*
|
|
358
|
+
* @param pathPart - the path part to get the value, setter and key for
|
|
359
|
+
* @param currentPathObject - the object at the current path (before the path part)
|
|
360
|
+
* @param arraysWithOrder - a set of arrays that have an order
|
|
361
|
+
* @returns the current value, a setter for it, and the key (object key or
|
|
362
|
+
* array index) in `currentPathObject`
|
|
363
|
+
*
|
|
364
|
+
* @example
|
|
365
|
+
* ```ts
|
|
366
|
+
* const pathPart = {path: 'a', type: 'object', default: {}, pathToPart: 'a'}
|
|
367
|
+
* const currentPathObject = {}
|
|
368
|
+
* const arraysWithOrder = new Set()
|
|
369
|
+
* const [value, setValue, key] = handlePathPart(pathPart, currentPathObject, arraysWithOrder)
|
|
370
|
+
* setValue('b')
|
|
371
|
+
* // => currentPathObject = {a: 'b'}, key = 'a'
|
|
372
|
+
* ```
|
|
373
|
+
*
|
|
374
|
+
* @example
|
|
375
|
+
* ```ts
|
|
376
|
+
* const pathPart = {path: '0', type: 'array', default: [], pathToPart: 'a[0]'}
|
|
377
|
+
* const currentPathObject = {a: []}
|
|
378
|
+
* const arraysWithOrder = new Set()
|
|
379
|
+
* const [value, setValue, key] = handlePathPart(pathPart, currentPathObject.a, arraysWithOrder)
|
|
380
|
+
* setValue('b')
|
|
381
|
+
* // => currentPathObject = {a: ['b']}, key = 0
|
|
382
|
+
* ```
|
|
383
|
+
*
|
|
384
|
+
*/
|
|
385
|
+
function handlePathPart(pathPart, currentPathObject, arraysWithOrder) {
|
|
386
|
+
if (pathPart.type === "object") {
|
|
387
|
+
const key = pathPart.path;
|
|
388
|
+
if (FORBIDDEN_OBJECT_KEYS.has(key)) throw new ForbiddenKeyError(pathPart.pathToPart);
|
|
389
|
+
if (Array.isArray(currentPathObject)) throw new DuplicateKeyError(pathPart.pathToPart);
|
|
390
|
+
const currentObject = currentPathObject;
|
|
391
|
+
return [
|
|
392
|
+
Object.prototype.hasOwnProperty.call(currentObject, key) ? currentObject[key] : void 0,
|
|
393
|
+
(val) => {
|
|
394
|
+
if (!isPrototypeKey(key)) {
|
|
395
|
+
currentObject[key] = val;
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
Object.defineProperty(currentObject, key, {
|
|
399
|
+
value: val,
|
|
400
|
+
writable: true,
|
|
401
|
+
enumerable: true,
|
|
402
|
+
configurable: true
|
|
403
|
+
});
|
|
404
|
+
},
|
|
405
|
+
key
|
|
406
|
+
];
|
|
407
|
+
}
|
|
408
|
+
const isOrdered = pathPart.path !== "";
|
|
409
|
+
if (isOrdered && Number(pathPart.path) > MAX_ARRAY_INDEX) throw new InvalidPathError(pathPart.pathToPart);
|
|
410
|
+
if (!Array.isArray(currentPathObject)) throw new DuplicateKeyError(pathPart.pathToPart);
|
|
411
|
+
const currentArray = currentPathObject;
|
|
412
|
+
const isOrderedArray = arraysWithOrder.has(currentArray);
|
|
413
|
+
if (isOrdered) arraysWithOrder.add(currentArray);
|
|
414
|
+
if (!isOrdered && isOrderedArray || isOrdered && !isOrderedArray && currentArray.length > 0) throw new MixedArrayError(pathPart.pathToPart);
|
|
415
|
+
const order = isOrdered ? Number(pathPart.path) : currentArray.length;
|
|
416
|
+
return [
|
|
417
|
+
currentArray[order],
|
|
418
|
+
(val) => currentArray[order] = val,
|
|
419
|
+
order
|
|
420
|
+
];
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
*
|
|
424
|
+
* Parses a FormData object to a JSON object. This is done by parsing the `name`
|
|
425
|
+
* attribute of each `FormDataEntryValue` and then inserting the value at the
|
|
426
|
+
* path. Also by default the start of the path is used to transform the value.
|
|
427
|
+
*
|
|
428
|
+
*
|
|
429
|
+
* In front of the whole `key`:
|
|
430
|
+
* - `+` => parse to `Number`
|
|
431
|
+
* - `-` => set value to `null`
|
|
432
|
+
* - `&` => parse to `Boolean`
|
|
433
|
+
*
|
|
434
|
+
* - `.` between path parts => nest into `objects`
|
|
435
|
+
* - `[key]` after path part => nest into `objects`, same as `.key`; the text
|
|
436
|
+
* in brackets is the key as it is (`a[b.c]` => key `b.c`)
|
|
437
|
+
* - `[\d*]` after path part => push to array in order `\d` or push to end if `[]`
|
|
438
|
+
*
|
|
439
|
+
* @example
|
|
440
|
+
* ```ts
|
|
441
|
+
* const formData = new FormData()
|
|
442
|
+
* formData.append('+a', '1')
|
|
443
|
+
* formData.append('&b', 'true')
|
|
444
|
+
* formData.append('-c', 'null')
|
|
445
|
+
* formData.append('d', 'foo')
|
|
446
|
+
* parseFormData(formData)
|
|
447
|
+
* // => {a: 1, b: true, c: null, d: 'foo'}
|
|
448
|
+
* ```
|
|
449
|
+
*
|
|
450
|
+
* @example
|
|
451
|
+
* ```ts
|
|
452
|
+
* const formData = new FormData()
|
|
453
|
+
* formData.append('a.b', 'foo')
|
|
454
|
+
* parseFormData(formData)
|
|
455
|
+
* // => {a: {b: 'foo'}}
|
|
456
|
+
* ```
|
|
457
|
+
*
|
|
458
|
+
* @example
|
|
459
|
+
* ```ts
|
|
460
|
+
* const formData = new FormData()
|
|
461
|
+
* formData.append('a[b]', 'foo')
|
|
462
|
+
* formData.append('a.c', 'bar')
|
|
463
|
+
* parseFormData(formData)
|
|
464
|
+
* // => {a: {b: 'foo', c: 'bar'}}
|
|
465
|
+
* ```
|
|
466
|
+
*
|
|
467
|
+
* @example
|
|
468
|
+
* ```ts
|
|
469
|
+
* const formData = new FormData()
|
|
470
|
+
* formData.append('a[0]', 'foo')
|
|
471
|
+
* formData.append('a[1]', 'bar')
|
|
472
|
+
* parseFormData(formData)
|
|
473
|
+
* // => {a: ['foo', 'bar']}
|
|
474
|
+
* ```
|
|
475
|
+
*
|
|
476
|
+
* @example
|
|
477
|
+
* ```ts
|
|
478
|
+
* const formData = new FormData()
|
|
479
|
+
* formData.append('a[]', 'foo')
|
|
480
|
+
* formData.append('a[]', 'bar')
|
|
481
|
+
* parseFormData(formData)
|
|
482
|
+
* // => {a: ['foo', 'bar']}
|
|
483
|
+
* ```
|
|
484
|
+
*
|
|
485
|
+
* @example
|
|
486
|
+
* ```ts
|
|
487
|
+
* const formData = new FormData()
|
|
488
|
+
* formData.append('a[0]', 'foo')
|
|
489
|
+
* parseFormData(formData, {
|
|
490
|
+
* transformEntry: ([path, value]) => ({
|
|
491
|
+
* path,
|
|
492
|
+
* value: typeof value === 'string' ? value + 'bar' : value,
|
|
493
|
+
* }),
|
|
494
|
+
* })
|
|
495
|
+
* // => {a: ['foobar']}
|
|
496
|
+
* ```
|
|
497
|
+
*
|
|
498
|
+
* @example
|
|
499
|
+
* ```ts
|
|
500
|
+
* const formData = new FormData()
|
|
501
|
+
* formData.append('a[0]', 'foo')
|
|
502
|
+
* formData.append('a[1]', '')
|
|
503
|
+
* parseFormData(formData, {removeEmptyString: true})
|
|
504
|
+
* // => {a: ['foo']}
|
|
505
|
+
* ```
|
|
506
|
+
*
|
|
507
|
+
* @param {Iterable<[string, string | File]>} formData - an iterator of an [`path`, `value`] tuple
|
|
508
|
+
* - `path` := an optional prefix (`+`, `-`, `&`), then path parts: keys after
|
|
509
|
+
* `.` or in brackets (`[key]`), and array parts `[]` or `[\d+]` (e.g.
|
|
510
|
+
* `+a[][1].b[c]`)
|
|
511
|
+
* - `value` := `string` or `File` (native or polyfilled `File` values are kept
|
|
512
|
+
* as they are)
|
|
513
|
+
* @param {ParseFormDataOptions} options - options for parsing the form data
|
|
514
|
+
* - `transformEntry` - a function to transform the path and the value before
|
|
515
|
+
* inserting the value at the path in the resulting object (default: `defaultTransform`)
|
|
516
|
+
* - `removeEmptyString` - if `true` removes all entries where the value is an empty string
|
|
517
|
+
* - `depth` - the maximum number of path parts in a path, counting every part
|
|
518
|
+
* (default: `Infinity`)
|
|
519
|
+
* @returns {JsonObject} the parsed JSON object
|
|
520
|
+
* @throws `TypeError` if `depth` isn't a positive integer or `Infinity`
|
|
521
|
+
* @throws `DepthLimitError` if a path has more path parts than `depth`
|
|
522
|
+
* - e.g. `a.b[0]` with `depth: 2` => `DepthLimitError('a.b[0]')`
|
|
523
|
+
* @throws `DuplicateKeyError` if
|
|
524
|
+
* - two entries set a value at the same path
|
|
525
|
+
* - e.g. `a` and `a`, `a[0]` and `a[0]`, `a.b` and `a[b]`
|
|
526
|
+
* - an entry uses a path part as an object, array or value and another entry
|
|
527
|
+
* uses it differently
|
|
528
|
+
* - e.g. `a` and `a.b`, `a.b` and `a[]`, `a[]` and `a.b`
|
|
529
|
+
* - the path starts with an array part
|
|
530
|
+
* - e.g. `[0]` or `[]`
|
|
531
|
+
* @throws `MixedArrayError` if at a specific path part an unordered array is
|
|
532
|
+
* defined and at a later path part an ordered array is defined or vice versa
|
|
533
|
+
* - e.g. `a[0]` and `a[]`
|
|
534
|
+
* - e.g. `a[]` and `a[0]`
|
|
535
|
+
* @throws `ForbiddenKeyError` if an object path part is `__proto__`,
|
|
536
|
+
* `constructor` or `prototype`
|
|
537
|
+
* - e.g. `__proto__.polluted`
|
|
538
|
+
* @throws `InvalidPathError` if an array index is larger than `4294967294`
|
|
539
|
+
* - e.g. `a[4294967295]`
|
|
540
|
+
*
|
|
541
|
+
* Every error's `key` is the path after `transformEntry`, not the field name
|
|
542
|
+
* (e.g. `+a.b.c` with `depth: 2` => `DepthLimitError('a.b.c')`).
|
|
543
|
+
*
|
|
544
|
+
* An entry with any other object path part named like a property on
|
|
545
|
+
* `Object.prototype` (`toString`, `hasOwnProperty`, ...) is removed from the
|
|
546
|
+
* result. It's parsed like any other entry first, so it causes the same errors
|
|
547
|
+
* as an unused name: an error doesn't tell the client which properties exist
|
|
548
|
+
* on the server's `Object.prototype`.
|
|
549
|
+
* - e.g. `user.toString` => `{}`
|
|
550
|
+
* - e.g. `user[toString]` => `{}`
|
|
551
|
+
*/
|
|
552
|
+
function parseFormData(formData, { removeEmptyString = false, transformEntry = defaultTransform, depth = Infinity } = {}) {
|
|
553
|
+
if (depth !== Infinity && !(Number.isInteger(depth) && depth > 0)) throw new TypeError(`depth must be a positive integer or Infinity, got ${String(depth)}`);
|
|
554
|
+
const result = {};
|
|
555
|
+
const arraysWithOrder = /* @__PURE__ */ new Set();
|
|
556
|
+
const createdByRemoved = [];
|
|
557
|
+
for (const entry of Array.from(formData)) {
|
|
558
|
+
if (removeEmptyString && entry[1] === "") continue;
|
|
559
|
+
const { path, value } = transformEntry(entry, defaultTransform);
|
|
560
|
+
const pathParts = extractPathParts(path, depth);
|
|
561
|
+
const isRemoved = pathParts.some((pathPart) => pathPart.type === "object" && isPrototypeKey(pathPart.path));
|
|
562
|
+
let currentPathObject = result;
|
|
563
|
+
pathParts.forEach((pathPart, idx) => {
|
|
564
|
+
const [nextPathValue, setNextPathValue, key] = handlePathPart(pathPart, currentPathObject, arraysWithOrder);
|
|
565
|
+
const parent = currentPathObject;
|
|
566
|
+
if (pathParts.length - 1 === idx) {
|
|
567
|
+
if (nextPathValue !== void 0) throw new DuplicateKeyError(pathPart.pathToPart);
|
|
568
|
+
setNextPathValue(value);
|
|
569
|
+
if (isRemoved) createdByRemoved.push([
|
|
570
|
+
parent,
|
|
571
|
+
key,
|
|
572
|
+
void 0
|
|
573
|
+
]);
|
|
574
|
+
} else {
|
|
575
|
+
if (nextPathValue !== void 0 && !isJsonObject(nextPathValue) && !Array.isArray(nextPathValue)) throw new DuplicateKeyError(pathPart.pathToPart);
|
|
576
|
+
const nextPathObject = nextPathValue ?? pathPart.default;
|
|
577
|
+
currentPathObject = nextPathObject;
|
|
578
|
+
setNextPathValue(nextPathObject);
|
|
579
|
+
if (isRemoved && nextPathValue === void 0) createdByRemoved.push([
|
|
580
|
+
parent,
|
|
581
|
+
key,
|
|
582
|
+
nextPathObject
|
|
583
|
+
]);
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
for (let idx = createdByRemoved.length - 1; idx >= 0; idx--) {
|
|
588
|
+
const [parent, key, container] = createdByRemoved[idx];
|
|
589
|
+
if (container && Object.keys(container).length > 0) continue;
|
|
590
|
+
Reflect.deleteProperty(parent, key);
|
|
591
|
+
if (Array.isArray(parent)) arraysWithOrder.add(parent);
|
|
592
|
+
}
|
|
593
|
+
for (const orderedArray of Array.from(arraysWithOrder)) {
|
|
594
|
+
const values = Object.values(orderedArray);
|
|
595
|
+
orderedArray.length = 0;
|
|
596
|
+
for (const value of values) orderedArray.push(value);
|
|
597
|
+
}
|
|
598
|
+
return result;
|
|
599
|
+
}
|
|
600
|
+
exports.DepthLimitError = DepthLimitError;
|
|
601
|
+
exports.DuplicateKeyError = DuplicateKeyError;
|
|
602
|
+
exports.ForbiddenKeyError = ForbiddenKeyError;
|
|
603
|
+
exports.InvalidPathError = InvalidPathError;
|
|
604
|
+
exports.MixedArrayError = MixedArrayError;
|
|
605
|
+
exports.parseFormData = parseFormData;
|
|
606
|
+
});
|
|
6
607
|
|
|
7
|
-
|
|
8
|
-
* @name parse-nested-form-data
|
|
9
|
-
* @license MIT license.
|
|
10
|
-
* @copyright (c) 2022 Christian Schurr
|
|
11
|
-
* @author Christian Schurr <chris@schurr.dev>
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Thrown when a path is used multiple times or has missmatching path parts.
|
|
16
|
-
*
|
|
17
|
-
* @example
|
|
18
|
-
* ```ts
|
|
19
|
-
* const formData = new FormData()
|
|
20
|
-
* formData.append('a[0]', 'b')
|
|
21
|
-
* formData.append('a[0]', 'c')
|
|
22
|
-
* parseFormData(formData)
|
|
23
|
-
* // throws DuplicateKeyError('a[0]')
|
|
24
|
-
* ```
|
|
25
|
-
*
|
|
26
|
-
* @example
|
|
27
|
-
* ```ts
|
|
28
|
-
* const formData = new FormData()
|
|
29
|
-
* formData.append('a', 'b')
|
|
30
|
-
* formData.append('a', 'c')
|
|
31
|
-
* parseFormData(formData)
|
|
32
|
-
* // throws DuplicateKeyError('a')
|
|
33
|
-
*
|
|
34
|
-
* @example
|
|
35
|
-
* ```ts
|
|
36
|
-
* const formData = new FormData()
|
|
37
|
-
* formData.append('a', 'b')
|
|
38
|
-
* formData.append('a[]', 'c')
|
|
39
|
-
* parseFormData(formData)
|
|
40
|
-
* // throws DuplicateKeyError('a[]')
|
|
41
|
-
* ```
|
|
42
|
-
*
|
|
43
|
-
*/
|
|
44
|
-
class DuplicateKeyError extends Error {
|
|
45
|
-
constructor(key) {
|
|
46
|
-
super(`Duplicate key at path part ${key}`);
|
|
47
|
-
this.key = void 0;
|
|
48
|
-
this.key = key;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* Thrown when an array is used at the same path with an order parameter and
|
|
53
|
-
* without an order parameter.
|
|
54
|
-
*
|
|
55
|
-
* @example
|
|
56
|
-
* ```ts
|
|
57
|
-
* const formData = new FormData()
|
|
58
|
-
* formData.append('a[0]', 'a')
|
|
59
|
-
* formData.append('a[]', 'b')
|
|
60
|
-
* parseFormData(formData)
|
|
61
|
-
* // => throws `MixedArrayError(a[])`
|
|
62
|
-
* ```
|
|
63
|
-
*
|
|
64
|
-
* @example
|
|
65
|
-
* ```ts
|
|
66
|
-
* const formData = new FormData()
|
|
67
|
-
* formData.append('a[]', 'a')
|
|
68
|
-
* formData.append('a[0]', 'b')
|
|
69
|
-
* parseFormData(formData)
|
|
70
|
-
* // => throws `MixedArrayError(a[0])`
|
|
71
|
-
* ```
|
|
72
|
-
*/
|
|
73
|
-
class MixedArrayError extends Error {
|
|
74
|
-
constructor(key) {
|
|
75
|
-
super(`Mixed array at path part ${key}`);
|
|
76
|
-
this.key = void 0;
|
|
77
|
-
this.key = key;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Thrown when a path part would access or assign a property on
|
|
82
|
-
* `Object.prototype` (`__proto__`, `constructor`, `prototype`). Rejected
|
|
83
|
-
* regardless of whether pollution would actually occur, to keep input
|
|
84
|
-
* unambiguous.
|
|
85
|
-
*
|
|
86
|
-
* @example
|
|
87
|
-
* ```ts
|
|
88
|
-
* const formData = new FormData()
|
|
89
|
-
* formData.append('__proto__.polluted', 'yes')
|
|
90
|
-
* parseFormData(formData)
|
|
91
|
-
* // throws ForbiddenKeyError('__proto__')
|
|
92
|
-
* ```
|
|
93
|
-
*/
|
|
94
|
-
class ForbiddenKeyError extends Error {
|
|
95
|
-
constructor(key) {
|
|
96
|
-
super(`Forbidden key at path part ${key}`);
|
|
97
|
-
this.key = void 0;
|
|
98
|
-
this.key = key;
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
const FORBIDDEN_OBJECT_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
102
|
-
function isJsonObject(val) {
|
|
103
|
-
return typeof val === 'object' && !Array.isArray(val) && val !== null && !(val instanceof webFile.File);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Default Transformer for `parseFormData`.
|
|
108
|
-
*
|
|
109
|
-
* Transforms a FormData Entry into a path and a `JsonLeafValue`.
|
|
110
|
-
*
|
|
111
|
-
* - `path` starts with `+` -> transform value to `number`
|
|
112
|
-
* - `path` starts with `&` -> transform value to `boolean`
|
|
113
|
-
* - `path` starts with `-` -> transform value to `null`
|
|
114
|
-
*
|
|
115
|
-
* @example
|
|
116
|
-
* ```ts
|
|
117
|
-
* const entry = ['a[0]', 'b']
|
|
118
|
-
* const result = defaultTransform(entry)
|
|
119
|
-
* // => {path: 'a[0]', value: 'b'}
|
|
120
|
-
* ```
|
|
121
|
-
*
|
|
122
|
-
* @example
|
|
123
|
-
* ```ts
|
|
124
|
-
* const entry = ['+a[0]', '1']
|
|
125
|
-
* const result = defaultTransform(entry)
|
|
126
|
-
* // => {path: 'a[0]', value: 1}
|
|
127
|
-
* ```
|
|
128
|
-
*
|
|
129
|
-
* @example
|
|
130
|
-
* ```ts
|
|
131
|
-
* const entry = ['&a[0]', 'true']
|
|
132
|
-
* const result = defaultTransform(entry)
|
|
133
|
-
* // => {path: 'a[0]', value: true}
|
|
134
|
-
* ```
|
|
135
|
-
*
|
|
136
|
-
* @example
|
|
137
|
-
* ```ts
|
|
138
|
-
* const entry = ['-a[0]', 'null']
|
|
139
|
-
* const result = defaultTransform(entry)
|
|
140
|
-
* // => {path: 'a[0]', value: null}
|
|
141
|
-
* ```
|
|
142
|
-
*
|
|
143
|
-
* @example
|
|
144
|
-
* ```ts
|
|
145
|
-
* const entry = ['a[0]', new File([''], 'file.txt')]
|
|
146
|
-
* const result = defaultTransform(entry)
|
|
147
|
-
* // => {path: 'a[0]', value: File}
|
|
148
|
-
* ```
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
* @param entry [path, value]: the FormData entry
|
|
152
|
-
* @returns the path and the transformed value
|
|
153
|
-
*/
|
|
154
|
-
function defaultTransform(entry) {
|
|
155
|
-
let path = entry[0];
|
|
156
|
-
let value = entry[1];
|
|
157
|
-
if (path.startsWith('+')) {
|
|
158
|
-
path = path.slice(1);
|
|
159
|
-
value = Number(value);
|
|
160
|
-
} else if (path.startsWith('&')) {
|
|
161
|
-
path = path.slice(1);
|
|
162
|
-
value = value === 'on' || value === 'true' || Boolean(Number(value));
|
|
163
|
-
} else if (path.startsWith('-')) {
|
|
164
|
-
path = path.slice(1);
|
|
165
|
-
value = null;
|
|
166
|
-
}
|
|
167
|
-
return {
|
|
168
|
-
path,
|
|
169
|
-
value
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Options to change the behavior of `parseFormData`.
|
|
175
|
-
* @param transformEntry - a function to transform the FormData entry into a path and a value
|
|
176
|
-
* (default: `defaultTransform`)
|
|
177
|
-
* @param removeEmptyString - skip empty values '' (default: `false`)
|
|
178
|
-
*
|
|
179
|
-
* @example
|
|
180
|
-
* ```ts
|
|
181
|
-
* const formData = new FormData()
|
|
182
|
-
* formData.append('a', '')
|
|
183
|
-
* formData.append('b', 'b')
|
|
184
|
-
* const result = parseFormData(formData, {removeEmptyString: true})
|
|
185
|
-
* // => {b: 'b'}
|
|
186
|
-
* ```
|
|
187
|
-
*
|
|
188
|
-
* @example
|
|
189
|
-
* ```ts
|
|
190
|
-
* const formData = new FormData()
|
|
191
|
-
* formData.append('a', 'a')
|
|
192
|
-
* formData.append('b', 'b')
|
|
193
|
-
* parseFormData(formData, {
|
|
194
|
-
* transformEntry: ([path, value], defaultTransform) => {
|
|
195
|
-
* return {
|
|
196
|
-
* path,
|
|
197
|
-
* value:
|
|
198
|
-
* typeof value === 'string'
|
|
199
|
-
* ? value.toUpperCase()
|
|
200
|
-
* : defaultTransform(value),
|
|
201
|
-
* }
|
|
202
|
-
* },
|
|
203
|
-
* })
|
|
204
|
-
* // => {a: 'A', b: 'B'}
|
|
205
|
-
* ```
|
|
206
|
-
*/
|
|
207
|
-
|
|
208
|
-
/**
|
|
209
|
-
* A parsed part of a FormData path. It consists of four parts:
|
|
210
|
-
* @param path - the key to access the value in the intermediate result
|
|
211
|
-
* @param type - the type of the path part (array - e.g. [\d*], or object .e.g. .key)
|
|
212
|
-
* @param default - the default value of the next path part ([] for array, {} for object)
|
|
213
|
-
* @param pathToPart - the full path to the current path part
|
|
214
|
-
*
|
|
215
|
-
* @example
|
|
216
|
-
* ```ts
|
|
217
|
-
* const path = 'a[0].b'
|
|
218
|
-
* const result = extractPathParts(path)
|
|
219
|
-
* // => [{path: 'a', type: 'object, default: [], pathToPart: 'a'},
|
|
220
|
-
* // {path: '0', type: 'array', default: {}, pathToPart: 'a[0]'},
|
|
221
|
-
* // {path: 'b', type: 'object', default: {}, pathToPart: 'a[0].b'}]
|
|
222
|
-
* ```
|
|
223
|
-
*/
|
|
224
|
-
|
|
225
|
-
/**
|
|
226
|
-
*
|
|
227
|
-
* Transforms a FormData path into an array of `PathPart`s.
|
|
228
|
-
*
|
|
229
|
-
* @param path - the path to extract the path parts from
|
|
230
|
-
* @returns {Array<PathPart>} the extracted path parts
|
|
231
|
-
*
|
|
232
|
-
* @example
|
|
233
|
-
* ```ts
|
|
234
|
-
* const path = 'a[0].b'
|
|
235
|
-
* const result = extractPathParts(path)
|
|
236
|
-
* // => [{path: 'a', type: 'object, default: [], pathToPart: 'a'},
|
|
237
|
-
* // {path: '0', type: 'array', default: {}, pathToPart: 'a[0]'},
|
|
238
|
-
* // {path: 'b', type: 'object', default: {}, pathToPart: 'a[0].b'}]
|
|
239
|
-
* ```
|
|
240
|
-
*
|
|
241
|
-
* @example
|
|
242
|
-
* ```ts
|
|
243
|
-
* const path = 'a.b'
|
|
244
|
-
* const result = extractPathParts(path)
|
|
245
|
-
* // => [{path: 'a', type: 'object, default: {}, pathToPart: 'a'},
|
|
246
|
-
* // {path: 'b', type: 'object', default: {}, pathToPart: 'a.b'}]
|
|
247
|
-
* ```
|
|
248
|
-
*
|
|
249
|
-
* @example
|
|
250
|
-
* ```ts
|
|
251
|
-
* const path = 'a[][0]'
|
|
252
|
-
* const result = extractPathParts(path)
|
|
253
|
-
* // => [{path: 'a', type: 'object, default: [], pathToPart: 'a'},
|
|
254
|
-
* // {path: '', type: 'array', default: [], pathToPart: 'a[]'},
|
|
255
|
-
* // {path: '0', type: 'array', default: {}, pathToPart: 'a[][0]'}]
|
|
256
|
-
* ```
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
*/
|
|
260
|
-
function extractPathParts(path) {
|
|
261
|
-
const re = /((?<array>\d*)\]|(?<pathPart>[^.[]+))(?<nextType>\[|\.|$)/g;
|
|
262
|
-
return Array.from(path.matchAll(re)).map(match => {
|
|
263
|
-
// self casted RegexExpMatchArray to custom
|
|
264
|
-
const typedMatch = match;
|
|
265
|
-
const {
|
|
266
|
-
array,
|
|
267
|
-
pathPart,
|
|
268
|
-
nextType
|
|
269
|
-
} = typedMatch.groups;
|
|
270
|
-
const type = array === undefined ? 'object' : 'array';
|
|
271
|
-
const nextDefault = nextType === '[' ? [] : {};
|
|
272
|
-
return {
|
|
273
|
-
path: array ?? pathPart,
|
|
274
|
-
type,
|
|
275
|
-
default: nextDefault,
|
|
276
|
-
pathToPart: path.slice(0, typedMatch.index + typedMatch[1].length)
|
|
277
|
-
};
|
|
278
|
-
});
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
/**
|
|
282
|
-
*
|
|
283
|
-
* Returns the value accessed via `pathPart` in the `currentPathObject`
|
|
284
|
-
* and a setter function to set the value in the `currentPathObject` via the
|
|
285
|
-
* provided `pathPart`.
|
|
286
|
-
*
|
|
287
|
-
* @param pathPart - the path part to get the setter and getter for
|
|
288
|
-
* @param currentPathObject - the object at the current path (before the path part)
|
|
289
|
-
* @param arraysWithOrder - a set of arrays that have an order
|
|
290
|
-
* @returns the setter and getter for the path part
|
|
291
|
-
*
|
|
292
|
-
* @example
|
|
293
|
-
* ```ts
|
|
294
|
-
* const pathPart = {path: 'a', type: 'object', default: {}, pathToPart: 'a'}
|
|
295
|
-
* const currentPathObject = {}
|
|
296
|
-
* const arraysWithOrder = new Set()
|
|
297
|
-
* const [value, setValue] = getSetterAndGetter(pathPart, currentPathObject, arraysWithOrder)
|
|
298
|
-
* setValue('b')
|
|
299
|
-
* // => currentPathObject = {a: 'b'}
|
|
300
|
-
* ```
|
|
301
|
-
*
|
|
302
|
-
* @example
|
|
303
|
-
* ```ts
|
|
304
|
-
* const pathPart = {path: '0', type: 'array', default: [], pathToPart: 'a[0]'}
|
|
305
|
-
* const currentPathObject = {a: []}
|
|
306
|
-
* const arraysWithOrder = new Set()
|
|
307
|
-
* const [value, setValue] = getSetterAndGetter(pathPart, currentPathObject, arraysWithOrder)
|
|
308
|
-
* setValue('b')
|
|
309
|
-
* // => currentPathObject = {a: ['b']}
|
|
310
|
-
* ```
|
|
311
|
-
*
|
|
312
|
-
*/
|
|
313
|
-
function handlePathPart(pathPart, currentPathObject, arraysWithOrder) {
|
|
314
|
-
if (FORBIDDEN_OBJECT_KEYS.has(pathPart.path)) {
|
|
315
|
-
throw new ForbiddenKeyError(pathPart.pathToPart);
|
|
316
|
-
}
|
|
317
|
-
if (pathPart.type === 'object') {
|
|
318
|
-
if (Array.isArray(currentPathObject)) {
|
|
319
|
-
throw new DuplicateKeyError(pathPart.pathToPart);
|
|
320
|
-
}
|
|
321
|
-
const currentObject = currentPathObject;
|
|
322
|
-
return [currentObject[pathPart.path], val => currentObject[pathPart.path] = val];
|
|
323
|
-
}
|
|
324
|
-
if (!Array.isArray(currentPathObject)) {
|
|
325
|
-
throw new DuplicateKeyError(pathPart.pathToPart);
|
|
326
|
-
}
|
|
327
|
-
const currentArray = currentPathObject;
|
|
328
|
-
const isOrdered = pathPart.path !== '';
|
|
329
|
-
const isOrderedArray = arraysWithOrder.has(currentArray);
|
|
330
|
-
if (isOrdered) {
|
|
331
|
-
arraysWithOrder.add(currentArray);
|
|
332
|
-
}
|
|
333
|
-
if (!isOrdered && isOrderedArray || isOrdered && !isOrderedArray && currentArray.length > 0) {
|
|
334
|
-
throw new MixedArrayError(pathPart.pathToPart);
|
|
335
|
-
}
|
|
336
|
-
const order = isOrdered ? Number(pathPart.path) : currentArray.length;
|
|
337
|
-
return [currentArray[order], val => currentArray[order] = val];
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
/**
|
|
341
|
-
*
|
|
342
|
-
* Parses a FormData object to a JSON object. This is done by parsing the `name`
|
|
343
|
-
* attribute of each `FormDataEntryValue` and then inserting the value at the
|
|
344
|
-
* path. Also by default the start of the path is used to transform the value.
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
* In front of the whole `key`:
|
|
348
|
-
* - `+` => parse to `Number`
|
|
349
|
-
* - `-` => set value to `null`
|
|
350
|
-
* - `&` => parse to `Boolean`
|
|
351
|
-
*
|
|
352
|
-
* - `.` between path parts => nest into `objects`
|
|
353
|
-
* - `[\d*]` after path part => push to array in order `\d` or push to end if `[]`
|
|
354
|
-
*
|
|
355
|
-
|
|
356
|
-
*
|
|
357
|
-
* @example
|
|
358
|
-
* ```ts
|
|
359
|
-
* const formData = new FormData()
|
|
360
|
-
* formData.append('+a', '1')
|
|
361
|
-
* formData.append('&b', 'true')
|
|
362
|
-
* formData.append('-c', 'null')
|
|
363
|
-
* formData.append('d', 'foo')
|
|
364
|
-
* parseFormData(formData, defaultTransform)
|
|
365
|
-
* // => {a: 1, b: true, c: null, d: 'foo'}
|
|
366
|
-
* ```
|
|
367
|
-
*
|
|
368
|
-
* @example
|
|
369
|
-
* ```ts
|
|
370
|
-
* const formData = new FormData()
|
|
371
|
-
* formData.append('a.b', 'foo')
|
|
372
|
-
* parseFormData(formData)
|
|
373
|
-
* // => {a: {b: 'foo'}}
|
|
374
|
-
* ```
|
|
375
|
-
*
|
|
376
|
-
* @example
|
|
377
|
-
* ```ts
|
|
378
|
-
* const formData = new FormData()
|
|
379
|
-
* formData.append('a[0]', 'foo')
|
|
380
|
-
* formData.append('a[1]', 'bar')
|
|
381
|
-
* parseFormData(formData)
|
|
382
|
-
* // => {a: ['foo', 'bar']}
|
|
383
|
-
* ```
|
|
384
|
-
*
|
|
385
|
-
* @example
|
|
386
|
-
* ```ts
|
|
387
|
-
* const formData = new FormData()
|
|
388
|
-
* formData.append('a[]', 'foo')
|
|
389
|
-
* formData.append('a[]', 'bar')
|
|
390
|
-
* parseFormData(formData)
|
|
391
|
-
* // => {a: ['foo', 'bar']}
|
|
392
|
-
* ```
|
|
393
|
-
*
|
|
394
|
-
* @example
|
|
395
|
-
* ```ts
|
|
396
|
-
* const formData = new FormData()
|
|
397
|
-
* formData.append('a[0]', 'foo')
|
|
398
|
-
* parseFormData(formData, {transformEntry: (path, value) => {path, value: value + 'bar'}})
|
|
399
|
-
* // => {a: ['foobar']}
|
|
400
|
-
* ```
|
|
401
|
-
*
|
|
402
|
-
* @example
|
|
403
|
-
* ```ts
|
|
404
|
-
* const formData = new FormData()
|
|
405
|
-
* formData.append('a[0]', 'foo')
|
|
406
|
-
* formData.append('a[1]', '')
|
|
407
|
-
* parseFormData(formData, {removeEmptyString: true})
|
|
408
|
-
* // => {a: ['foo']}
|
|
409
|
-
* ```
|
|
410
|
-
*
|
|
411
|
-
* @param {Iterable<[string, string | File]>} formData - an iterator of an [`path`, `value`] tuple
|
|
412
|
-
* - `path` := `^(\+|\-|\&)?([^\.]+?(\[\d*\])*)(\.[^\.]+?(\[\d*\])*)*$` (e.g. `+a[][1].b`)
|
|
413
|
-
* - `value` := `string` or `File`
|
|
414
|
-
* @param {ParseFormDataOptions} options - options for parsing the form data
|
|
415
|
-
* - `transformEntry` - a function to transform the path and the value before
|
|
416
|
-
* inserting the value at the path in the resulting object (default: `defaultTransform`)
|
|
417
|
-
* - `removeEmptyString` - if `true` removes all entries where the value is an empty string
|
|
418
|
-
* @returns {JsonObject} the parsed JSON object
|
|
419
|
-
* @throws `DuplicateKeyError` if
|
|
420
|
-
* - a path part is an object and the path part is already defined as an object
|
|
421
|
-
* - a path part is an array and the path part is already defined as an array
|
|
422
|
-
* @throws `MixedArrayError` if at a specific path part an unordered array is
|
|
423
|
-
* defined and at a later path part an ordered array is defined or vice versa
|
|
424
|
-
* - e.g. `a[0]` and `a[]`
|
|
425
|
-
* - e.g. `a[]` and `a[0]`
|
|
426
|
-
*/
|
|
427
|
-
function parseFormData(formData, {
|
|
428
|
-
removeEmptyString = false,
|
|
429
|
-
transformEntry = defaultTransform
|
|
430
|
-
} = {}) {
|
|
431
|
-
const result = {};
|
|
432
|
-
|
|
433
|
-
// all arrays we need to squash (in place) later
|
|
434
|
-
const arraysWithOrder = new Set();
|
|
435
|
-
for (const entry of Array.from(formData)) {
|
|
436
|
-
if (removeEmptyString && entry[1] === '') continue;
|
|
437
|
-
const {
|
|
438
|
-
path,
|
|
439
|
-
value
|
|
440
|
-
} = transformEntry(entry, defaultTransform);
|
|
441
|
-
const pathParts = extractPathParts(path);
|
|
442
|
-
let currentPathObject = result;
|
|
443
|
-
pathParts.forEach((pathPart, idx) => {
|
|
444
|
-
const [nextPathValue, setNextPathValue] = handlePathPart(pathPart, currentPathObject, arraysWithOrder);
|
|
445
|
-
if (pathParts.length - 1 === idx) {
|
|
446
|
-
if (nextPathValue !== undefined) {
|
|
447
|
-
throw new DuplicateKeyError(pathPart.pathToPart);
|
|
448
|
-
}
|
|
449
|
-
setNextPathValue(value);
|
|
450
|
-
} else {
|
|
451
|
-
if (nextPathValue !== undefined && !isJsonObject(nextPathValue) && !Array.isArray(nextPathValue)) {
|
|
452
|
-
throw new DuplicateKeyError(pathPart.pathToPart);
|
|
453
|
-
}
|
|
454
|
-
const nextPathObject = nextPathValue ?? pathPart.default;
|
|
455
|
-
currentPathObject = nextPathObject;
|
|
456
|
-
setNextPathValue(nextPathObject);
|
|
457
|
-
}
|
|
458
|
-
});
|
|
459
|
-
}
|
|
460
|
-
for (const orderedArray of Array.from(arraysWithOrder)) {
|
|
461
|
-
// replace array with a squashed array
|
|
462
|
-
// array.flat(0) will remove all empty slots (e.g. [0, , 1] => [0, 1])
|
|
463
|
-
orderedArray.splice(0, orderedArray.length, ...orderedArray.flat(0));
|
|
464
|
-
}
|
|
465
|
-
return result;
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
exports.DuplicateKeyError = DuplicateKeyError;
|
|
469
|
-
exports.ForbiddenKeyError = ForbiddenKeyError;
|
|
470
|
-
exports.MixedArrayError = MixedArrayError;
|
|
471
|
-
exports.parseFormData = parseFormData;
|
|
472
|
-
|
|
473
|
-
Object.defineProperty(exports, '__esModule', { value: true });
|
|
474
|
-
|
|
475
|
-
}));
|
|
476
|
-
//# sourceMappingURL=parse-nested-form-data.umd.js.map
|
|
608
|
+
//# sourceMappingURL=parse-nested-form-data.umd.js.map
|