{"id":21466549,"url":"https://github.com/permafrost-dev/pretty-format","last_synced_at":"2025-03-17T05:47:57.972Z","repository":{"id":37080082,"uuid":"343510388","full_name":"permafrost-dev/pretty-format","owner":"permafrost-dev","description":"Stringify any JavaScript value.","archived":false,"fork":false,"pushed_at":"2023-11-20T17:16:42.000Z","size":95,"stargazers_count":0,"open_issues_count":8,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-12T17:08:09.489Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/permafrost-dev.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-01T18:03:35.000Z","updated_at":"2022-12-01T23:21:15.000Z","dependencies_parsed_at":"2024-06-21T04:30:09.159Z","dependency_job_id":null,"html_url":"https://github.com/permafrost-dev/pretty-format","commit_stats":{"total_commits":38,"total_committers":4,"mean_commits":9.5,"dds":"0.42105263157894735","last_synced_commit":"29e0b6668107a0da4048cdfe01fb03e59ce68f5b"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/permafrost-dev%2Fpretty-format","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/permafrost-dev%2Fpretty-format/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/permafrost-dev%2Fpretty-format/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/permafrost-dev%2Fpretty-format/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/permafrost-dev","download_url":"https://codeload.github.com/permafrost-dev/pretty-format/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243858048,"owners_count":20359267,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-23T08:14:29.571Z","updated_at":"2025-03-17T05:47:57.953Z","avatar_url":"https://github.com/permafrost-dev.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# @permafrost-dev/pretty-format\n\n---\n\n\u003cp align=\"center\"\u003e\n    \u003cimg src=\"https://shields.io/npm/v/@permafrost-dev/pretty-format\" alt=\"npm version\"\u003e \u003cimg src=\"https://github.com/permafrost-dev/pretty-format/actions/workflows/run-tests.yml/badge.svg\" alt=\"test status\"\u003e \u003cimg src=\"https://codecov.io/gh/permafrost-dev/pretty-format/branch/main/graph/badge.svg?token=FS0MGVSMUE\"/\u003e\n\u003c/p\u003e\n\nThis package originally comes from the `jest` package _(27.0.0-next.3)_.  It is located under `packages/pretty-format`.\n\nThe original package author was James Kyle \u003cme@thejameskyle.com\u003e.\n\n---\n\nThis package is largely unchanged from the original with the exception of removing several plugins, including support for React components.\n\n---\n\nStringify any JavaScript value.\n\n- Serialize built-in JavaScript types.\n- Serialize application-specific data types with built-in or user-defined plugins.\n\n## Installation\n\n```sh\n$ npm install @permafrost-dev/pretty-format\n\nor\n\n$ yarn add @permafrost-dev/pretty-format\n```\n\n## Usage\n\n```js\nconst {format: prettyFormat} = require('@permafrost-dev/pretty-format'); // CommonJS\n```\n\n```js\nimport {format as prettyFormat} from '@permafrost-dev/pretty-format'; // ES2015 modules\n```\n\n```js\nconst val = {object: {}};\nval.circularReference = val;\nval[Symbol('foo')] = 'foo';\nval.map = new Map([['prop', 'value']]);\nval.array = [-0, Infinity, NaN];\n\nconsole.log(prettyFormat(val));\n/*\nObject {\n  \"array\": Array [\n    -0,\n    Infinity,\n    NaN,\n  ],\n  \"circularReference\": [Circular],\n  \"map\": Map {\n    \"prop\" =\u003e \"value\",\n  },\n  \"object\": Object {},\n  Symbol(foo): \"foo\",\n}\n*/\n```\n\n## Usage with options\n\n```js\nfunction onClick() {}\n\nconsole.log(prettyFormat(onClick));\n/*\n[Function onClick]\n*/\n\nconst options = {\n  printFunctionName: false,\n};\nconsole.log(prettyFormat(onClick, options));\n/*\n[Function]\n*/\n```\n\n\u003c!-- prettier-ignore --\u003e\n| key                 | type      | default    | description                                             |\n| :------------------ | :-------- | :--------- | :------------------------------------------------------ |\n| `callToJSON`        | `boolean` | `true`     | call `toJSON` method (if it exists) on objects          |\n| `escapeRegex`       | `boolean` | `false`    | escape special characters in regular expressions        |\n| `escapeString`      | `boolean` | `true`     | escape special characters in strings                    |\n| `highlight`         | `boolean` | `false`    | highlight syntax with colors in terminal (some plugins) |\n| `indent`            | `number`  | `2`        | spaces in each level of indentation                     |\n| `maxDepth`          | `number`  | `Infinity` | levels to print in arrays, objects, elements, and so on |\n| `min`               | `boolean` | `false`    | minimize added space: no indentation nor line breaks    |\n| `plugins`           | `array`   | `[]`       | plugins to serialize application-specific data types    |\n| `printFunctionName` | `boolean` | `true`     | include or omit the name of a function                  |\n| `theme`             | `object`  |            | colors to highlight syntax in terminal                  |\n\nProperty values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors)\n\n```js\nconst DEFAULT_THEME = {\n  comment: 'gray',\n  content: 'reset',\n  prop: 'yellow',\n  tag: 'cyan',\n  value: 'green',\n};\n```\n## Usage in Jest\n\nFor snapshot tests, Jest uses `pretty-format` with options that include some of its built-in plugins. For this purpose, plugins are also known as **snapshot serializers**.\n\nTo serialize application-specific data types, you can add modules to `devDependencies` of a project, and then:\n\nIn an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration.\n\n```js\nimport serializer from 'my-serializer-module';\nexpect.addSnapshotSerializer(serializer);\n\n// tests which have `expect(value).toMatchSnapshot()` assertions\n```\n\nFor **all** test files, you can specify modules in Jest configuration. They precede built-in plugins for HTML data types. For example, in a `package.json` file:\n\n```json\n{\n  \"jest\": {\n    \"snapshotSerializers\": [\"my-serializer-module\"]\n  }\n}\n```\n\n## Writing plugins\n\nA plugin is a JavaScript object.\n\nIf `options` has a `plugins` array: for the first plugin whose `test(val)` method returns a truthy value, then `prettyFormat(val, options)` returns the result from either:\n\n- `serialize(val, …)` method of the **improved** interface (available in **version 21** or later)\n- `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method)\n\n### test\n\nWrite `test` so it can receive `val` argument of any type. To serialize **objects** which have certain properties, then a guarded expression like `val != null \u0026\u0026 …` or more concise `val \u0026\u0026 …` prevents the following errors:\n\n- `TypeError: Cannot read property 'whatever' of null`\n- `TypeError: Cannot read property 'whatever' of undefined`\n\nPay attention to efficiency in `test` because `pretty-format` calls it often.\n\n### serialize\n\nThe **improved** interface is available in **version 21** or later.\n\nWrite `serialize` to return a string, given the arguments:\n\n- `val` which “passed the test”\n- unchanging `config` object: derived from `options`\n- current `indentation` string: concatenate to `indent` from `config`\n- current `depth` number: compare to `maxDepth` from `config`\n- current `refs` array: find circular references in objects\n- `printer` callback function: serialize children\n\n### config\n\n\u003c!-- prettier-ignore --\u003e\n| key                 | type      | description                                             |\n| :------------------ | :-------- | :------------------------------------------------------ |\n| `callToJSON`        | `boolean` | call `toJSON` method (if it exists) on objects          |\n| `colors`            | `Object`  | escape codes for colors to highlight syntax             |\n| `escapeRegex`       | `boolean` | escape special characters in regular expressions        |\n| `escapeString`      | `boolean` | escape special characters in strings                    |\n| `indent`            | `string`  | spaces in each level of indentation                     |\n| `maxDepth`          | `number`  | levels to print in arrays, objects, elements, and so on |\n| `min`               | `boolean` | minimize added space: no indentation nor line breaks    |\n| `plugins`           | `array`   | plugins to serialize application-specific data types    |\n| `printFunctionName` | `boolean` | include or omit the name of a function                  |\n| `spacingInner`      | `strong`  | spacing to separate items in a list                     |\n| `spacingOuter`      | `strong`  | spacing to enclose a list of items                      |\n\nEach property of `colors` in `config` corresponds to a property of `theme` in `options`:\n\n- the key is the same (for example, `tag`)\n- the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`)\n\nSome properties in `config` are derived from `min` in `options`:\n\n- `spacingInner` and `spacingOuter` are **newline** if `min` is `false`\n- `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true`\n\n### Example of serialize and test\n\nThis plugin is a pattern you can apply to serialize composite data types. Side note: `pretty-format` does not need a plugin to serialize arrays.\n\n```js\n// We reused more code when we factored out a function for child items\n// that is independent of depth, name, and enclosing punctuation (see below).\nconst SEPARATOR = ',';\nfunction serializeItems(items, config, indentation, depth, refs, printer) {\n  if (items.length === 0) {\n    return '';\n  }\n  const indentationItems = indentation + config.indent;\n  return (\n    config.spacingOuter +\n    items\n      .map(\n        item =\u003e\n          indentationItems +\n          printer(item, config, indentationItems, depth, refs), // callback\n      )\n      .join(SEPARATOR + config.spacingInner) +\n    (config.min ? '' : SEPARATOR) + // following the last item\n    config.spacingOuter +\n    indentation\n  );\n}\n\nconst plugin = {\n  test(val) {\n    return Array.isArray(val);\n  },\n  serialize(array, config, indentation, depth, refs, printer) {\n    const name = array.constructor.name;\n    return ++depth \u003e config.maxDepth\n      ? '[' + name + ']'\n      : (config.min ? '' : name + ' ') +\n          '[' +\n          serializeItems(array, config, indentation, depth, refs, printer) +\n          ']';\n  },\n};\n```\n\n```js\nconst val = {\n  filter: 'completed',\n  items: [\n    {\n      text: 'Write test',\n      completed: true,\n    },\n    {\n      text: 'Write serialize',\n      completed: true,\n    },\n  ],\n};\n```\n\n```js\nconsole.log(\n  prettyFormat(val, {\n    plugins: [plugin],\n  }),\n);\n/*\nObject {\n  \"filter\": \"completed\",\n  \"items\": Array [\n    Object {\n      \"completed\": true,\n      \"text\": \"Write test\",\n    },\n    Object {\n      \"completed\": true,\n      \"text\": \"Write serialize\",\n    },\n  ],\n}\n*/\n```\n\n```js\nconsole.log(\n  prettyFormat(val, {\n    indent: 4,\n    plugins: [plugin],\n  }),\n);\n/*\nObject {\n    \"filter\": \"completed\",\n    \"items\": Array [\n        Object {\n            \"completed\": true,\n            \"text\": \"Write test\",\n        },\n        Object {\n            \"completed\": true,\n            \"text\": \"Write serialize\",\n        },\n    ],\n}\n*/\n```\n\n```js\nconsole.log(\n  prettyFormat(val, {\n    maxDepth: 1,\n    plugins: [plugin],\n  }),\n);\n/*\nObject {\n  \"filter\": \"completed\",\n  \"items\": [Array],\n}\n*/\n```\n\n```js\nconsole.log(\n  prettyFormat(val, {\n    min: true,\n    plugins: [plugin],\n  }),\n);\n/*\n{\"filter\": \"completed\", \"items\": [{\"completed\": true, \"text\": \"Write test\"}, {\"completed\": true, \"text\": \"Write serialize\"}]}\n*/\n```\n\n### print\n\nThe **original** interface is adequate for plugins:\n\n- that **do not** depend on options other than `highlight` or `min`\n- that **do not** depend on `depth` or `refs` in recursive traversal, and\n- if values either\n  - do **not** require indentation, or\n  - do **not** occur as children of JavaScript data structures (for example, array)\n\nWrite `print` to return a string, given the arguments:\n\n- `val` which “passed the test”\n- current `printer(valChild)` callback function: serialize children\n- current `indenter(lines)` callback function: indent lines at the next level\n- unchanging `config` object: derived from `options`\n- unchanging `colors` object: derived from `options`\n\nThe 3 properties of `config` are `min` in `options` and:\n\n- `spacing` and `edgeSpacing` are **newline** if `min` is `false`\n- `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true`\n\nEach property of `colors` corresponds to a property of `theme` in `options`:\n\n- the key is the same (for example, `tag`)\n- the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`)\n\n### Example of print and test\n\nThis plugin prints functions with the **number of named arguments** excluding rest argument.\n\n```js\nconst plugin = {\n  print(val) {\n    return `[Function ${val.name || 'anonymous'} ${val.length}]`;\n  },\n  test(val) {\n    return typeof val === 'function';\n  },\n};\n```\n\n```js\nconst val = {\n  onClick(event) {},\n  render() {},\n};\n\nprettyFormat(val, {\n  plugins: [plugin],\n});\n/*\nObject {\n  \"onClick\": [Function onClick 1],\n  \"render\": [Function render 0],\n}\n*/\n\nprettyFormat(val);\n/*\nObject {\n  \"onClick\": [Function onClick],\n  \"render\": [Function render],\n}\n*/\n```\n\nThis plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above.\n\n```js\nprettyFormat(val, {\n  plugins: [pluginOld],\n  printFunctionName: false,\n});\n/*\nObject {\n  \"onClick\": [Function onClick 1],\n  \"render\": [Function render 0],\n}\n*/\n\nprettyFormat(val, {\n  printFunctionName: false,\n});\n/*\nObject {\n  \"onClick\": [Function],\n  \"render\": [Function],\n}\n*/\n```\n\n## Testing\n\n`node-ray` uses Jest for unit tests.  To run the test suite:\n\n`npm run test`\n\n---\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Security Vulnerabilities\n\nPlease review [our security policy](../../security/policy) on how to report security vulnerabilities.\n\n## Credits\n\n- James Kyle \u003cme@thejameskyle.com\u003e\n- [Patrick Organ](https://github.com/patinthehat)\n- [All Contributors](../../contributors)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpermafrost-dev%2Fpretty-format","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpermafrost-dev%2Fpretty-format","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpermafrost-dev%2Fpretty-format/lists"}