You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /*
  2. Copyright (c) 2014, Yahoo! Inc. All rights reserved.
  3. Copyrights licensed under the New BSD License.
  4. See the accompanying LICENSE file for terms.
  5. */
  6. 'use strict';
  7. // Generate an internal UID to make the regexp pattern harder to guess.
  8. var UID = Math.floor(Math.random() * 0x10000000000).toString(16);
  9. var PLACE_HOLDER_REGEXP = new RegExp('"@__(F|R|D|M|S)-' + UID + '-(\\d+)__@"', 'g');
  10. var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g;
  11. var IS_PURE_FUNCTION = /function.*?\(/;
  12. var IS_ARROW_FUNCTION = /.*?=>.*?/;
  13. var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g;
  14. var RESERVED_SYMBOLS = ['*', 'async'];
  15. // Mapping of unsafe HTML and invalid JavaScript line terminator chars to their
  16. // Unicode char counterparts which are safe to use in JavaScript strings.
  17. var ESCAPED_CHARS = {
  18. '<' : '\\u003C',
  19. '>' : '\\u003E',
  20. '/' : '\\u002F',
  21. '\u2028': '\\u2028',
  22. '\u2029': '\\u2029'
  23. };
  24. function escapeUnsafeChars(unsafeChar) {
  25. return ESCAPED_CHARS[unsafeChar];
  26. }
  27. module.exports = function serialize(obj, options) {
  28. options || (options = {});
  29. // Backwards-compatibility for `space` as the second argument.
  30. if (typeof options === 'number' || typeof options === 'string') {
  31. options = {space: options};
  32. }
  33. var functions = [];
  34. var regexps = [];
  35. var dates = [];
  36. var maps = [];
  37. var sets = [];
  38. // Returns placeholders for functions and regexps (identified by index)
  39. // which are later replaced by their string representation.
  40. function replacer(key, value) {
  41. if (!value) {
  42. return value;
  43. }
  44. // If the value is an object w/ a toJSON method, toJSON is called before
  45. // the replacer runs, so we use this[key] to get the non-toJSONed value.
  46. var origValue = this[key];
  47. var type = typeof origValue;
  48. if (type === 'object') {
  49. if(origValue instanceof RegExp) {
  50. return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@';
  51. }
  52. if(origValue instanceof Date) {
  53. return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@';
  54. }
  55. if(origValue instanceof Map) {
  56. return '@__M-' + UID + '-' + (maps.push(origValue) - 1) + '__@';
  57. }
  58. if(origValue instanceof Set) {
  59. return '@__S-' + UID + '-' + (sets.push(origValue) - 1) + '__@';
  60. }
  61. }
  62. if (type === 'function') {
  63. return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@';
  64. }
  65. return value;
  66. }
  67. function serializeFunc(fn) {
  68. var serializedFn = fn.toString();
  69. if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) {
  70. throw new TypeError('Serializing native function: ' + fn.name);
  71. }
  72. // pure functions, example: {key: function() {}}
  73. if(IS_PURE_FUNCTION.test(serializedFn)) {
  74. return serializedFn;
  75. }
  76. // arrow functions, example: arg1 => arg1+5
  77. if(IS_ARROW_FUNCTION.test(serializedFn)) {
  78. return serializedFn;
  79. }
  80. var argsStartsAt = serializedFn.indexOf('(');
  81. var def = serializedFn.substr(0, argsStartsAt)
  82. .trim()
  83. .split(' ')
  84. .filter(function(val) { return val.length > 0 });
  85. var nonReservedSymbols = def.filter(function(val) {
  86. return RESERVED_SYMBOLS.indexOf(val) === -1
  87. });
  88. // enhanced literal objects, example: {key() {}}
  89. if(nonReservedSymbols.length > 0) {
  90. return (def.indexOf('async') > -1 ? 'async ' : '') + 'function'
  91. + (def.join('').indexOf('*') > -1 ? '*' : '')
  92. + serializedFn.substr(argsStartsAt);
  93. }
  94. // arrow functions
  95. return serializedFn;
  96. }
  97. var str;
  98. // Creates a JSON string representation of the value.
  99. // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args.
  100. if (options.isJSON && !options.space) {
  101. str = JSON.stringify(obj);
  102. } else {
  103. str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
  104. }
  105. // Protects against `JSON.stringify()` returning `undefined`, by serializing
  106. // to the literal string: "undefined".
  107. if (typeof str !== 'string') {
  108. return String(str);
  109. }
  110. // Replace unsafe HTML and invalid JavaScript line terminator chars with
  111. // their safe Unicode char counterpart. This _must_ happen before the
  112. // regexps and functions are serialized and added back to the string.
  113. if (options.unsafe !== true) {
  114. str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
  115. }
  116. if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0) {
  117. return str;
  118. }
  119. // Replaces all occurrences of function, regexp, date, map and set placeholders in the
  120. // JSON string with their string representations. If the original value can
  121. // not be found, then `undefined` is used.
  122. return str.replace(PLACE_HOLDER_REGEXP, function (match, type, valueIndex) {
  123. if (type === 'D') {
  124. return "new Date(\"" + dates[valueIndex].toISOString() + "\")";
  125. }
  126. if (type === 'R') {
  127. return regexps[valueIndex].toString();
  128. }
  129. if (type === 'M') {
  130. return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")";
  131. }
  132. if (type === 'S') {
  133. return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")";
  134. }
  135. var fn = functions[valueIndex];
  136. return serializeFunc(fn);
  137. });
  138. }