stringify.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. 'use strict';
  2. var getSideChannel = require('side-channel');
  3. var utils = require('./utils');
  4. var formats = require('./formats');
  5. var has = Object.prototype.hasOwnProperty;
  6. var arrayPrefixGenerators = {
  7. brackets: function brackets(prefix) {
  8. return prefix + '[]';
  9. },
  10. comma: 'comma',
  11. indices: function indices(prefix, key) {
  12. return prefix + '[' + key + ']';
  13. },
  14. repeat: function repeat(prefix) {
  15. return prefix;
  16. }
  17. };
  18. var isArray = Array.isArray;
  19. var push = Array.prototype.push;
  20. var pushToArray = function (arr, valueOrArray) {
  21. push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
  22. };
  23. var toISO = Date.prototype.toISOString;
  24. var defaultFormat = formats['default'];
  25. var defaults = {
  26. addQueryPrefix: false,
  27. allowDots: false,
  28. charset: 'utf-8',
  29. charsetSentinel: false,
  30. delimiter: '&',
  31. encode: true,
  32. encoder: utils.encode,
  33. encodeValuesOnly: false,
  34. format: defaultFormat,
  35. formatter: formats.formatters[defaultFormat],
  36. // deprecated
  37. indices: false,
  38. serializeDate: function serializeDate(date) {
  39. return toISO.call(date);
  40. },
  41. skipNulls: false,
  42. strictNullHandling: false
  43. };
  44. var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
  45. return typeof v === 'string'
  46. || typeof v === 'number'
  47. || typeof v === 'boolean'
  48. || typeof v === 'symbol'
  49. || typeof v === 'bigint';
  50. };
  51. var stringify = function stringify(
  52. object,
  53. prefix,
  54. generateArrayPrefix,
  55. strictNullHandling,
  56. skipNulls,
  57. encoder,
  58. filter,
  59. sort,
  60. allowDots,
  61. serializeDate,
  62. format,
  63. formatter,
  64. encodeValuesOnly,
  65. charset,
  66. sideChannel
  67. ) {
  68. var obj = object;
  69. if (sideChannel.has(object)) {
  70. throw new RangeError('Cyclic object value');
  71. }
  72. if (typeof filter === 'function') {
  73. obj = filter(prefix, obj);
  74. } else if (obj instanceof Date) {
  75. obj = serializeDate(obj);
  76. } else if (generateArrayPrefix === 'comma' && isArray(obj)) {
  77. obj = utils.maybeMap(obj, function (value) {
  78. if (value instanceof Date) {
  79. return serializeDate(value);
  80. }
  81. return value;
  82. });
  83. }
  84. if (obj === null) {
  85. if (strictNullHandling) {
  86. return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix;
  87. }
  88. obj = '';
  89. }
  90. if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
  91. if (encoder) {
  92. var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format);
  93. return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))];
  94. }
  95. return [formatter(prefix) + '=' + formatter(String(obj))];
  96. }
  97. var values = [];
  98. if (typeof obj === 'undefined') {
  99. return values;
  100. }
  101. var objKeys;
  102. if (generateArrayPrefix === 'comma' && isArray(obj)) {
  103. // we need to join elements in
  104. objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : undefined }];
  105. } else if (isArray(filter)) {
  106. objKeys = filter;
  107. } else {
  108. var keys = Object.keys(obj);
  109. objKeys = sort ? keys.sort(sort) : keys;
  110. }
  111. for (var i = 0; i < objKeys.length; ++i) {
  112. var key = objKeys[i];
  113. var value = typeof key === 'object' && key.value !== undefined ? key.value : obj[key];
  114. if (skipNulls && value === null) {
  115. continue;
  116. }
  117. var keyPrefix = isArray(obj)
  118. ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix
  119. : prefix + (allowDots ? '.' + key : '[' + key + ']');
  120. sideChannel.set(object, true);
  121. var valueSideChannel = getSideChannel();
  122. pushToArray(values, stringify(
  123. value,
  124. keyPrefix,
  125. generateArrayPrefix,
  126. strictNullHandling,
  127. skipNulls,
  128. encoder,
  129. filter,
  130. sort,
  131. allowDots,
  132. serializeDate,
  133. format,
  134. formatter,
  135. encodeValuesOnly,
  136. charset,
  137. valueSideChannel
  138. ));
  139. }
  140. return values;
  141. };
  142. var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
  143. if (!opts) {
  144. return defaults;
  145. }
  146. if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') {
  147. throw new TypeError('Encoder has to be a function.');
  148. }
  149. var charset = opts.charset || defaults.charset;
  150. if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
  151. throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
  152. }
  153. var format = formats['default'];
  154. if (typeof opts.format !== 'undefined') {
  155. if (!has.call(formats.formatters, opts.format)) {
  156. throw new TypeError('Unknown format option provided.');
  157. }
  158. format = opts.format;
  159. }
  160. var formatter = formats.formatters[format];
  161. var filter = defaults.filter;
  162. if (typeof opts.filter === 'function' || isArray(opts.filter)) {
  163. filter = opts.filter;
  164. }
  165. return {
  166. addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
  167. allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
  168. charset: charset,
  169. charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
  170. delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
  171. encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
  172. encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
  173. encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
  174. filter: filter,
  175. format: format,
  176. formatter: formatter,
  177. serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
  178. skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
  179. sort: typeof opts.sort === 'function' ? opts.sort : null,
  180. strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
  181. };
  182. };
  183. module.exports = function (object, opts) {
  184. var obj = object;
  185. var options = normalizeStringifyOptions(opts);
  186. var objKeys;
  187. var filter;
  188. if (typeof options.filter === 'function') {
  189. filter = options.filter;
  190. obj = filter('', obj);
  191. } else if (isArray(options.filter)) {
  192. filter = options.filter;
  193. objKeys = filter;
  194. }
  195. var keys = [];
  196. if (typeof obj !== 'object' || obj === null) {
  197. return '';
  198. }
  199. var arrayFormat;
  200. if (opts && opts.arrayFormat in arrayPrefixGenerators) {
  201. arrayFormat = opts.arrayFormat;
  202. } else if (opts && 'indices' in opts) {
  203. arrayFormat = opts.indices ? 'indices' : 'repeat';
  204. } else {
  205. arrayFormat = 'indices';
  206. }
  207. var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
  208. if (!objKeys) {
  209. objKeys = Object.keys(obj);
  210. }
  211. if (options.sort) {
  212. objKeys.sort(options.sort);
  213. }
  214. var sideChannel = getSideChannel();
  215. for (var i = 0; i < objKeys.length; ++i) {
  216. var key = objKeys[i];
  217. if (options.skipNulls && obj[key] === null) {
  218. continue;
  219. }
  220. pushToArray(keys, stringify(
  221. obj[key],
  222. key,
  223. generateArrayPrefix,
  224. options.strictNullHandling,
  225. options.skipNulls,
  226. options.encode ? options.encoder : null,
  227. options.filter,
  228. options.sort,
  229. options.allowDots,
  230. options.serializeDate,
  231. options.format,
  232. options.formatter,
  233. options.encodeValuesOnly,
  234. options.charset,
  235. sideChannel
  236. ));
  237. }
  238. var joined = keys.join(options.delimiter);
  239. var prefix = options.addQueryPrefix === true ? '?' : '';
  240. if (options.charsetSentinel) {
  241. if (options.charset === 'iso-8859-1') {
  242. // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark
  243. prefix += 'utf8=%26%2310003%3B&';
  244. } else {
  245. // encodeURIComponent('✓')
  246. prefix += 'utf8=%E2%9C%93&';
  247. }
  248. }
  249. return joined.length > 0 ? prefix + joined : '';
  250. };