UNPKG

9.35 kBJavaScriptView Raw
1'use strict';
2
3var utils = require('./utils');
4
5var has = Object.prototype.hasOwnProperty;
6var isArray = Array.isArray;
7
8var defaults = {
9 allowDots: false,
10 allowPrototypes: false,
11 allowSparse: false,
12 arrayLimit: 20,
13 charset: 'utf-8',
14 charsetSentinel: false,
15 comma: false,
16 decoder: utils.decode,
17 delimiter: '&',
18 depth: 5,
19 ignoreQueryPrefix: false,
20 interpretNumericEntities: false,
21 parameterLimit: 1000,
22 parseArrays: true,
23 plainObjects: false,
24 strictNullHandling: false
25};
26
27var interpretNumericEntities = function (str) {
28 return str.replace(/&#(\d+);/g, function ($0, numberStr) {
29 return String.fromCharCode(parseInt(numberStr, 10));
30 });
31};
32
33var parseArrayValue = function (val, options) {
34 if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
35 return val.split(',');
36 }
37
38 return val;
39};
40
41// This is what browsers will submit when the ✓ character occurs in an
42// application/x-www-form-urlencoded body and the encoding of the page containing
43// the form is iso-8859-1, or when the submitted form has an accept-charset
44// attribute of iso-8859-1. Presumably also with other charsets that do not contain
45// the ✓ character, such as us-ascii.
46var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓')
47
48// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
49var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
50
51var parseValues = function parseQueryStringValues(str, options) {
52 var obj = {};
53 var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
54 var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
55 var parts = cleanStr.split(options.delimiter, limit);
56 var skipIndex = -1; // Keep track of where the utf8 sentinel was found
57 var i;
58
59 var charset = options.charset;
60 if (options.charsetSentinel) {
61 for (i = 0; i < parts.length; ++i) {
62 if (parts[i].indexOf('utf8=') === 0) {
63 if (parts[i] === charsetSentinel) {
64 charset = 'utf-8';
65 } else if (parts[i] === isoSentinel) {
66 charset = 'iso-8859-1';
67 }
68 skipIndex = i;
69 i = parts.length; // The eslint settings do not allow break;
70 }
71 }
72 }
73
74 for (i = 0; i < parts.length; ++i) {
75 if (i === skipIndex) {
76 continue;
77 }
78 var part = parts[i];
79
80 var bracketEqualsPos = part.indexOf(']=');
81 var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
82
83 var key, val;
84 if (pos === -1) {
85 key = options.decoder(part, defaults.decoder, charset, 'key');
86 val = options.strictNullHandling ? null : '';
87 } else {
88 key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');
89 val = utils.maybeMap(
90 parseArrayValue(part.slice(pos + 1), options),
91 function (encodedVal) {
92 return options.decoder(encodedVal, defaults.decoder, charset, 'value');
93 }
94 );
95 }
96
97 if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
98 val = interpretNumericEntities(val);
99 }
100
101 if (part.indexOf('[]=') > -1) {
102 val = isArray(val) ? [val] : val;
103 }
104
105 if (has.call(obj, key)) {
106 obj[key] = utils.combine(obj[key], val);
107 } else {
108 obj[key] = val;
109 }
110 }
111
112 return obj;
113};
114
115var parseObject = function (chain, val, options, valuesParsed) {
116 var leaf = valuesParsed ? val : parseArrayValue(val, options);
117
118 for (var i = chain.length - 1; i >= 0; --i) {
119 var obj;
120 var root = chain[i];
121
122 if (root === '[]' && options.parseArrays) {
123 obj = [].concat(leaf);
124 } else {
125 obj = options.plainObjects ? Object.create(null) : {};
126 var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
127 var index = parseInt(cleanRoot, 10);
128 if (!options.parseArrays && cleanRoot === '') {
129 obj = { 0: leaf };
130 } else if (
131 !isNaN(index)
132 && root !== cleanRoot
133 && String(index) === cleanRoot
134 && index >= 0
135 && (options.parseArrays && index <= options.arrayLimit)
136 ) {
137 obj = [];
138 obj[index] = leaf;
139 } else {
140 obj[cleanRoot] = leaf;
141 }
142 }
143
144 leaf = obj;
145 }
146
147 return leaf;
148};
149
150var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
151 if (!givenKey) {
152 return;
153 }
154
155 // Transform dot notation to bracket notation
156 var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
157
158 // The regex chunks
159
160 var brackets = /(\[[^[\]]*])/;
161 var child = /(\[[^[\]]*])/g;
162
163 // Get the parent
164
165 var segment = options.depth > 0 && brackets.exec(key);
166 var parent = segment ? key.slice(0, segment.index) : key;
167
168 // Stash the parent if it exists
169
170 var keys = [];
171 if (parent) {
172 // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
173 if (!options.plainObjects && has.call(Object.prototype, parent)) {
174 if (!options.allowPrototypes) {
175 return;
176 }
177 }
178
179 keys.push(parent);
180 }
181
182 // Loop through children appending to the array until we hit depth
183
184 var i = 0;
185 while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
186 i += 1;
187 if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
188 if (!options.allowPrototypes) {
189 return;
190 }
191 }
192 keys.push(segment[1]);
193 }
194
195 // If there's a remainder, just add whatever is left
196
197 if (segment) {
198 keys.push('[' + key.slice(segment.index) + ']');
199 }
200
201 return parseObject(keys, val, options, valuesParsed);
202};
203
204var normalizeParseOptions = function normalizeParseOptions(opts) {
205 if (!opts) {
206 return defaults;
207 }
208
209 if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
210 throw new TypeError('Decoder has to be a function.');
211 }
212
213 if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
214 throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
215 }
216 var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;
217
218 return {
219 allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
220 allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
221 allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,
222 arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
223 charset: charset,
224 charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
225 comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
226 decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
227 delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
228 // eslint-disable-next-line no-implicit-coercion, no-extra-parens
229 depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
230 ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
231 interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
232 parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
233 parseArrays: opts.parseArrays !== false,
234 plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
235 strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
236 };
237};
238
239module.exports = function (str, opts) {
240 var options = normalizeParseOptions(opts);
241
242 if (str === '' || str === null || typeof str === 'undefined') {
243 return options.plainObjects ? Object.create(null) : {};
244 }
245
246 var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
247 var obj = options.plainObjects ? Object.create(null) : {};
248
249 // Iterate over the keys and setup the new object
250
251 var keys = Object.keys(tempObj);
252 for (var i = 0; i < keys.length; ++i) {
253 var key = keys[i];
254 var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
255 obj = utils.merge(obj, newObj, options);
256 }
257
258 if (options.allowSparse === true) {
259 return obj;
260 }
261
262 return utils.compact(obj);
263};