parse.js 8.3 KB

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