parse.js 14 KB

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