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.

210 lines
6.6 KiB

4 years ago
  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|U)-' + 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. function deleteFunctions(obj){
  28. var functionKeys = [];
  29. for (var key in obj) {
  30. if (typeof obj[key] === "function") {
  31. functionKeys.push(key);
  32. }
  33. }
  34. for (var i = 0; i < functionKeys.length; i++) {
  35. delete obj[functionKeys[i]];
  36. }
  37. }
  38. module.exports = function serialize(obj, options) {
  39. options || (options = {});
  40. // Backwards-compatibility for `space` as the second argument.
  41. if (typeof options === 'number' || typeof options === 'string') {
  42. options = {space: options};
  43. }
  44. var functions = [];
  45. var regexps = [];
  46. var dates = [];
  47. var maps = [];
  48. var sets = [];
  49. var undefs = [];
  50. // Returns placeholders for functions and regexps (identified by index)
  51. // which are later replaced by their string representation.
  52. function replacer(key, value) {
  53. // For nested function
  54. if(options.ignoreFunction){
  55. deleteFunctions(value);
  56. }
  57. if (!value && value !== undefined) {
  58. return value;
  59. }
  60. // If the value is an object w/ a toJSON method, toJSON is called before
  61. // the replacer runs, so we use this[key] to get the non-toJSONed value.
  62. var origValue = this[key];
  63. var type = typeof origValue;
  64. if (type === 'object') {
  65. if(origValue instanceof RegExp) {
  66. return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@';
  67. }
  68. if(origValue instanceof Date) {
  69. return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@';
  70. }
  71. if(origValue instanceof Map) {
  72. return '@__M-' + UID + '-' + (maps.push(origValue) - 1) + '__@';
  73. }
  74. if(origValue instanceof Set) {
  75. return '@__S-' + UID + '-' + (sets.push(origValue) - 1) + '__@';
  76. }
  77. }
  78. if (type === 'function') {
  79. return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@';
  80. }
  81. if (type === 'undefined') {
  82. return '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@';
  83. }
  84. return value;
  85. }
  86. function serializeFunc(fn) {
  87. var serializedFn = fn.toString();
  88. if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) {
  89. throw new TypeError('Serializing native function: ' + fn.name);
  90. }
  91. // pure functions, example: {key: function() {}}
  92. if(IS_PURE_FUNCTION.test(serializedFn)) {
  93. return serializedFn;
  94. }
  95. // arrow functions, example: arg1 => arg1+5
  96. if(IS_ARROW_FUNCTION.test(serializedFn)) {
  97. return serializedFn;
  98. }
  99. var argsStartsAt = serializedFn.indexOf('(');
  100. var def = serializedFn.substr(0, argsStartsAt)
  101. .trim()
  102. .split(' ')
  103. .filter(function(val) { return val.length > 0 });
  104. var nonReservedSymbols = def.filter(function(val) {
  105. return RESERVED_SYMBOLS.indexOf(val) === -1
  106. });
  107. // enhanced literal objects, example: {key() {}}
  108. if(nonReservedSymbols.length > 0) {
  109. return (def.indexOf('async') > -1 ? 'async ' : '') + 'function'
  110. + (def.join('').indexOf('*') > -1 ? '*' : '')
  111. + serializedFn.substr(argsStartsAt);
  112. }
  113. // arrow functions
  114. return serializedFn;
  115. }
  116. // Check if the parameter is function
  117. if (options.ignoreFunction && typeof obj === "function") {
  118. obj = undefined;
  119. }
  120. // Protects against `JSON.stringify()` returning `undefined`, by serializing
  121. // to the literal string: "undefined".
  122. if (obj === undefined) {
  123. return String(obj);
  124. }
  125. var str;
  126. // Creates a JSON string representation of the value.
  127. // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args.
  128. if (options.isJSON && !options.space) {
  129. str = JSON.stringify(obj);
  130. } else {
  131. str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
  132. }
  133. // Protects against `JSON.stringify()` returning `undefined`, by serializing
  134. // to the literal string: "undefined".
  135. if (typeof str !== 'string') {
  136. return String(str);
  137. }
  138. // Replace unsafe HTML and invalid JavaScript line terminator chars with
  139. // their safe Unicode char counterpart. This _must_ happen before the
  140. // regexps and functions are serialized and added back to the string.
  141. if (options.unsafe !== true) {
  142. str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
  143. }
  144. if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && undefs.length === 0) {
  145. return str;
  146. }
  147. // Replaces all occurrences of function, regexp, date, map and set placeholders in the
  148. // JSON string with their string representations. If the original value can
  149. // not be found, then `undefined` is used.
  150. return str.replace(PLACE_HOLDER_REGEXP, function (match, type, valueIndex) {
  151. if (type === 'D') {
  152. return "new Date(\"" + dates[valueIndex].toISOString() + "\")";
  153. }
  154. if (type === 'R') {
  155. return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")";
  156. }
  157. if (type === 'M') {
  158. return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")";
  159. }
  160. if (type === 'S') {
  161. return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")";
  162. }
  163. if (type === 'U') {
  164. return 'undefined'
  165. }
  166. var fn = functions[valueIndex];
  167. return serializeFunc(fn);
  168. });
  169. }