index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. 'use strict';
  2. var _ansiStyles = _interopRequireDefault(require('ansi-styles'));
  3. var _collections = require('./collections');
  4. var _AsymmetricMatcher = _interopRequireDefault(
  5. require('./plugins/AsymmetricMatcher')
  6. );
  7. var _ConvertAnsi = _interopRequireDefault(require('./plugins/ConvertAnsi'));
  8. var _DOMCollection = _interopRequireDefault(require('./plugins/DOMCollection'));
  9. var _DOMElement = _interopRequireDefault(require('./plugins/DOMElement'));
  10. var _Immutable = _interopRequireDefault(require('./plugins/Immutable'));
  11. var _ReactElement = _interopRequireDefault(require('./plugins/ReactElement'));
  12. var _ReactTestComponent = _interopRequireDefault(
  13. require('./plugins/ReactTestComponent')
  14. );
  15. function _interopRequireDefault(obj) {
  16. return obj && obj.__esModule ? obj : {default: obj};
  17. }
  18. /**
  19. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  20. *
  21. * This source code is licensed under the MIT license found in the
  22. * LICENSE file in the root directory of this source tree.
  23. */
  24. /* eslint-disable local/ban-types-eventually */
  25. const toString = Object.prototype.toString;
  26. const toISOString = Date.prototype.toISOString;
  27. const errorToString = Error.prototype.toString;
  28. const regExpToString = RegExp.prototype.toString;
  29. /**
  30. * Explicitly comparing typeof constructor to function avoids undefined as name
  31. * when mock identity-obj-proxy returns the key as the value for any key.
  32. */
  33. const getConstructorName = val =>
  34. (typeof val.constructor === 'function' && val.constructor.name) || 'Object';
  35. /* global window */
  36. /** Is val is equal to global window object? Works even if it does not exist :) */
  37. const isWindow = val => typeof window !== 'undefined' && val === window;
  38. const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;
  39. const NEWLINE_REGEXP = /\n/gi;
  40. class PrettyFormatPluginError extends Error {
  41. constructor(message, stack) {
  42. super(message);
  43. this.stack = stack;
  44. this.name = this.constructor.name;
  45. }
  46. }
  47. function isToStringedArrayType(toStringed) {
  48. return (
  49. toStringed === '[object Array]' ||
  50. toStringed === '[object ArrayBuffer]' ||
  51. toStringed === '[object DataView]' ||
  52. toStringed === '[object Float32Array]' ||
  53. toStringed === '[object Float64Array]' ||
  54. toStringed === '[object Int8Array]' ||
  55. toStringed === '[object Int16Array]' ||
  56. toStringed === '[object Int32Array]' ||
  57. toStringed === '[object Uint8Array]' ||
  58. toStringed === '[object Uint8ClampedArray]' ||
  59. toStringed === '[object Uint16Array]' ||
  60. toStringed === '[object Uint32Array]'
  61. );
  62. }
  63. function printNumber(val) {
  64. return Object.is(val, -0) ? '-0' : String(val);
  65. }
  66. function printBigInt(val) {
  67. return String(`${val}n`);
  68. }
  69. function printFunction(val, printFunctionName) {
  70. if (!printFunctionName) {
  71. return '[Function]';
  72. }
  73. return '[Function ' + (val.name || 'anonymous') + ']';
  74. }
  75. function printSymbol(val) {
  76. return String(val).replace(SYMBOL_REGEXP, 'Symbol($1)');
  77. }
  78. function printError(val) {
  79. return '[' + errorToString.call(val) + ']';
  80. }
  81. /**
  82. * The first port of call for printing an object, handles most of the
  83. * data-types in JS.
  84. */
  85. function printBasicValue(val, printFunctionName, escapeRegex, escapeString) {
  86. if (val === true || val === false) {
  87. return '' + val;
  88. }
  89. if (val === undefined) {
  90. return 'undefined';
  91. }
  92. if (val === null) {
  93. return 'null';
  94. }
  95. const typeOf = typeof val;
  96. if (typeOf === 'number') {
  97. return printNumber(val);
  98. }
  99. if (typeOf === 'bigint') {
  100. return printBigInt(val);
  101. }
  102. if (typeOf === 'string') {
  103. if (escapeString) {
  104. return '"' + val.replace(/"|\\/g, '\\$&') + '"';
  105. }
  106. return '"' + val + '"';
  107. }
  108. if (typeOf === 'function') {
  109. return printFunction(val, printFunctionName);
  110. }
  111. if (typeOf === 'symbol') {
  112. return printSymbol(val);
  113. }
  114. const toStringed = toString.call(val);
  115. if (toStringed === '[object WeakMap]') {
  116. return 'WeakMap {}';
  117. }
  118. if (toStringed === '[object WeakSet]') {
  119. return 'WeakSet {}';
  120. }
  121. if (
  122. toStringed === '[object Function]' ||
  123. toStringed === '[object GeneratorFunction]'
  124. ) {
  125. return printFunction(val, printFunctionName);
  126. }
  127. if (toStringed === '[object Symbol]') {
  128. return printSymbol(val);
  129. }
  130. if (toStringed === '[object Date]') {
  131. return isNaN(+val) ? 'Date { NaN }' : toISOString.call(val);
  132. }
  133. if (toStringed === '[object Error]') {
  134. return printError(val);
  135. }
  136. if (toStringed === '[object RegExp]') {
  137. if (escapeRegex) {
  138. // https://github.com/benjamingr/RegExp.escape/blob/master/polyfill.js
  139. return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
  140. }
  141. return regExpToString.call(val);
  142. }
  143. if (val instanceof Error) {
  144. return printError(val);
  145. }
  146. return null;
  147. }
  148. /**
  149. * Handles more complex objects ( such as objects with circular references.
  150. * maps and sets etc )
  151. */
  152. function printComplexValue(
  153. val,
  154. config,
  155. indentation,
  156. depth,
  157. refs,
  158. hasCalledToJSON
  159. ) {
  160. if (refs.indexOf(val) !== -1) {
  161. return '[Circular]';
  162. }
  163. refs = refs.slice();
  164. refs.push(val);
  165. const hitMaxDepth = ++depth > config.maxDepth;
  166. const min = config.min;
  167. if (
  168. config.callToJSON &&
  169. !hitMaxDepth &&
  170. val.toJSON &&
  171. typeof val.toJSON === 'function' &&
  172. !hasCalledToJSON
  173. ) {
  174. return printer(val.toJSON(), config, indentation, depth, refs, true);
  175. }
  176. const toStringed = toString.call(val);
  177. if (toStringed === '[object Arguments]') {
  178. return hitMaxDepth
  179. ? '[Arguments]'
  180. : (min ? '' : 'Arguments ') +
  181. '[' +
  182. (0, _collections.printListItems)(
  183. val,
  184. config,
  185. indentation,
  186. depth,
  187. refs,
  188. printer
  189. ) +
  190. ']';
  191. }
  192. if (isToStringedArrayType(toStringed)) {
  193. return hitMaxDepth
  194. ? '[' + val.constructor.name + ']'
  195. : (min ? '' : val.constructor.name + ' ') +
  196. '[' +
  197. (0, _collections.printListItems)(
  198. val,
  199. config,
  200. indentation,
  201. depth,
  202. refs,
  203. printer
  204. ) +
  205. ']';
  206. }
  207. if (toStringed === '[object Map]') {
  208. return hitMaxDepth
  209. ? '[Map]'
  210. : 'Map {' +
  211. (0, _collections.printIteratorEntries)(
  212. val.entries(),
  213. config,
  214. indentation,
  215. depth,
  216. refs,
  217. printer,
  218. ' => '
  219. ) +
  220. '}';
  221. }
  222. if (toStringed === '[object Set]') {
  223. return hitMaxDepth
  224. ? '[Set]'
  225. : 'Set {' +
  226. (0, _collections.printIteratorValues)(
  227. val.values(),
  228. config,
  229. indentation,
  230. depth,
  231. refs,
  232. printer
  233. ) +
  234. '}';
  235. } // Avoid failure to serialize global window object in jsdom test environment.
  236. // For example, not even relevant if window is prop of React element.
  237. return hitMaxDepth || isWindow(val)
  238. ? '[' + getConstructorName(val) + ']'
  239. : (min ? '' : getConstructorName(val) + ' ') +
  240. '{' +
  241. (0, _collections.printObjectProperties)(
  242. val,
  243. config,
  244. indentation,
  245. depth,
  246. refs,
  247. printer
  248. ) +
  249. '}';
  250. }
  251. function isNewPlugin(plugin) {
  252. return plugin.serialize != null;
  253. }
  254. function printPlugin(plugin, val, config, indentation, depth, refs) {
  255. let printed;
  256. try {
  257. printed = isNewPlugin(plugin)
  258. ? plugin.serialize(val, config, indentation, depth, refs, printer)
  259. : plugin.print(
  260. val,
  261. valChild => printer(valChild, config, indentation, depth, refs),
  262. str => {
  263. const indentationNext = indentation + config.indent;
  264. return (
  265. indentationNext +
  266. str.replace(NEWLINE_REGEXP, '\n' + indentationNext)
  267. );
  268. },
  269. {
  270. edgeSpacing: config.spacingOuter,
  271. min: config.min,
  272. spacing: config.spacingInner
  273. },
  274. config.colors
  275. );
  276. } catch (error) {
  277. throw new PrettyFormatPluginError(error.message, error.stack);
  278. }
  279. if (typeof printed !== 'string') {
  280. throw new Error(
  281. `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`
  282. );
  283. }
  284. return printed;
  285. }
  286. function findPlugin(plugins, val) {
  287. for (let p = 0; p < plugins.length; p++) {
  288. try {
  289. if (plugins[p].test(val)) {
  290. return plugins[p];
  291. }
  292. } catch (error) {
  293. throw new PrettyFormatPluginError(error.message, error.stack);
  294. }
  295. }
  296. return null;
  297. }
  298. function printer(val, config, indentation, depth, refs, hasCalledToJSON) {
  299. const plugin = findPlugin(config.plugins, val);
  300. if (plugin !== null) {
  301. return printPlugin(plugin, val, config, indentation, depth, refs);
  302. }
  303. const basicResult = printBasicValue(
  304. val,
  305. config.printFunctionName,
  306. config.escapeRegex,
  307. config.escapeString
  308. );
  309. if (basicResult !== null) {
  310. return basicResult;
  311. }
  312. return printComplexValue(
  313. val,
  314. config,
  315. indentation,
  316. depth,
  317. refs,
  318. hasCalledToJSON
  319. );
  320. }
  321. const DEFAULT_THEME = {
  322. comment: 'gray',
  323. content: 'reset',
  324. prop: 'yellow',
  325. tag: 'cyan',
  326. value: 'green'
  327. };
  328. const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME);
  329. const DEFAULT_OPTIONS = {
  330. callToJSON: true,
  331. escapeRegex: false,
  332. escapeString: true,
  333. highlight: false,
  334. indent: 2,
  335. maxDepth: Infinity,
  336. min: false,
  337. plugins: [],
  338. printFunctionName: true,
  339. theme: DEFAULT_THEME
  340. };
  341. function validateOptions(options) {
  342. Object.keys(options).forEach(key => {
  343. if (!DEFAULT_OPTIONS.hasOwnProperty(key)) {
  344. throw new Error(`pretty-format: Unknown option "${key}".`);
  345. }
  346. });
  347. if (options.min && options.indent !== undefined && options.indent !== 0) {
  348. throw new Error(
  349. 'pretty-format: Options "min" and "indent" cannot be used together.'
  350. );
  351. }
  352. if (options.theme !== undefined) {
  353. if (options.theme === null) {
  354. throw new Error(`pretty-format: Option "theme" must not be null.`);
  355. }
  356. if (typeof options.theme !== 'object') {
  357. throw new Error(
  358. `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".`
  359. );
  360. }
  361. }
  362. }
  363. const getColorsHighlight = options =>
  364. DEFAULT_THEME_KEYS.reduce((colors, key) => {
  365. const value =
  366. options.theme && options.theme[key] !== undefined
  367. ? options.theme[key]
  368. : DEFAULT_THEME[key];
  369. const color = value && _ansiStyles.default[value];
  370. if (
  371. color &&
  372. typeof color.close === 'string' &&
  373. typeof color.open === 'string'
  374. ) {
  375. colors[key] = color;
  376. } else {
  377. throw new Error(
  378. `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.`
  379. );
  380. }
  381. return colors;
  382. }, Object.create(null));
  383. const getColorsEmpty = () =>
  384. DEFAULT_THEME_KEYS.reduce((colors, key) => {
  385. colors[key] = {
  386. close: '',
  387. open: ''
  388. };
  389. return colors;
  390. }, Object.create(null));
  391. const getPrintFunctionName = options =>
  392. options && options.printFunctionName !== undefined
  393. ? options.printFunctionName
  394. : DEFAULT_OPTIONS.printFunctionName;
  395. const getEscapeRegex = options =>
  396. options && options.escapeRegex !== undefined
  397. ? options.escapeRegex
  398. : DEFAULT_OPTIONS.escapeRegex;
  399. const getEscapeString = options =>
  400. options && options.escapeString !== undefined
  401. ? options.escapeString
  402. : DEFAULT_OPTIONS.escapeString;
  403. const getConfig = options => ({
  404. callToJSON:
  405. options && options.callToJSON !== undefined
  406. ? options.callToJSON
  407. : DEFAULT_OPTIONS.callToJSON,
  408. colors:
  409. options && options.highlight
  410. ? getColorsHighlight(options)
  411. : getColorsEmpty(),
  412. escapeRegex: getEscapeRegex(options),
  413. escapeString: getEscapeString(options),
  414. indent:
  415. options && options.min
  416. ? ''
  417. : createIndent(
  418. options && options.indent !== undefined
  419. ? options.indent
  420. : DEFAULT_OPTIONS.indent
  421. ),
  422. maxDepth:
  423. options && options.maxDepth !== undefined
  424. ? options.maxDepth
  425. : DEFAULT_OPTIONS.maxDepth,
  426. min: options && options.min !== undefined ? options.min : DEFAULT_OPTIONS.min,
  427. plugins:
  428. options && options.plugins !== undefined
  429. ? options.plugins
  430. : DEFAULT_OPTIONS.plugins,
  431. printFunctionName: getPrintFunctionName(options),
  432. spacingInner: options && options.min ? ' ' : '\n',
  433. spacingOuter: options && options.min ? '' : '\n'
  434. });
  435. function createIndent(indent) {
  436. return new Array(indent + 1).join(' ');
  437. }
  438. /**
  439. * Returns a presentation string of your `val` object
  440. * @param val any potential JavaScript object
  441. * @param options Custom settings
  442. */
  443. function prettyFormat(val, options) {
  444. if (options) {
  445. validateOptions(options);
  446. if (options.plugins) {
  447. const plugin = findPlugin(options.plugins, val);
  448. if (plugin !== null) {
  449. return printPlugin(plugin, val, getConfig(options), '', 0, []);
  450. }
  451. }
  452. }
  453. const basicResult = printBasicValue(
  454. val,
  455. getPrintFunctionName(options),
  456. getEscapeRegex(options),
  457. getEscapeString(options)
  458. );
  459. if (basicResult !== null) {
  460. return basicResult;
  461. }
  462. return printComplexValue(val, getConfig(options), '', 0, []);
  463. }
  464. prettyFormat.plugins = {
  465. AsymmetricMatcher: _AsymmetricMatcher.default,
  466. ConvertAnsi: _ConvertAnsi.default,
  467. DOMCollection: _DOMCollection.default,
  468. DOMElement: _DOMElement.default,
  469. Immutable: _Immutable.default,
  470. ReactElement: _ReactElement.default,
  471. ReactTestComponent: _ReactTestComponent.default
  472. };
  473. module.exports = prettyFormat;