index.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. var randomBytes = require('randombytes');
  8. // Generate an internal UID to make the regexp pattern harder to guess.
  9. var UID_LENGTH = 16;
  10. var UID = generateUID();
  11. var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B)-' + UID + '-(\\d+)__@"', 'g');
  12. var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g;
  13. var IS_PURE_FUNCTION = /function.*?\(/;
  14. var IS_ARROW_FUNCTION = /.*?=>.*?/;
  15. var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g;
  16. var RESERVED_SYMBOLS = ['*', 'async'];
  17. // Mapping of unsafe HTML and invalid JavaScript line terminator chars to their
  18. // Unicode char counterparts which are safe to use in JavaScript strings.
  19. var ESCAPED_CHARS = {
  20. '<' : '\\u003C',
  21. '>' : '\\u003E',
  22. '/' : '\\u002F',
  23. '\u2028': '\\u2028',
  24. '\u2029': '\\u2029'
  25. };
  26. function escapeUnsafeChars(unsafeChar) {
  27. return ESCAPED_CHARS[unsafeChar];
  28. }
  29. function generateUID() {
  30. var bytes = randomBytes(UID_LENGTH);
  31. var result = '';
  32. for(var i=0; i<UID_LENGTH; ++i) {
  33. result += bytes[i].toString(16);
  34. }
  35. return result;
  36. }
  37. function deleteFunctions(obj){
  38. var functionKeys = [];
  39. for (var key in obj) {
  40. if (typeof obj[key] === "function") {
  41. functionKeys.push(key);
  42. }
  43. }
  44. for (var i = 0; i < functionKeys.length; i++) {
  45. delete obj[functionKeys[i]];
  46. }
  47. }
  48. module.exports = function serialize(obj, options) {
  49. options || (options = {});
  50. // Backwards-compatibility for `space` as the second argument.
  51. if (typeof options === 'number' || typeof options === 'string') {
  52. options = {space: options};
  53. }
  54. var functions = [];
  55. var regexps = [];
  56. var dates = [];
  57. var maps = [];
  58. var sets = [];
  59. var arrays = [];
  60. var undefs = [];
  61. var infinities= [];
  62. var bigInts = [];
  63. // Returns placeholders for functions and regexps (identified by index)
  64. // which are later replaced by their string representation.
  65. function replacer(key, value) {
  66. // For nested function
  67. if(options.ignoreFunction){
  68. deleteFunctions(value);
  69. }
  70. if (!value && value !== undefined) {
  71. return value;
  72. }
  73. // If the value is an object w/ a toJSON method, toJSON is called before
  74. // the replacer runs, so we use this[key] to get the non-toJSONed value.
  75. var origValue = this[key];
  76. var type = typeof origValue;
  77. if (type === 'object') {
  78. if(origValue instanceof RegExp) {
  79. return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@';
  80. }
  81. if(origValue instanceof Date) {
  82. return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@';
  83. }
  84. if(origValue instanceof Map) {
  85. return '@__M-' + UID + '-' + (maps.push(origValue) - 1) + '__@';
  86. }
  87. if(origValue instanceof Set) {
  88. return '@__S-' + UID + '-' + (sets.push(origValue) - 1) + '__@';
  89. }
  90. if(origValue instanceof Array) {
  91. var isSparse = origValue.filter(function(){return true}).length !== origValue.length;
  92. if (isSparse) {
  93. return '@__A-' + UID + '-' + (arrays.push(origValue) - 1) + '__@';
  94. }
  95. }
  96. }
  97. if (type === 'function') {
  98. return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@';
  99. }
  100. if (type === 'undefined') {
  101. return '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@';
  102. }
  103. if (type === 'number' && !isNaN(origValue) && !isFinite(origValue)) {
  104. return '@__I-' + UID + '-' + (infinities.push(origValue) - 1) + '__@';
  105. }
  106. if (type === 'bigint') {
  107. return '@__B-' + UID + '-' + (bigInts.push(origValue) - 1) + '__@';
  108. }
  109. return value;
  110. }
  111. function serializeFunc(fn) {
  112. var serializedFn = fn.toString();
  113. if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) {
  114. throw new TypeError('Serializing native function: ' + fn.name);
  115. }
  116. // pure functions, example: {key: function() {}}
  117. if(IS_PURE_FUNCTION.test(serializedFn)) {
  118. return serializedFn;
  119. }
  120. // arrow functions, example: arg1 => arg1+5
  121. if(IS_ARROW_FUNCTION.test(serializedFn)) {
  122. return serializedFn;
  123. }
  124. var argsStartsAt = serializedFn.indexOf('(');
  125. var def = serializedFn.substr(0, argsStartsAt)
  126. .trim()
  127. .split(' ')
  128. .filter(function(val) { return val.length > 0 });
  129. var nonReservedSymbols = def.filter(function(val) {
  130. return RESERVED_SYMBOLS.indexOf(val) === -1
  131. });
  132. // enhanced literal objects, example: {key() {}}
  133. if(nonReservedSymbols.length > 0) {
  134. return (def.indexOf('async') > -1 ? 'async ' : '') + 'function'
  135. + (def.join('').indexOf('*') > -1 ? '*' : '')
  136. + serializedFn.substr(argsStartsAt);
  137. }
  138. // arrow functions
  139. return serializedFn;
  140. }
  141. // Check if the parameter is function
  142. if (options.ignoreFunction && typeof obj === "function") {
  143. obj = undefined;
  144. }
  145. // Protects against `JSON.stringify()` returning `undefined`, by serializing
  146. // to the literal string: "undefined".
  147. if (obj === undefined) {
  148. return String(obj);
  149. }
  150. var str;
  151. // Creates a JSON string representation of the value.
  152. // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args.
  153. if (options.isJSON && !options.space) {
  154. str = JSON.stringify(obj);
  155. } else {
  156. str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
  157. }
  158. // Protects against `JSON.stringify()` returning `undefined`, by serializing
  159. // to the literal string: "undefined".
  160. if (typeof str !== 'string') {
  161. return String(str);
  162. }
  163. // Replace unsafe HTML and invalid JavaScript line terminator chars with
  164. // their safe Unicode char counterpart. This _must_ happen before the
  165. // regexps and functions are serialized and added back to the string.
  166. if (options.unsafe !== true) {
  167. str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
  168. }
  169. if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && arrays.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0) {
  170. return str;
  171. }
  172. // Replaces all occurrences of function, regexp, date, map and set placeholders in the
  173. // JSON string with their string representations. If the original value can
  174. // not be found, then `undefined` is used.
  175. return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) {
  176. // The placeholder may not be preceded by a backslash. This is to prevent
  177. // replacing things like `"a\"@__R-<UID>-0__@"` and thus outputting
  178. // invalid JS.
  179. if (backSlash) {
  180. return match;
  181. }
  182. if (type === 'D') {
  183. return "new Date(\"" + dates[valueIndex].toISOString() + "\")";
  184. }
  185. if (type === 'R') {
  186. return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")";
  187. }
  188. if (type === 'M') {
  189. return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")";
  190. }
  191. if (type === 'S') {
  192. return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")";
  193. }
  194. if (type === 'A') {
  195. return "Array.prototype.slice.call(" + serialize(Object.assign({ length: arrays[valueIndex].length }, arrays[valueIndex]), options) + ")";
  196. }
  197. if (type === 'U') {
  198. return 'undefined'
  199. }
  200. if (type === 'I') {
  201. return infinities[valueIndex];
  202. }
  203. if (type === 'B') {
  204. return "BigInt(\"" + bigInts[valueIndex] + "\")";
  205. }
  206. var fn = functions[valueIndex];
  207. return serializeFunc(fn);
  208. });
  209. }