index.js 7.6 KB

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