index.js 13 KB

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