parse-nested-form-data
Version:
A tiny node module for parsing FormData by name into objects and arrays
9 lines (8 loc) • 2.25 kB
JavaScript
!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@remix-run/web-file")):"function"==typeof define&&define.amd?define(["exports","@remix-run/web-file"],r):r((t="undefined"!=typeof globalThis?globalThis:t||self).parseNestedFormData={},t.RemixRunWebFile)}(this,(function(t,r){"use strict";
/**
* @name parse-nested-form-data
* @license MIT license.
* @copyright (c) 2022 Christian Schurr
* @author Christian Schurr <chris@schurr.dev>
*/class e extends Error{constructor(t){super(`Duplicate key at path part ${t}`),this.key=void 0,this.key=t}}class a extends Error{constructor(t){super(`Mixed array at path part ${t}`),this.key=void 0,this.key=t}}function o(t){let r=t[0],e=t[1];return r.startsWith("+")?(r=r.slice(1),e=Number(e)):r.startsWith("&")?(r=r.slice(1),e="on"===e||"true"===e||Boolean(Number(e))):r.startsWith("-")&&(r=r.slice(1),e=null),{path:r,value:e}}function n(t){return Array.from(t.matchAll(/((?<array>\d*)\]|(?<pathPart>[^.[]+))(?<nextType>\[|\.|$)/g)).map((r=>{const e=r,{array:a,pathPart:o,nextType:n}=e.groups;return{path:a??o,type:void 0===a?"object":"array",default:"["===n?[]:{},pathToPart:t.slice(0,e.index+e[1].length)}}))}function i(t,r,o){if("object"===t.type){if(Array.isArray(r))throw new e(t.pathToPart);const a=r;return[a[t.path],r=>a[t.path]=r]}if(!Array.isArray(r))throw new e(t.pathToPart);const n=r,i=""!==t.path,s=o.has(n);if(i&&o.add(n),!i&&s||i&&!s&&n.length>0)throw new a(t.pathToPart);const f=i?Number(t.path):n.length;return[n[f],t=>n[f]=t]}t.DuplicateKeyError=e,t.MixedArrayError=a,t.parseFormData=function(t,a){let{removeEmptyString:s=!1,transformEntry:f=o}=void 0===a?{}:a;const l={},p=new Set;for(const a of Array.from(t)){if(s&&""===a[1])continue;const{path:t,value:u}=f(a,o),c=n(t);let h=l;c.forEach(((t,a)=>{const[o,n]=i(t,h,p);if(c.length-1===a){if(void 0!==o)throw new e(t.pathToPart);n(u)}else{if(void 0!==o&&("object"!=typeof(s=o)||Array.isArray(s)||null===s||s instanceof r.File)&&!Array.isArray(o))throw new e(t.pathToPart);const a=o??t.default;h=a,n(a)}var s}))}for(const t of Array.from(p))t.splice(0,t.length,...t.flat(0));return l},Object.defineProperty(t,"__esModule",{value:!0})}));
//# sourceMappingURL=parse-nested-form-data.umd.min.js.map