parse.js 11 KB

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