[
  {
    "path": ".gitignore",
    "content": "node_modules\nprojects\nyarn-error.log\nbuild\ncoverage\n.DS_Store\n/package-lock.json\n"
  },
  {
    "path": ".npmignore",
    "content": "docs/\nexample/"
  },
  {
    "path": "LICENSE",
    "content": "The MIT Licence (MIT)\n\nCopyright 2021 Jani Eväkallio <jani.evakallio@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
  },
  {
    "path": "README.md",
    "content": "# jest-clean-console-reporter (alpha)\n\n_A custom Jest reporter to reduce `console` spam in your test output._\n\n---\n\nRemember back in the day when [Jest](https://jestjs.io/) used to swallow `console.log` messages by default, and it was basically impossible to figure out why your code was failing under test? \\***Sigh\\***. Those were the days.\n\nNow that Jest prints all console messages, whether from our own code, third-party framework code, or the test runner itself, we have the opposite problem: **It's easy to lose actually important warnings among noise.**\n\nThe `jest-clean-console-reporter` reporter collects all console messages written by the test process, and allows you to group them by known error warning types, or ignore them outright.\n\n![Demo](docs/demo.png)\n\n## Stating the obvious\n\n**The best way to remove warnings in your code is to address their root cause.**\n\nThis reporter is probably best used when filtering out spammy library warnings that are otherwise tricky or impossible to get rid of, or ignoring intentional user-facing warnings of your own project.\n\n## Usage\n\nInstall with your favorite package manager:\n\n```sh\nnpm install --save-dev jest-clean-console-reporter\n```\n\nYou'll also need Jest 25.1 or later installed in your project.\n\n### Configuration\n\n```js\n// List known warnings you want to group or suppress. See docs below.\n// Tip: This is just an array, you can import it from an external file\nconst rules = [\n  {\n    match: /^You are using the simple \\(heuristic\\) fragment matcher/,\n    group: \"Apollo: You are using the simple (heuristic) fragment matcher.\",\n  },\n  {\n    match: /^Heuristic fragment matching going on/,\n    group: null, // ignore outright\n  },\n  {\n    match: /^Warning: An update to (\\w*) inside a test was not wrapped in act/,\n    group: \"React: Act warnings\",\n    keep: true, // include in summary, but also keep raw console output\n  },\n];\n\n// Add reporters to your jest config\nmodule.exports = {\n  // ...\n\n  reporters: [\n    // Add jest-clean-console-reporter. This takes place of the\n    // default reporter, and behaves identically otherwise\n    [\"jest-clean-console-reporter\", { rules: rules }],\n\n    // Overriding config.reporters wipes out default reporters, so\n    // we need to restore the summary reporter.\n    //\n    // NOTE: For jest 26.6.1 or older, this file is located at\n    // @jest/reporters/build/summary_reporter\n    \"@jest/reporters/build/SummaryReporter\",\n  ],\n};\n```\n\n## Options\n\nPass options to the reporter in your jest configuration as follows:\n\n### Using Jest 26.6.2 or newer\n\n```js\nconst jestConfig = {\n  reporters: [\n    [\"jest-clean-console-reporter\", options], // <--\n    \"@jest/reporters/build/SummaryReporter\",\n  ],\n};\n```\n\n### Using Jest 25.1.0-26.6.1\n\n```js\nconst jestConfig = {\n  reporters: [\n    [\"jest-clean-console-reporter\", options], // <--\n    \"@jest/reporters/build/summary_reporter\",\n  ],\n};\n```\n\n### `options.rules`\n\nRules tell the reporter which console messages should be filtered, and how\nthey should be grouped in the summary.\n\nEach rule has three options, `match`, `group` and (optionally) `keep`.\n\n#### `rule.match : RegExp | string | (message, level, origin) => boolean`\n\n`match` is either a regular expression, a string, or a predicate function:\n\n- `RegExp`: Matches console message against this regular expression.\n- `string`: Matches console message against this string, first using literal `===` comparison, and falls back to regular expression comparison using `message.match(match)`. The latter is not recommended, but useful if you need to serialize your regular expressions.\n- A predicate function that's called with `match(message, level)` where\n  - `message` is the full console message\n  - `level` is the log level (error, warning, log etc..).\n  - `origin` is the stack trace string for this error. Useful if you want to ignore all errors from a certain library, for example. Note that this string can contain newlines, so any regexes used to match it should use the `/g` flag.\n  - To match this message, the predicate may return any truthy value.\n\nRules are matched in order, from top down. A message that is not matched by any rule will be displayed in the Jest test output as normal.\n\nMatched messages are grouped according to the `group` property:\n\n#### `rule.group : string | null | (message, level, matcher) => string | null`\n\n`group` is either a string, a formatter function, or null:\n\n- `string`: Matched messages are grouped by this literal string\n- `null`: Matched message is ignored.\n- Formatter function that's called with `group(message, level, matcher)` where\n  - `message` is the full console message.\n  - `level` is the log level (error, warning, log etc..).\n  - `matcher` is the original matcher used to match this message. This can be useful if you want to e.g. execute the regular expression for capture groups.\n  - The value returned by this function is used as capture key. If the function returns `null`, the message is ignored.\n\n#### `rule.keep: boolean`\n\nSetting `keep: true` option allows you to keep the original console output for this group intact, while also displaying it in the test run summary.\n\n### options.levels\n\nDefine which log levels to display in the summary at the end of the test run:\n\nDefault: `[\"error\", \"warn\", \"info\", \"debug\", \"log\"]`\n\nThese levels only affect the summary display, and have no effect on whether messages are matched. For that, see [Can I ignore all messages of certain log level?](#can-i-ignore-all-messages-of-certain-log-level).\n\n## Never Asked Questions\n\nHere are some questions nobody has ever asked, but might be helpful anyway.\n\n### Can I ignore all messages of certain log level?\n\nYes. Use the second parameter passed to a function macher:\n\n```js\n{ match: (message, level) => level === \"log\", group: null }\n```\n\n### Can I ignore all messages, period?\n\nYes, but it's probably a bad idea:\n\n```js\n{ matcher: () => true, group: null }\n```\n\n### Can I group multiple error messages into the same bucket?\n\nYes, just give them the same group key:\n\n```js\n[\n  {\n    match: /^Warning: componentWillMount has been renamed/,\n    group: \"React componentWill* deprecation warnings\",\n  },\n  {\n    match: /^Warning: componentWillReceiveProps has been renamed/,\n    group: \"React componentWill* deprecation warnings\",\n  },\n];\n```\n\n### Can I temporarily let a certain message through?\n\nYes, just set the rule's `keep` property to `true`:\n\n```js\n{\n  match: /^Warning: An update to (\\w*) inside a test was not wrapped in act/,\n  group: \"An update to (Component) inside a test was not wrapped in act\",\n  keep: true\n}\n```\n\n### Can I use this with .json config?\n\nYou can use string matchers, which are first compared to the message as literal strings, and failing that, attempted to test against the message as regular expressions:\n\n```json\n{\n  \"match\": \"Warning: An update to \\\\w* inside a test was not wrapped in act\",\n  \"group\": \"An update to (Component) inside a test was not wrapped in act\"\n}\n```\n\n### Can I parameterize log groups using regex capture groups?\n\nYou can use the grouping function, where the original matcher is provided as a third argument.\n\n```js\n{\n    match: /^Warning: An update to (\\w*) inside a test was not wrapped in act/,\n    group: (message, _level, matcher) => {\n      // Note: String.matchAll requires Node 12.x or higher\n      const [match] = message.matchAll(matcher);\n      return `React: An update to ${match[1]} was not wrapped in act.`;\n    }\n}\n```\n\n### Can I ignore random `console.error`s from a specific library?\n\nYes, `console.error` comes with an `origin` property that contains the full stack trace\nat the time of logging, which you should be able to use to filter per library, or even per file and line!\n\nThe origin may not be available for other log types, so check it before you use it.\n\n```js\n  {\n    match: (_message, _type, origin) =>\n      origin && /node_modules\\/rc-form\\/lib\\/createBaseForm/g.test(origin),\n    group: 'rc-form validation warnings'\n  },\n```\n\n### Can I help make this library better?\n\nYes, see [Contibuting](#contributing).\n\n## Contributing\n\nThis software is very much at alpha stage. If you want to help, here are a few things that could be helpful:\n\n- [ ] Write tests\n- [ ] Convert project to TypeScript\n- [ ] NPM scripts for workflows\n- [ ] Don't override DefaultReporter\n  - [ ] When I started hacking on this, I couldn't immediately see a way to suppress `result.console` from being printed by the DefaultReporter, so I overrode it. This is annoying, because it can't be used with other custom reporters now. But it occurs to me, that maybe if a custom reporter is installed in the pipeline **before** the default reporter, perhaps we could filter out console messages there. Tradeoff here would be that we would nuke the console for ALL other reporters, whereas now we only do it for DefaultReporter.\n- [ ] Feature ideas\n  - [ ] Allow to fail the test suite after a certain threshold is passed, e.g. `rule.failAfter`.\n  - [ ] Provide better summary that shows errors by file/test (behind an option flag)\n  - [ ] Show deltas (+/- change) since last run (would require caching)\n- [ ] Known issues\n  - [ ] When running Jest with a single file parameter (e.g. `jest src/file.js`), the reporter is not activated\n\n## License\n\n[MIT](LICENSE)\n"
  },
  {
    "path": "example/jest.config.js",
    "content": "const rules = [\n  {\n    match: /^Received invalid input:/,\n    group: \"Received invalid input\",\n    keep: true,\n  },\n  {\n    match: /^Received a non-integer number:/,\n    group: \"Received a non-integer number\",\n  },\n  {\n    match: /^Received value:/,\n    group: null,\n  },\n];\n\nmodule.exports = {\n  reporters: [\n    [\"jest-clean-console-reporter\", { rules }],\n    \"@jest/reporters/build/SummaryReporter\",\n  ],\n  testMatch: [\"<rootDir>/src/**/*.test.js\"],\n};\n"
  },
  {
    "path": "example/package.json",
    "content": "{\n  \"name\": \"jest-clean-console-reporter-test-app\",\n  \"version\": \"1.0.0\",\n  \"main\": \"index.js\",\n  \"author\": \"Jani Eväkallio\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"test\": \"jest --config jest.config.js\"\n  },\n  \"devDependencies\": {\n    \"jest\": \"^26.6.3\",\n    \"jest-clean-console-reporter\": \"latest\"\n  }\n}\n"
  },
  {
    "path": "example/src/print.js",
    "content": "\"use strict\";\n\nmodule.exports = function print(n) {\n  console.info(\"Received value: \" + n);\n\n  // throws when \"n\" is not a number\n  return n.toFixed(2);\n};\n"
  },
  {
    "path": "example/src/print.test.js",
    "content": "const print = require(\"./print\");\n\ndescribe(\"print\", () => {\n  it(\"prints a number\", () => {\n    expect(print(25 / 2)).toBe(\"12.50\");\n  });\n\n  it(\"crashes when passed a non-number\", () => {\n    // this test will fail\n    expect(() => print(\"100\")).toThrow();\n  });\n});\n"
  },
  {
    "path": "example/src/square.js",
    "content": "module.exports = function square(n) {\n  // info\n  console.info(\"Received value: \" + n);\n\n  if (typeof n !== \"number\") {\n    // this error is preserved with rule.keep\n    console.error(\"Received invalid input: \" + n);\n    return NaN;\n  }\n\n  if (!Number.isInteger(n)) {\n    // warning\n    console.warn(\"Received a non-integer number: \" + n);\n  }\n\n  return n * n;\n};\n"
  },
  {
    "path": "example/src/square.test.js",
    "content": "const square = require(\"./square\");\n\ndescribe(\"square\", () => {\n  it(\"squares an integer\", () => {\n    expect(square(3)).toBe(9);\n  });\n\n  it(\"squares a non-integer number\", () => {\n    expect(square(2.5)).toBe(6.25);\n  });\n\n  it(\"fails to square a non-number\", () => {\n    expect(square(\"bob\")).toBe(NaN);\n  });\n});\n"
  },
  {
    "path": "lib/CleanConsoleReporter.js",
    "content": "/* global require module */\n\nconst { DefaultReporter } = require(\"@jest/reporters\");\nconst getLogGroupKey = require(\"./getLogGroupKey\");\nconst getLogGroupSummary = require(\"./getLogGroupSummary\");\n\n/**\n * Overrides Jest's default reporter to filter out known console messages,\n * and prints a summary at the end of the test run.\n */\nclass CleanConsoleReporter extends DefaultReporter {\n  constructor(globalConfig, options = {}) {\n    super(globalConfig);\n    this.rules = options.rules || [];\n    this.levels = options.levels || [\"error\", \"warn\", \"info\", \"debug\", \"log\"];\n    this.logs = new Map();\n    this.ignored = 0;\n  }\n\n  // Override DefaultReporter method\n  printTestFileHeader(testPath, config, result) {\n    // Strip out known console messages before passing to base implementation\n    const filteredResult = {\n      ...result,\n      console: this.filterOutKnownMessages(result.console),\n    };\n\n    DefaultReporter.prototype.printTestFileHeader.call(\n      this,\n      testPath,\n      config,\n      filteredResult\n    );\n  }\n\n  filterOutKnownMessages(consoleBuffer = []) {\n    const rules = this.rules;\n    const retain = [];\n\n    for (const frame of consoleBuffer) {\n      // Check if this a known type message\n      const [key, keep] = getLogGroupKey(rules, frame);\n      if (key) {\n        this.groupMessageByKey(frame.type, key);\n        if (keep) {\n          retain.push(frame);\n        }\n      } else if (key === null) {\n        this.ignored++;\n      } else {\n        retain.push(frame);\n      }\n    }\n\n    // Based implementation expects undefined instead of empty array\n    return retain.length ? retain : undefined;\n  }\n\n  groupMessageByKey(type, key) {\n    // this.logs : Map<string, Map<string, number>>\n    let level = this.logs.get(type);\n    if (!level) {\n      this.logs.set(type, (level = new Map()));\n    }\n\n    level.set(key, (level.get(key) || 0) + 1);\n  }\n\n  onRunStart(...args) {\n    DefaultReporter.prototype.onRunStart.call(this, ...args);\n  }\n\n  onRunComplete(...args) {\n    const summary = getLogGroupSummary(this.logs, this.levels, this.ignored);\n    if (summary) {\n      summary.forEach(this.log);\n    }\n\n    DefaultReporter.prototype.onRunComplete.call(this, ...args);\n  }\n}\n\nmodule.exports = CleanConsoleReporter;\n"
  },
  {
    "path": "lib/getLogGroupHeader.js",
    "content": "/* global require, module */\n\nconst chalk = require(\"chalk\");\n\n// Explicitly reset for these messages since they can get written out in the\n// middle of error logging\nconst ERROR_TEXT = \"ERROR\";\nconst WARN_TEXT = \"WARN\";\nconst LOG_TEXT = \"LOG\";\nconst INFO_TEXT = \"INFO\";\nconst DEBUG_TEXT = \"DEBUG\";\n\nconst statusByType = {\n  error: chalk.supportsColor\n    ? chalk.reset.bold.red(` ${ERROR_TEXT}`.padEnd(7))\n    : ERROR_TEXT,\n  warn: chalk.supportsColor\n    ? chalk.reset.bold.yellow(` ${WARN_TEXT}`.padEnd(7))\n    : WARN_TEXT,\n  log: chalk.supportsColor\n    ? chalk.reset.bold.cyan(` ${LOG_TEXT}`.padEnd(7))\n    : LOG_TEXT,\n  info: chalk.supportsColor\n    ? chalk.reset.bold.blue(` ${INFO_TEXT}`.padEnd(7))\n    : INFO_TEXT,\n  debug: chalk.supportsColor\n    ? chalk.reset.bold.magenta(` ${DEBUG_TEXT}`.padEnd(7))\n    : DEBUG_TEXT,\n};\n\nconst formatCount = (count) => {\n  const chars = count.toString();\n  const chalked = chalk.bold(chars);\n  const formatChars = chalked.length - chars.length;\n  return `${chalked}`.padEnd(5 + formatChars, \" \");\n};\n\nconst formatMessage = (key) => {\n  const truncated = key.length > 100 ? `${key.substring(0, 100)}...` : key;\n  const singleline = truncated.replace(/[\\r\\n]+/g, \" \");\n  const highlighted = singleline.replace(\"@TODO\", chalk.bold(\"@TODO\"));\n\n  return highlighted;\n};\n\nconst getLogGroupHeader = (type, key, count) => {\n  const status = statusByType[type] || type.toUpperCase();\n  return `${status} ${formatCount(count)} ${formatMessage(key)}`;\n};\n\nconst getSkippedHeader = (count) => {\n  const label = \" SKIP\".padEnd(7);\n  const message = `${label} ${formatCount(count)} messages were filtered`;\n  return chalk.supportsColor ? chalk.reset.gray(message) : message;\n};\n\nmodule.exports = { getLogGroupHeader, getSkippedHeader };\n"
  },
  {
    "path": "lib/getLogGroupKey.js",
    "content": "/* global module */\nconst matchWith = (matcher, message, type, origin) => {\n  if (matcher instanceof RegExp) {\n    return matcher.test(message);\n  }\n  if (typeof matcher === \"string\") {\n    if (matcher === message) {\n      return true;\n    } else {\n      return message.match(matcher);\n    }\n  }\n  if (typeof matcher === \"function\") {\n    return matcher(message, type, origin);\n  }\n\n  throw new Error(\"Filter must be a string, function or a regular expression\");\n};\n\nconst formatMessage = (formatter, message, type, matcher) => {\n  if (typeof formatter === \"undefined\") {\n    return null;\n  }\n\n  if (typeof formatter === \"function\") {\n    return formatter(message, type, matcher);\n  }\n\n  if (typeof formatter === \"string\") {\n    return formatter;\n  }\n\n  if (formatter === null) {\n    return null;\n  }\n\n  return message;\n};\n\nconst getLogGroupKey = (rules, { message, type, origin }) => {\n  for (let { match: matcher, group: formatter, keep = false } of rules) {\n    if (matchWith(matcher, message, type, origin)) {\n      return [formatMessage(formatter, message, type, matcher), keep];\n    }\n  }\n\n  return [];\n};\n\nmodule.exports = getLogGroupKey;\n"
  },
  {
    "path": "lib/getLogGroupSummary.js",
    "content": "/* global require module */\n\nconst chalk = require(\"chalk\");\nconst { getLogGroupHeader, getSkippedHeader } = require(\"./getLogGroupHeader\");\n\nconst orderBy = ([aKey, aCount], [bKey, bCount]) => {\n  // count descending\n  if (aCount > bCount) return -1;\n  if (bCount > aCount) return 1;\n\n  // key ascending\n  if (aKey < bKey) return -1;\n  if (bKey < aKey) return 1;\n\n  // should never happen since keys are unique\n  return 0;\n};\n\nconst getLogGroupSummary = (logs, levels, ignored) => {\n  if (logs.size === 0 && !ignored) {\n    return null;\n  }\n\n  const lines = [`\\n ${chalk.bold(\"\\u25cf \")} Suppressed console messages:\\n`];\n  levels.forEach((type) => {\n    const level = logs.get(type);\n    if (level) {\n      const entries = [...level.entries()].sort(orderBy);\n      for (let [key, count] of entries) {\n        lines.push(getLogGroupHeader(type, key, count));\n      }\n    }\n  });\n\n  if (ignored) {\n    lines.push(getSkippedHeader(ignored));\n  }\n\n  return lines;\n};\n\nmodule.exports = getLogGroupSummary;\n"
  },
  {
    "path": "lib/index.js",
    "content": "/* global require module */\nmodule.exports = require(\"./CleanConsoleReporter\");\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"jest-clean-console-reporter\",\n  \"version\": \"0.3.0\",\n  \"description\": \"Jest reporter for grouping and filtering intrusive console warnings\",\n  \"main\": \"lib/index.js\",\n  \"repository\": \"https://github.com/jevakallio/jest-clean-console-reporter\",\n  \"author\": \"Jani Eväkallio\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"prepare\": \"npm-install-peers\"\n  },\n  \"dependencies\": {\n    \"chalk\": \">=3.0.0\"\n  },\n  \"peerDependencies\": {\n    \"jest\": \">=25.1.0\"\n  },\n  \"devDependencies\": {\n    \"npm-install-peers\": \"^1.2.1\"\n  }\n}\n"
  }
]