jsesc.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. 'use strict';
  2. const object = {};
  3. const hasOwnProperty = object.hasOwnProperty;
  4. const forOwn = (object, callback) => {
  5. for (const key in object) {
  6. if (hasOwnProperty.call(object, key)) {
  7. callback(key, object[key]);
  8. }
  9. }
  10. };
  11. const extend = (destination, source) => {
  12. if (!source) {
  13. return destination;
  14. }
  15. forOwn(source, (key, value) => {
  16. destination[key] = value;
  17. });
  18. return destination;
  19. };
  20. const forEach = (array, callback) => {
  21. const length = array.length;
  22. let index = -1;
  23. while (++index < length) {
  24. callback(array[index]);
  25. }
  26. };
  27. const fourHexEscape = (hex) => {
  28. return '\\u' + ('0000' + hex).slice(-4);
  29. }
  30. const hexadecimal = (code, lowercase) => {
  31. let hexadecimal = code.toString(16);
  32. if (lowercase) return hexadecimal;
  33. return hexadecimal.toUpperCase();
  34. };
  35. const toString = object.toString;
  36. const isArray = Array.isArray;
  37. const isBuffer = (value) => {
  38. return typeof Buffer === 'function' && Buffer.isBuffer(value);
  39. };
  40. const isObject = (value) => {
  41. // This is a very simple check, but it’s good enough for what we need.
  42. return toString.call(value) == '[object Object]';
  43. };
  44. const isString = (value) => {
  45. return typeof value == 'string' ||
  46. toString.call(value) == '[object String]';
  47. };
  48. const isNumber = (value) => {
  49. return typeof value == 'number' ||
  50. toString.call(value) == '[object Number]';
  51. };
  52. const isFunction = (value) => {
  53. return typeof value == 'function';
  54. };
  55. const isMap = (value) => {
  56. return toString.call(value) == '[object Map]';
  57. };
  58. const isSet = (value) => {
  59. return toString.call(value) == '[object Set]';
  60. };
  61. /*--------------------------------------------------------------------------*/
  62. // https://mathiasbynens.be/notes/javascript-escapes#single
  63. const singleEscapes = {
  64. '\\': '\\\\',
  65. '\b': '\\b',
  66. '\f': '\\f',
  67. '\n': '\\n',
  68. '\r': '\\r',
  69. '\t': '\\t'
  70. // `\v` is omitted intentionally, because in IE < 9, '\v' == 'v'.
  71. // '\v': '\\x0B'
  72. };
  73. const regexSingleEscape = /[\\\b\f\n\r\t]/;
  74. const regexDigit = /[0-9]/;
  75. const regexWhitespace = /[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
  76. const escapeEverythingRegex = /([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^]/g;
  77. const escapeNonAsciiRegex = /([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^ !#-&\(-\[\]-_a-~]/g;
  78. const jsesc = (argument, options) => {
  79. const increaseIndentation = () => {
  80. oldIndent = indent;
  81. ++options.indentLevel;
  82. indent = options.indent.repeat(options.indentLevel)
  83. };
  84. // Handle options
  85. const defaults = {
  86. 'escapeEverything': false,
  87. 'minimal': false,
  88. 'isScriptContext': false,
  89. 'quotes': 'single',
  90. 'wrap': false,
  91. 'es6': false,
  92. 'json': false,
  93. 'compact': true,
  94. 'lowercaseHex': false,
  95. 'numbers': 'decimal',
  96. 'indent': '\t',
  97. 'indentLevel': 0,
  98. '__inline1__': false,
  99. '__inline2__': false
  100. };
  101. const json = options && options.json;
  102. if (json) {
  103. defaults.quotes = 'double';
  104. defaults.wrap = true;
  105. }
  106. options = extend(defaults, options);
  107. if (
  108. options.quotes != 'single' &&
  109. options.quotes != 'double' &&
  110. options.quotes != 'backtick'
  111. ) {
  112. options.quotes = 'single';
  113. }
  114. const quote = options.quotes == 'double' ?
  115. '"' :
  116. (options.quotes == 'backtick' ?
  117. '`' :
  118. '\''
  119. );
  120. const compact = options.compact;
  121. const lowercaseHex = options.lowercaseHex;
  122. let indent = options.indent.repeat(options.indentLevel);
  123. let oldIndent = '';
  124. const inline1 = options.__inline1__;
  125. const inline2 = options.__inline2__;
  126. const newLine = compact ? '' : '\n';
  127. let result;
  128. let isEmpty = true;
  129. const useBinNumbers = options.numbers == 'binary';
  130. const useOctNumbers = options.numbers == 'octal';
  131. const useDecNumbers = options.numbers == 'decimal';
  132. const useHexNumbers = options.numbers == 'hexadecimal';
  133. if (json && argument && isFunction(argument.toJSON)) {
  134. argument = argument.toJSON();
  135. }
  136. if (!isString(argument)) {
  137. if (isMap(argument)) {
  138. if (argument.size == 0) {
  139. return 'new Map()';
  140. }
  141. if (!compact) {
  142. options.__inline1__ = true;
  143. options.__inline2__ = false;
  144. }
  145. return 'new Map(' + jsesc(Array.from(argument), options) + ')';
  146. }
  147. if (isSet(argument)) {
  148. if (argument.size == 0) {
  149. return 'new Set()';
  150. }
  151. return 'new Set(' + jsesc(Array.from(argument), options) + ')';
  152. }
  153. if (isBuffer(argument)) {
  154. if (argument.length == 0) {
  155. return 'Buffer.from([])';
  156. }
  157. return 'Buffer.from(' + jsesc(Array.from(argument), options) + ')';
  158. }
  159. if (isArray(argument)) {
  160. result = [];
  161. options.wrap = true;
  162. if (inline1) {
  163. options.__inline1__ = false;
  164. options.__inline2__ = true;
  165. }
  166. if (!inline2) {
  167. increaseIndentation();
  168. }
  169. forEach(argument, (value) => {
  170. isEmpty = false;
  171. if (inline2) {
  172. options.__inline2__ = false;
  173. }
  174. result.push(
  175. (compact || inline2 ? '' : indent) +
  176. jsesc(value, options)
  177. );
  178. });
  179. if (isEmpty) {
  180. return '[]';
  181. }
  182. if (inline2) {
  183. return '[' + result.join(', ') + ']';
  184. }
  185. return '[' + newLine + result.join(',' + newLine) + newLine +
  186. (compact ? '' : oldIndent) + ']';
  187. } else if (isNumber(argument)) {
  188. if (json) {
  189. // Some number values (e.g. `Infinity`) cannot be represented in JSON.
  190. return JSON.stringify(argument);
  191. }
  192. if (useDecNumbers) {
  193. return String(argument);
  194. }
  195. if (useHexNumbers) {
  196. let hexadecimal = argument.toString(16);
  197. if (!lowercaseHex) {
  198. hexadecimal = hexadecimal.toUpperCase();
  199. }
  200. return '0x' + hexadecimal;
  201. }
  202. if (useBinNumbers) {
  203. return '0b' + argument.toString(2);
  204. }
  205. if (useOctNumbers) {
  206. return '0o' + argument.toString(8);
  207. }
  208. } else if (!isObject(argument)) {
  209. if (json) {
  210. // For some values (e.g. `undefined`, `function` objects),
  211. // `JSON.stringify(value)` returns `undefined` (which isn’t valid
  212. // JSON) instead of `'null'`.
  213. return JSON.stringify(argument) || 'null';
  214. }
  215. return String(argument);
  216. } else { // it’s an object
  217. result = [];
  218. options.wrap = true;
  219. increaseIndentation();
  220. forOwn(argument, (key, value) => {
  221. isEmpty = false;
  222. result.push(
  223. (compact ? '' : indent) +
  224. jsesc(key, options) + ':' +
  225. (compact ? '' : ' ') +
  226. jsesc(value, options)
  227. );
  228. });
  229. if (isEmpty) {
  230. return '{}';
  231. }
  232. return '{' + newLine + result.join(',' + newLine) + newLine +
  233. (compact ? '' : oldIndent) + '}';
  234. }
  235. }
  236. const regex = options.escapeEverything ? escapeEverythingRegex : escapeNonAsciiRegex;
  237. result = argument.replace(regex, (char, pair, lone, quoteChar, index, string) => {
  238. if (pair) {
  239. if (options.minimal) return pair;
  240. const first = pair.charCodeAt(0);
  241. const second = pair.charCodeAt(1);
  242. if (options.es6) {
  243. // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  244. const codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  245. const hex = hexadecimal(codePoint, lowercaseHex);
  246. return '\\u{' + hex + '}';
  247. }
  248. return fourHexEscape(hexadecimal(first, lowercaseHex)) + fourHexEscape(hexadecimal(second, lowercaseHex));
  249. }
  250. if (lone) {
  251. return fourHexEscape(hexadecimal(lone.charCodeAt(0), lowercaseHex));
  252. }
  253. if (
  254. char == '\0' &&
  255. !json &&
  256. !regexDigit.test(string.charAt(index + 1))
  257. ) {
  258. return '\\0';
  259. }
  260. if (quoteChar) {
  261. if (quoteChar == quote || options.escapeEverything) {
  262. return '\\' + quoteChar;
  263. }
  264. return quoteChar;
  265. }
  266. if (regexSingleEscape.test(char)) {
  267. // no need for a `hasOwnProperty` check here
  268. return singleEscapes[char];
  269. }
  270. if (options.minimal && !regexWhitespace.test(char)) {
  271. return char;
  272. }
  273. const hex = hexadecimal(char.charCodeAt(0), lowercaseHex);
  274. if (json || hex.length > 2) {
  275. return fourHexEscape(hex);
  276. }
  277. return '\\x' + ('00' + hex).slice(-2);
  278. });
  279. if (quote == '`') {
  280. result = result.replace(/\$\{/g, '\\${');
  281. }
  282. if (options.isScriptContext) {
  283. // https://mathiasbynens.be/notes/etago
  284. result = result
  285. .replace(/<\/(script|style)/gi, '<\\/$1')
  286. .replace(/<!--/g, json ? '\\u003C!--' : '\\x3C!--');
  287. }
  288. if (options.wrap) {
  289. result = quote + result + quote;
  290. }
  291. return result;
  292. };
  293. jsesc.version = '3.0.2';
  294. module.exports = jsesc;