index.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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|L)-' + 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. var urls = [];
  64. // Returns placeholders for functions and regexps (identified by index)
  65. // which are later replaced by their string representation.
  66. function replacer(key, value) {
  67. // For nested function
  68. if(options.ignoreFunction){
  69. deleteFunctions(value);
  70. }
  71. if (!value && value !== undefined && value !== BigInt(0)) {
  72. return value;
  73. }
  74. // If the value is an object w/ a toJSON method, toJSON is called before
  75. // the replacer runs, so we use this[key] to get the non-toJSONed value.
  76. var origValue = this[key];
  77. var type = typeof origValue;
  78. if (type === 'object') {
  79. if(origValue instanceof RegExp) {
  80. return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@';
  81. }
  82. if(origValue instanceof Date) {
  83. return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@';
  84. }
  85. if(origValue instanceof Map) {
  86. return '@__M-' + UID + '-' + (maps.push(origValue) - 1) + '__@';
  87. }
  88. if(origValue instanceof Set) {
  89. return '@__S-' + UID + '-' + (sets.push(origValue) - 1) + '__@';
  90. }
  91. if(origValue instanceof Array) {
  92. var isSparse = origValue.filter(function(){return true}).length !== origValue.length;
  93. if (isSparse) {
  94. return '@__A-' + UID + '-' + (arrays.push(origValue) - 1) + '__@';
  95. }
  96. }
  97. if(origValue instanceof URL) {
  98. return '@__L-' + UID + '-' + (urls.push(origValue) - 1) + '__@';
  99. }
  100. }
  101. if (type === 'function') {
  102. return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@';
  103. }
  104. if (type === 'undefined') {
  105. return '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@';
  106. }
  107. if (type === 'number' && !isNaN(origValue) && !isFinite(origValue)) {
  108. return '@__I-' + UID + '-' + (infinities.push(origValue) - 1) + '__@';
  109. }
  110. if (type === 'bigint') {
  111. return '@__B-' + UID + '-' + (bigInts.push(origValue) - 1) + '__@';
  112. }
  113. return value;
  114. }
  115. function serializeFunc(fn) {
  116. var serializedFn = fn.toString();
  117. if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) {
  118. throw new TypeError('Serializing native function: ' + fn.name);
  119. }
  120. // pure functions, example: {key: function() {}}
  121. if(IS_PURE_FUNCTION.test(serializedFn)) {
  122. return serializedFn;
  123. }
  124. // arrow functions, example: arg1 => arg1+5
  125. if(IS_ARROW_FUNCTION.test(serializedFn)) {
  126. return serializedFn;
  127. }
  128. var argsStartsAt = serializedFn.indexOf('(');
  129. var def = serializedFn.substr(0, argsStartsAt)
  130. .trim()
  131. .split(' ')
  132. .filter(function(val) { return val.length > 0 });
  133. var nonReservedSymbols = def.filter(function(val) {
  134. return RESERVED_SYMBOLS.indexOf(val) === -1
  135. });
  136. // enhanced literal objects, example: {key() {}}
  137. if(nonReservedSymbols.length > 0) {
  138. return (def.indexOf('async') > -1 ? 'async ' : '') + 'function'
  139. + (def.join('').indexOf('*') > -1 ? '*' : '')
  140. + serializedFn.substr(argsStartsAt);
  141. }
  142. // arrow functions
  143. return serializedFn;
  144. }
  145. // Check if the parameter is function
  146. if (options.ignoreFunction && typeof obj === "function") {
  147. obj = undefined;
  148. }
  149. // Protects against `JSON.stringify()` returning `undefined`, by serializing
  150. // to the literal string: "undefined".
  151. if (obj === undefined) {
  152. return String(obj);
  153. }
  154. var str;
  155. // Creates a JSON string representation of the value.
  156. // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args.
  157. if (options.isJSON && !options.space) {
  158. str = JSON.stringify(obj);
  159. } else {
  160. str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
  161. }
  162. // Protects against `JSON.stringify()` returning `undefined`, by serializing
  163. // to the literal string: "undefined".
  164. if (typeof str !== 'string') {
  165. return String(str);
  166. }
  167. // Replace unsafe HTML and invalid JavaScript line terminator chars with
  168. // their safe Unicode char counterpart. This _must_ happen before the
  169. // regexps and functions are serialized and added back to the string.
  170. if (options.unsafe !== true) {
  171. str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
  172. }
  173. 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 && urls.length === 0) {
  174. return str;
  175. }
  176. // Replaces all occurrences of function, regexp, date, map and set placeholders in the
  177. // JSON string with their string representations. If the original value can
  178. // not be found, then `undefined` is used.
  179. return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) {
  180. // The placeholder may not be preceded by a backslash. This is to prevent
  181. // replacing things like `"a\"@__R-<UID>-0__@"` and thus outputting
  182. // invalid JS.
  183. if (backSlash) {
  184. return match;
  185. }
  186. if (type === 'D') {
  187. return "new Date(\"" + dates[valueIndex].toISOString() + "\")";
  188. }
  189. if (type === 'R') {
  190. return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")";
  191. }
  192. if (type === 'M') {
  193. return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")";
  194. }
  195. if (type === 'S') {
  196. return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")";
  197. }
  198. if (type === 'A') {
  199. return "Array.prototype.slice.call(" + serialize(Object.assign({ length: arrays[valueIndex].length }, arrays[valueIndex]), options) + ")";
  200. }
  201. if (type === 'U') {
  202. return 'undefined'
  203. }
  204. if (type === 'I') {
  205. return infinities[valueIndex];
  206. }
  207. if (type === 'B') {
  208. return "BigInt(\"" + bigInts[valueIndex] + "\")";
  209. }
  210. if (type === 'L') {
  211. return "new URL(" + serialize(urls[valueIndex].toString(), options) + ")";
  212. }
  213. var fn = functions[valueIndex];
  214. return serializeFunc(fn);
  215. });
  216. }