index.js 5.4 KB

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