[
  {
    "path": ".babelrc",
    "content": "{\n    \"presets\": [],\n    \"plugins\": [\n      \"@babel/plugin-proposal-class-properties\"\n    ]\n  }\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE.md",
    "content": "To create a new issue or search existing discussions, start here:  \n👉 **https://www.pika.dev/packages/@pika/pack/discuss** 👈\n\nAll new issues created directly through GitHub will be closed.  \nLearn more: https://www.pika.dev/discussions\n"
  },
  {
    "path": ".gitignore",
    "content": "lib-node/\nlocal/\n.DS_Store\n/pkg\n/lib\n/lib-legacy\n/node_modules\n*.log\n/.nyc_output\n/coverage\n/dist-*\n/dist\n/dist-debug\n/artifacts\n/updates\n/resources/winsetup/generated.wxs\n/resources/winsetup/obj\n/resources/winsetup/bin\n/resources/win-chocolatey/tools/chocolateyinstall.ps1\n.vs\n*.msi\n*.nupkg\ntest/fixtures/**/.fbkpm\n/tmp/\n/__tests__/fixtures/**/_*\n/__tests__/fixtures/request-cache/GET/localhost/.bin\n.idea\n.pika-meta\n.pnp.js\n.pnp\n/packages/lockfile/index.js\n.vscode/\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n    \"singleQuote\": true,\n    \"trailingComma\": \"all\",\n    \"bracketSpacing\": false,\n    \"printWidth\": 120\n  }\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to making participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, sex characteristics, gender identity and expression,\nlevel of experience, education, socio-economic status, nationality, personal\nappearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or\n advances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic\n address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces\nwhen an individual is representing the project or its community. Examples of\nrepresenting a project or community include using an official project e-mail\naddress, posting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event. Representation of a project may be\nfurther defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at fkschott@gmail.com. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see\nhttps://www.contributor-covenant.org/faq\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to @pika/pack\n\nAll contributions are welcome! \n\n## Building the Project\n\nIt is very cool being able to use @pika/pack to build @pika/pack. Unfortunately, npm doesn't make it easy to install a package as a dependency of itself. So to get around this, we keep a `checkpoint/` folder in the project which is a checkpoint build of a working @pika/pack. We then use this to build our package in development.\n\n```\ngit clone https://github.com/pikapkg/pack.git\nnpm install\nnpm run build\n```\n\n## Testing the Project\n\nWriting unit tests for the project is still TODO. I know, I know, I'm more embarassed than anyone. \n\nThe good news is that we have several example projects, including @pika/pack itself. First I'd like to get Travis running builds of all of our example projects with the PR'd version of @pika/pack. Until then, our only automated test is to use @pika/pack to build @pika/pack.\n\n```\nnpm t\n```\n"
  },
  {
    "path": "LICENSE",
    "content": "\"\"\"\nThe MIT License\n\nCopyright (c) 2019 Fred K. Schott\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies 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,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\n\n\nThis license applies to parts of @pika/pack originating from the\nhttps://github.com/sindresorhus/np repository:\n\n\"\"\"\nMIT License\n\nCopyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n\nThis license applies to parts of @pika/pack originating from the\nhttps://github.com/yarnpkg/yarn repository:\n\n\"\"\"\nBSD 2-Clause License\n\nFor Yarn software\n\nCopyright (c) 2016-present, Yarn Contributors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <img alt=\"Logo\" src=\"https://www.pika.dev/static/img/pika-pack-logo.jpg\" width=\"280\">\n</p>\n\n<p align=\"center\">\n  <strong>@pika/pack</strong> • npm package building, reimagined.\n</p>\n\n<p align=\"center\">\n  <img alt=\"Demo\" src=\"https://www.pika.dev/static/img/pack-build-demo.gif\" width=\"720\">\n</p>\n\n\n## @pika/pack helps you build amazing packages without the hassle:\n\n- **Simple** &nbsp;⚡️&nbsp; Use pre-configured plugins to build your package for you.\n- **Flexible** &nbsp;🏋️‍♀️&nbsp; Choose plugins and optimizations to match your needs.\n- **Holistic** &nbsp;⚛️&nbsp; Let us build the entire package... *including package.json.*\n\n\n## Quickstart\n\n```bash\nnpx @pika/pack                           # Run once.\nnpm install --dev @pika/pack             # Or, run multiple times using \"pika pack\" in any package.json scripts\n```\n\n😎🆒! So now what? If you run `pika build` with an empty pipeline, you'll get an empty package build. **@pika/pack** lets you connect pre-configured plugins to build and optimize your package for you. Plugins wrap already-popular tools like Babel and Rollup with npm-optimized config options, removing the need to fiddle with much (if any) configuration yourself. You even get a generated package.json manifest configured for you ***automatically***.\n\n### 1. Create a project pipeline out of simple, pluggable builders.\n\n```js\n// Before: Your top-level package.json manifest:\n{\n  \"name\": \"simple-package\",\n  \"version\": \"1.0.0\",\n  \"@pika/pack\": {\n    \"pipeline\": [\n      [\"@pika/plugin-standard-pkg\", {\"exclude\": [\"__tests__/**/*\"]}],\n      [\"@pika/plugin-build-node\"],\n      [\"@pika/plugin-build-web\"],\n      [\"@pika/plugin-build-types\"]\n    ]\n  }\n}\n```\n\nBuilders are simple, single-purpose build plugins defined in your `package.json`. For example, `@pika/plugin-build-node` & `@pika/plugin-build-web` build your package for those different environments. Other, more interesting builders can bundle your web build for [unpkg](https://unpkg.com), generate TypeScript definitions from your JavaScript, addon a standard CLI wrapper for Node.js builds, and even compile non-JS languages to WASM (with JS bindings added).\n\n### 2. Builders handle everything, including package configuration.\n\n```js\n// After: your built \"pkg/\" package.json manifest:\n{\n  \"name\": \"simple-package\",\n  \"version\": \"1.0.0\",\n  // Multiple distributions, built & configured automatically:\n  \"esnext\": \"dist-src/index.js\",\n  \"main\": \"dist-node/index.js\",\n  \"module\": \"dist-web/index.js\",\n  \"types\": \"dist-types/index.d.ts\",\n  // With sensible package defaults:\n  \"sideEffects\": false,\n  \"files\": [\"dist-*/\", \"assets/\", \"bin/\"]\n}\n```\n\nThis is all possible because **@pika/pack** builds your entire package: code, assets, and even package.json manifest. By building the entire package, you end up with a fully-built `pkg/` directory, ready to publish. Entry points like \"main\", \"module\", \"umd:main\", \"types\", \"unpkg\", \"files\", and even advanced options like \"sideEffects\" are all handled by your build pipeline.\n\n\n## Build Plugins\n\n**[Check out the full list](https://github.com/pikapkg/builders)** of official & community-written @pika/pack plugins!\n\n\n## Lerna Support\n\nCurious about integrating @pika/pack with Lerna? Our official collection of plugins is a Lerna repo that uses @pika/pack to build each package! [Check it out](https://github.com/pikapkg/builders) to see how easy it is to use the two tools together.\n"
  },
  {
    "path": "checkpoint/LICENSE",
    "content": "\"\"\"\nThe MIT License\n\nCopyright (c) 2019 Fred K. Schott\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies 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,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\n\n\nThis license applies to parts of @pika/pack originating from the\nhttps://github.com/sindresorhus/np repository:\n\n\"\"\"\nMIT License\n\nCopyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n\nThis license applies to parts of @pika/pack originating from the\nhttps://github.com/yarnpkg/yarn repository:\n\n\"\"\"\nBSD 2-Clause License\n\nFor Yarn software\n\nCopyright (c) 2016-present, Yarn Contributors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\n"
  },
  {
    "path": "checkpoint/README.md",
    "content": "<p align=\"center\">\n  <img alt=\"Logo\" src=\"https://next.pikapkg.com/static/img/new-logo1.png\" width=\"280\">\n</p>\n\n<p align=\"center\">\n  <strong>@pika/pack</strong> • npm package building, reimagined.\n</p>\n\n<p align=\"center\">\n  <img alt=\"Demo\" src=\"https://next.pikapkg.com/static/img/pack-build-demo.gif?\" width=\"720\">\n</p>\n\n\n## @pika/pack helps you build amazing packages without the hassle:\n\n- **Simple** &nbsp;⚡️&nbsp; Use pre-configured plugins to build your package for you.\n- **Flexible** &nbsp;🏋️‍♀️&nbsp; Choose plugins and optimizations to match your needs.\n- **Holistic** &nbsp;⚛️&nbsp; Let us build the entire package... *including package.json.*\n\n\n## Quickstart\n\nGetting started is easy:\n\n```js\n// 1. Install it!\n$ npm install -g @pika/pack\n// 2. Add this to your package.json manifest:\n\"@pika/pack\": {\n  \"pipeline\": []\n}\n// 3. Run it!\n$ pack build\n```\n\n### 😎 🆒\n\nSo now what? If you run `pack build` with an empty pipeline, you'll get an empty package build. **@pika/pack** lets you connect pre-configured plugins to build and optimize your package for you. Plugins wrap already-popular tools like Babel and Rollup with npm-optimized config options, removing the need to fiddle with much (if any) configuration yourself. You even get a generated package.json manifest configured for you ***automatically***.\n\n### 1. Create a project pipeline out of simple, pluggable builders.\n\n```js\n// Before: Your top-level package.json manifest:\n{\n  \"name\": \"simple-package\",\n  \"version\": \"1.0.0\",\n  \"@pika/pack\": {\n    \"pipeline\": [\n      [\"@pika/plugin-standard-pkg\", {\"exclude\": [\"__tests__/**/*\"]}],\n      [\"@pika/plugin-build-node\"],\n      [\"@pika/plugin-build-web\"],\n      [\"@pika/plugin-build-types\"]\n    ]\n  }\n}\n```\n\nBuilders are simple, single-purpose build plugins defined in your `package.json`. For example, `@pika/plugin-build-node` & `@pika/plugin-build-web` build your package for those different environments. Other, more interesting builders can bundle your web build for [unpkg](https://unpkg.com), generate TypeScript definitions from your JavaScript, addon a standard CLI wrapper for Node.js builds, and even compile non-JS languages to WASM (with JS bindings added).\n\n### 2. Builders handle everything, including package configuration.\n\n```js\n// After: your built \"pkg/\" package.json manifest:\n{\n  \"name\": \"simple-package\",\n  \"version\": \"1.0.0\",\n  // Multiple distributions, built & configured automatically:\n  \"esnext\": \"dist-src/index.js\",\n  \"main\": \"dist-node/index.js\",\n  \"module\": \"dist-web/index.js\",\n  \"types\": \"dist-types/index.d.ts\",\n  // With sensible package defaults:\n  \"sideEffects\": false,\n  \"files\": [\"dist-*/\", \"assets/\", \"bin/\"]\n}\n```\n\nThis is all possible because **@pika/pack** builds your entire package: code, assets, and even package.json manifest. By building the entire package, you end up with a fully-built `pkg/` directory, ready to publish. Entry points like \"main\", \"module\", \"umd:main\", \"types\", \"unpkg\", \"files\", and even advanced options like \"sideEffects\" are all handled by your build pipeline.\n\n\n## Build Plugins\n\n**[Check out the full list](https://github.com/pikapkg/builders)** of official & community-written @pika/pack plugins!\n\n\n## Lerna Support\n\nCurious about integrating @pika/pack with Lerna? Our official collection of plugins is a Lerna repo that uses @pika/pack to build each package! [Check it out](https://github.com/pikapkg/builders) to see how easy it is to use the two tools together.\n"
  },
  {
    "path": "checkpoint/dist-node/index.bin.js",
    "content": "#!/usr/bin/env node\n'use strict';\n\nconst ver = process.versions.node;\nconst majorVer = parseInt(ver.split('.')[0], 10);\n\nif (majorVer < 8) {\n  console.error('Node version ' + ver + ' is not supported, please use Node.js 8.0 or higher.');\n  process.exit(1);\n}\n\nlet hasBundled = true    \n\ntry {\n  require.resolve('./index.bundled.js');\n} catch(err) {\n  // We don't have/need this on legacy builds and dev builds\n  // If an error happens here, throw it, that means no Node.js distribution exists at all.\n  hasBundled = false;\n}\n\nconst cli = !hasBundled ? require('../') : require('./index.bundled.js');\n\nif (cli.autoRun) {\n  return;\n}\n\nconst run = cli.run || cli.cli || cli.default;\nrun(process.argv).catch(function (error) {\n  console.error(error.stack || error.message || error);\n  process.exitCode = 1;\n});\n"
  },
  {
    "path": "checkpoint/dist-node/index.js",
    "content": "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar path = require('path');\nvar chalk = _interopDefault(require('chalk'));\nvar fs = require('fs');\nvar invariant = _interopDefault(require('invariant'));\nvar loudRejection = _interopDefault(require('loud-rejection'));\nvar readline = require('readline');\nvar stripAnsi = _interopDefault(require('strip-ansi'));\nvar util = require('util');\nrequire('camelcase');\nvar isCI = require('is-ci');\nvar os = require('os');\nvar events = require('events');\nvar tty = require('tty');\nvar _rimraf = _interopDefault(require('rimraf'));\nvar _mkdirp = _interopDefault(require('mkdirp'));\nvar _glob = _interopDefault(require('glob'));\nvar stripBOM = _interopDefault(require('strip-bom'));\nvar types = require('@pika/types');\nvar isBuiltinModule = _interopDefault(require('is-builtin-module'));\nvar validateLicense = _interopDefault(require('validate-npm-package-license'));\nvar semver = _interopDefault(require('semver'));\nvar nodeUrl = require('url');\nvar child_process = require('child_process');\nvar importFrom = _interopDefault(require('import-from'));\nvar uri2path = _interopDefault(require('file-uri-to-path'));\nvar yargs = _interopDefault(require('yargs-parser'));\n\n/* @flow */\nfunction removeSuffix(pattern, suffix) {\n  if (pattern.endsWith(suffix)) {\n    return pattern.slice(0, -suffix.length);\n  }\n\n  return pattern;\n}\n\nfunction formatFunction(...strs) {\n  return strs.join(' ');\n}\n\nconst defaultFormatter = {\n  bold: formatFunction,\n  dim: formatFunction,\n  italic: formatFunction,\n  underline: formatFunction,\n  inverse: formatFunction,\n  strikethrough: formatFunction,\n  black: formatFunction,\n  red: formatFunction,\n  green: formatFunction,\n  yellow: formatFunction,\n  blue: formatFunction,\n  magenta: formatFunction,\n  cyan: formatFunction,\n  white: formatFunction,\n  gray: formatFunction,\n  grey: formatFunction,\n  stripColor: formatFunction\n};\n\nconst messages = {\n  upToDate: 'Already up-to-date.',\n  folderInSync: 'Folder in sync.',\n  nothingToInstall: 'Nothing to install.',\n  resolvingPackages: 'Resolving packages',\n  checkingManifest: 'Validating package.json',\n  fetchingPackages: 'Fetching packages',\n  linkingDependencies: 'Linking dependencies',\n  rebuildingPackages: 'Rebuilding all packages',\n  buildingFreshPackages: 'Building fresh packages',\n  cleaningModules: 'Cleaning modules',\n  bumpingVersion: 'Bumping version',\n  savingHar: 'Saving HAR file: $0',\n  answer: 'Answer?',\n  usage: 'Usage',\n  installCommandRenamed: '`install` has been replaced with `add` to add new dependencies. Run $0 instead.',\n  globalFlagRemoved: '`--global` has been deprecated. Please run $0 instead.',\n  waitingInstance: 'Waiting for the other pika instance to finish (pid $0, inside $1)',\n  waitingNamedInstance: 'Waiting for the other pika instance to finish ($0)',\n  offlineRetrying: 'There appears to be trouble with your network connection. Retrying...',\n  internalServerErrorRetrying: 'There appears to be trouble with the npm registry (returned $1). Retrying...',\n  clearedCache: 'Cleared cache.',\n  couldntClearPackageFromCache: \"Couldn't clear package $0 from cache\",\n  clearedPackageFromCache: 'Cleared package $0 from cache',\n  packWroteTarball: 'Wrote tarball to $0.',\n  helpExamples: '  Examples:\\n$0\\n',\n  helpCommands: '  Commands:\\n$0\\n',\n  helpCommandsMore: '  Run `$0` for more information on specific commands.',\n  helpLearnMore: '  Visit $0 to learn more about Pika.\\n',\n  manifestPotentialTypo: 'Potential typo $0, did you mean $1?',\n  manifestBuiltinModule: '$0 is also the name of a node core module',\n  manifestNameDot: \"Name can't start with a dot\",\n  manifestNameIllegalChars: 'Name contains illegal characters',\n  manifestNameBlacklisted: 'Name is blacklisted',\n  manifestLicenseInvalid: 'License should be a valid SPDX license expression',\n  manifestLicenseNone: 'No license field',\n  manifestStringExpected: '$0 is not a string',\n  manifestDependencyCollision: '$0 has dependency $1 with range $2 that collides with a dependency in $3 of the same name with version $4',\n  manifestDirectoryNotFound: 'Unable to read $0 directory of module $1',\n  verboseFileCopy: 'Copying $0 to $1.',\n  verboseFileLink: 'Creating hardlink at $0 to $1.',\n  verboseFileSymlink: 'Creating symlink at $0 to $1.',\n  verboseFileSkip: 'Skipping copying of file $0 as the file at $1 is the same size ($2) and mtime ($3).',\n  verboseFileSkipSymlink: 'Skipping copying of $0 as the file at $1 is the same symlink ($2).',\n  verboseFileSkipHardlink: 'Skipping copying of $0 as the file at $1 is the same hardlink ($2).',\n  verboseFileRemoveExtraneous: 'Removing extraneous file $0.',\n  verboseFilePhantomExtraneous: \"File $0 would be marked as extraneous but has been removed as it's listed as a phantom file.\",\n  verboseFileSkipArtifact: 'Skipping copying of $0 as the file is marked as a built artifact and subject to change.',\n  verboseFileFolder: 'Creating directory $0.',\n  verboseRequestStart: 'Performing $0 request to $1.',\n  verboseRequestFinish: 'Request $0 finished with status code $1.',\n  configSet: 'Set $0 to $1.',\n  configDelete: 'Deleted $0.',\n  configNpm: 'npm config',\n  configPika: 'pika config',\n  couldntFindPackagejson: \"Couldn't find a package.json file in $0\",\n  couldntFindMatch: \"Couldn't find match for $0 in $1 for $2.\",\n  couldntFindPackageInCache: \"Couldn't find any versions for $0 that matches $1 in our cache (possible versions are $2). This is usually caused by a missing entry in the lockfile, running Pika without the --offline flag may help fix this issue.\",\n  couldntFindVersionThatMatchesRange: \"Couldn't find any versions for $0 that matches $1\",\n  chooseVersionFromList: 'Please choose a version of $0 from this list:',\n  moduleNotInManifest: \"This module isn't specified in a package.json file.\",\n  moduleAlreadyInManifest: '$0 is already in $1. Please remove existing entry first before adding it to $2.',\n  unknownFolderOrTarball: \"Passed folder/tarball doesn't exist,\",\n  unknownPackage: \"Couldn't find package $0.\",\n  unknownPackageName: \"Couldn't find package name.\",\n  unknownUser: \"Couldn't find user $0.\",\n  unknownRegistryResolver: 'Unknown registry resolver $0',\n  userNotAnOwner: \"User $0 isn't an owner of this package.\",\n  invalidVersionArgument: 'Use the $0 flag to create a new version.',\n  invalidVersion: 'Invalid version supplied.',\n  requiredVersionInRange: 'Required version in range.',\n  packageNotFoundRegistry: \"Couldn't find package $0 on the $1 registry.\",\n  requiredPackageNotFoundRegistry: \"Couldn't find package $0 required by $1 on the $2 registry.\",\n  doesntExist: \"Package $1 refers to a non-existing file '$0'.\",\n  missingRequiredPackageKey: `Package $0 doesn't have a $1.`,\n  invalidAccess: 'Invalid argument for access, expected public or restricted.',\n  invalidCommand: 'Invalid subcommand. Try $0',\n  invalidGistFragment: 'Invalid gist fragment $0.',\n  invalidHostedGitFragment: 'Invalid hosted git fragment $0.',\n  invalidFragment: 'Invalid fragment $0.',\n  invalidPackageName: 'Invalid package name.',\n  invalidPackageVersion: \"Can't add $0: invalid package version $1.\",\n  couldntFindManifestIn: \"Couldn't find manifest in $0.\",\n  shrinkwrapWarning: 'npm-shrinkwrap.json found. This will not be updated or respected. See https://yarnpkg.com/en/docs/migrating-from-npm for more information.',\n  npmLockfileWarning: 'package-lock.json found. Your project contains lock files generated by tools other than Pika. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json.',\n  lockfileOutdated: 'Outdated lockfile. Please run `pika install` and try again.',\n  lockfileMerged: 'Merge conflict detected in pika.lock and successfully merged.',\n  lockfileConflict: 'A merge conflict was found in pika.lock but it could not be successfully merged, regenerating pika.lock from scratch.',\n  ignoredScripts: 'Ignored scripts due to flag.',\n  missingAddDependencies: 'Missing list of packages to add to your project.',\n  yesWarning: 'The yes flag has been set. This will automatically answer yes to all questions, which may have security implications.',\n  networkWarning: \"You don't appear to have an internet connection. Try the --offline flag to use the cache for registry queries.\",\n  flatGlobalError: 'The package $0 requires a flat dependency graph. Add `\"flat\": true` to your package.json and try again.',\n  noName: `Package doesn't have a name.`,\n  noVersion: `Package doesn't have a version.`,\n  answerRequired: 'An answer is required.',\n  missingWhyDependency: 'Missing package name, folder or path to file to identify why a package has been installed',\n  bugReport: 'If you think this is a bug, please open a bug report with the information provided in $0.',\n  unexpectedError: 'An unexpected error occurred: $0.',\n  jsonError: 'Error parsing JSON at $0, $1.',\n  noPermission: 'Cannot create $0 due to insufficient permissions.',\n  noGlobalFolder: 'Cannot find a suitable global folder. Tried these: $0',\n  allDependenciesUpToDate: 'All of your dependencies are up to date.',\n  legendColorsForVersionUpdates: 'Color legend : \\n $0    : Major Update backward-incompatible updates \\n $1 : Minor Update backward-compatible features \\n $2  : Patch Update backward-compatible bug fixes',\n  frozenLockfileError: 'Your lockfile needs to be updated, but pika was run with `--frozen-lockfile`.',\n  fileWriteError: 'Could not write file $0: $1',\n  fileDeleteError: 'Could not delete file $0: $1',\n  multiplePackagesCantUnpackInSameDestination: 'Pattern $0 is trying to unpack in the same destination $1 as pattern $2. This could result in non-deterministic behavior, skipping.',\n  incorrectLockfileEntry: 'Lockfile has incorrect entry for $0. Ignoring it.',\n  invalidResolutionName: 'Resolution field $0 does not end with a valid package name and will be ignored',\n  invalidResolutionVersion: 'Resolution field $0 has an invalid version entry and may be ignored',\n  incompatibleResolutionVersion: 'Resolution field $0 is incompatible with requested version $1',\n  pikaOutdated: \"Your current version of Pika is out of date. The latest version is $0, while you're on $1.\",\n  pikaOutdatedInstaller: 'To upgrade, download the latest installer at $0.',\n  pikaOutdatedCommand: 'To upgrade, run the following command:',\n  tooManyArguments: 'Too many arguments, maximum of $0.',\n  tooFewArguments: 'Not enough arguments, expected at least $0.',\n  noArguments: \"This command doesn't require any arguments.\",\n  ownerRemoving: 'Removing owner $0 from package $1.',\n  ownerRemoved: 'Owner removed.',\n  ownerRemoveError: \"Couldn't remove owner.\",\n  ownerGetting: 'Getting owners for package $0',\n  ownerGettingFailed: \"Couldn't get list of owners.\",\n  ownerAlready: 'This user is already an owner of this package.',\n  ownerAdded: 'Added owner.',\n  ownerAdding: 'Adding owner $0 to package $1',\n  ownerAddingFailed: \"Couldn't add owner.\",\n  ownerNone: 'No owners.',\n  teamCreating: 'Creating team',\n  teamRemoving: 'Removing team',\n  teamAddingUser: 'Adding user to team',\n  teamRemovingUser: 'Removing user from team',\n  teamListing: 'Listing teams',\n  distFailed: `⚠️  Distribution \"$0\" failed to build: $1 $2`,\n  distExiting: `   Exiting...`,\n  distContinuing: `   Continuing...`,\n  cleaning: 'Cleaning modules',\n  cleanCreatingFile: 'Creating $0',\n  cleanCreatedFile: 'Created $0. Please review the contents of this file then run \"pika autoclean --force\" to perform a clean.',\n  cleanAlreadyExists: '$0 already exists. To revert to the default file, delete $0 then rerun this command.',\n  cleanRequiresForce: 'This command required the \"--force\" flag to perform the clean. This is a destructive operation. Files specified in $0 will be deleted.',\n  cleanDoesNotExist: '$0 does not exist. Autoclean will delete files specified by $0. Run \"autoclean --init\" to create $0 with the default entries.',\n  binLinkCollision: \"There's already a linked binary called $0 in your global Pika bin. Could not link this package's $0 bin entry.\",\n  linkCollision: \"There's already a package called $0 registered. This command has had no effect. If this command was run in another folder with the same name, the other folder is still linked. Please run pika unlink in the other folder if you want to register this folder.\",\n  linkMissing: 'No registered package found called $0.',\n  linkRegistered: 'Registered $0.',\n  linkRegisteredMessage: 'You can now run `pika link $0` in the projects where you want to use this package and it will be used instead.',\n  linkUnregistered: 'Unregistered $0.',\n  linkUnregisteredMessage: 'You can now run `pika unlink $0` in the projects where you no longer want to use this package.',\n  linkUsing: 'Using linked package for $0.',\n  linkDisusing: 'Removed linked package $0.',\n  linkDisusingMessage: 'You will need to run `pika` to re-install the package that was linked.',\n  linkTargetMissing: 'The target of linked package $0 is missing. Removing link.',\n  createInvalidBin: 'Invalid bin entry found in package $0.',\n  createMissingPackage: 'Package not found - this is probably an internal error, and should be reported at https://github.com/yarnpkg/yarn/issues.',\n  workspacesAddRootCheck: 'Running this command will add the dependency to the workspace root rather than the workspace itself, which might not be what you want - if you really meant it, make it explicit by running this command again with the -W flag (or --ignore-workspace-root-check).',\n  workspacesRemoveRootCheck: 'Running this command will remove the dependency from the workspace root rather than the workspace itself, which might not be what you want - if you really meant it, make it explicit by running this command again with the -W flag (or --ignore-workspace-root-check).',\n  workspacesFocusRootCheck: 'This command can only be run inside an individual workspace.',\n  workspacesRequirePrivateProjects: 'Workspaces can only be enabled in private projects.',\n  workspacesSettingMustBeArray: 'The workspaces field in package.json must be an array.',\n  workspacesDisabled: 'Your project root defines workspaces but the feature is disabled in your Pika config. Please check \"workspaces-experimental\" in your .pikarc file.',\n  workspacesNohoistRequirePrivatePackages: 'nohoist config is ignored in $0 because it is not a private package. If you think nohoist should be allowed in public packages, please submit an issue for your use case.',\n  workspacesNohoistDisabled: `$0 defines nohoist but the feature is disabled in your Pika config (\"workspaces-nohoist-experimental\" in .pikarc file)`,\n  workspaceRootNotFound: \"Cannot find the root of your workspace - are you sure you're currently in a workspace?\",\n  workspaceMissingWorkspace: 'Missing workspace name.',\n  workspaceMissingCommand: 'Missing command name.',\n  workspaceUnknownWorkspace: 'Unknown workspace $0.',\n  workspaceVersionMandatory: 'Missing version in workspace at $0, ignoring.',\n  workspaceNameMandatory: 'Missing name in workspace at $0, ignoring.',\n  workspaceNameDuplicate: 'There are more than one workspace with name $0',\n  cacheFolderSkipped: 'Skipping preferred cache folder $0 because it is not writable.',\n  cacheFolderMissing: \"Pika hasn't been able to find a cache folder it can use. Please use the explicit --cache-folder option to tell it what location to use, or make one of the preferred locations writable.\",\n  cacheFolderSelected: 'Selected the next writable cache folder in the list, will be $0.',\n  execMissingCommand: 'Missing command name.',\n  noScriptsAvailable: 'There are no scripts specified inside package.json.',\n  noBinAvailable: 'There are no binary scripts available.',\n  dashDashDeprecation: `From Pika 1.0 onwards, scripts don't require \"--\" for options to be forwarded. In a future version, any explicit \"--\" will be forwarded as-is to the scripts.`,\n  commandNotSpecified: 'No command specified.',\n  binCommands: 'Commands available from binary scripts: ',\n  possibleCommands: 'Project commands',\n  commandQuestion: 'Which command would you like to run?',\n  commandFailedWithCode: 'Command failed with exit code $0.',\n  commandFailedWithSignal: 'Command failed with signal $0.',\n  packageRequiresNodeGyp: 'This package requires node-gyp, which is not currently installed. Pika will attempt to automatically install it. If this fails, you can run \"pika global add node-gyp\" to manually install it.',\n  nodeGypAutoInstallFailed: 'Failed to auto-install node-gyp. Please run \"pika global add node-gyp\" manually. Error: $0',\n  foundIncompatible: 'Found incompatible module',\n  incompatibleEngine: 'The engine $0 is incompatible with this module. Expected version $1. Got $2',\n  incompatibleCPU: 'The CPU architecture $0 is incompatible with this module.',\n  incompatibleOS: 'The platform $0 is incompatible with this module.',\n  invalidEngine: 'The engine $0 appears to be invalid.',\n  optionalCompatibilityExcluded: '$0 is an optional dependency and failed compatibility check. Excluding it from installation.',\n  optionalModuleFail: 'This module is OPTIONAL, you can safely ignore this error',\n  optionalModuleScriptFail: 'Error running install script for optional dependency: $0',\n  optionalModuleCleanupFail: 'Could not cleanup build artifacts from failed install: $0',\n  unmetPeer: '$0 has unmet peer dependency $1.',\n  incorrectPeer: '$0 has incorrect peer dependency $1.',\n  selectedPeer: 'Selecting $1 at level $2 as the peer dependency of $0.',\n  missingBundledDependency: '$0 is missing a bundled dependency $1. This should be reported to the package maintainer.',\n  savedNewDependency: 'Saved 1 new dependency.',\n  savedNewDependencies: 'Saved $0 new dependencies.',\n  directDependencies: 'Direct dependencies',\n  allDependencies: 'All dependencies',\n  foundWarnings: 'Found $0 warnings.',\n  foundErrors: 'Found $0 errors.',\n  savedLockfile: 'Saved lockfile.',\n  noRequiredLockfile: 'No lockfile in this directory. Run `pika install` to generate one.',\n  noLockfileFound: 'No lockfile found.',\n  invalidSemver: 'Invalid semver version',\n  newVersion: 'New version',\n  currentVersion: 'Current version',\n  noVersionOnPublish: 'Proceeding with current version',\n  manualVersionResolution: 'Unable to find a suitable version for $0, please choose one by typing one of the numbers below:',\n  manualVersionResolutionOption: '$0 which resolved to $1',\n  createdTag: 'Created tag.',\n  createdTagFail: \"Couldn't add tag.\",\n  deletedTag: 'Deleted tag.',\n  deletedTagFail: \"Couldn't delete tag.\",\n  gettingTags: 'Getting tags',\n  deletingTags: 'Deleting tag',\n  creatingTag: 'Creating tag $0 = $1',\n  whyStart: 'Why do we have the module $0?',\n  whyFinding: 'Finding dependency',\n  whyCalculating: 'Calculating file sizes',\n  whyUnknownMatch: \"We couldn't find a match!\",\n  whyInitGraph: 'Initialising dependency graph',\n  whyWhoKnows: \"We don't know why this module exists\",\n  whyDiskSizeWithout: 'Disk size without dependencies: $0',\n  whyDiskSizeUnique: 'Disk size with unique dependencies: $0',\n  whyDiskSizeTransitive: 'Disk size with transitive dependencies: $0',\n  whySharedDependencies: 'Number of shared dependencies: $0',\n  whyHoistedTo: `Has been hoisted to $0`,\n  whyHoistedFromSimple: `This module exists because it's hoisted from $0.`,\n  whyNotHoistedSimple: `This module exists here because it's in the nohoist list $0.`,\n  whyDependedOnSimple: `This module exists because $0 depends on it.`,\n  whySpecifiedSimple: `This module exists because it's specified in $0.`,\n  whyReasons: 'Reasons this module exists',\n  whyHoistedFrom: 'Hoisted from $0',\n  whyNotHoisted: `in the nohoist list $0`,\n  whyDependedOn: '$0 depends on it',\n  whySpecified: `Specified in $0`,\n  whyMatch: `\\r=> Found $0`,\n  uninstalledPackages: 'Uninstalled packages.',\n  uninstallRegenerate: 'Regenerating lockfile and installing missing dependencies',\n  cleanRemovedFiles: 'Removed $0 files',\n  cleanSavedSize: 'Saved $0 MB.',\n  configFileFound: 'Found configuration file $0.',\n  configPossibleFile: 'Checking for configuration file $0.',\n  npmUsername: 'npm username',\n  npmPassword: 'npm password',\n  npmEmail: 'npm email',\n  npmOneTimePassword: 'npm one-time password',\n  loggingIn: 'Logging in',\n  loggedIn: 'Logged in.',\n  notRevokingEnvToken: 'Not revoking login token, specified via environment variable.',\n  notRevokingConfigToken: 'Not revoking login token, specified via config file.',\n  noTokenToRevoke: 'No login token to revoke.',\n  revokingToken: 'Revoking token',\n  revokedToken: 'Revoked login token.',\n  loginAsPublic: 'Logging in as public',\n  incorrectCredentials: 'Incorrect username or password.',\n  incorrectOneTimePassword: 'Incorrect one-time password.',\n  twoFactorAuthenticationEnabled: 'Two factor authentication enabled.',\n  clearedCredentials: 'Cleared login credentials.',\n  publishFail: \"Couldn't publish package: $0\",\n  publishPrivate: 'Package marked as private, not publishing.',\n  published: 'Published.',\n  publishing: 'Publishing',\n  nonInteractiveNoVersionSpecified: 'You must specify a new version with --new-version when running with --non-interactive.',\n  nonInteractiveNoToken: \"No token found and can't prompt for login when running with --non-interactive.\",\n  infoFail: 'Received invalid response from npm.',\n  malformedRegistryResponse: 'Received malformed response from registry for $0. The registry may be down.',\n  registryNoVersions: 'No valid versions found for $0. The package may be unpublished.',\n  cantRequestOffline: \"Can't make a request in offline mode ($0)\",\n  requestManagerNotSetupHAR: 'RequestManager was not setup to capture HAR files',\n  requestError: 'Request $0 returned a $1',\n  requestFailed: 'Request failed $0',\n  tarballNotInNetworkOrCache: '$0: Tarball is not in network and can not be located in cache ($1)',\n  fetchBadHashWithPath: \"Integrity check failed for $0 (computed integrity doesn't match our records, got $2)\",\n  fetchBadIntegrityAlgorithm: 'Integrity checked failed for $0 (none of the specified algorithms are supported)',\n  fetchErrorCorrupt: '$0. Mirror tarball appears to be corrupt. You can resolve this by running:\\n\\n  rm -rf $1\\n  pika install',\n  errorExtractingTarball: 'Extracting tar content of $1 failed, the file appears to be corrupt: $0',\n  updateInstalling: 'Installing $0...',\n  hostedGitResolveError: 'Error connecting to repository. Please, check the url.',\n  unknownFetcherFor: 'Unknown fetcher for $0',\n  downloadGitWithoutCommit: 'Downloading the git repo $0 over plain git without a commit hash',\n  downloadHTTPWithoutCommit: 'Downloading the git repo $0 over HTTP without a commit hash',\n  unplugDisabled: \"Packages can only be unplugged when Plug'n'Play is enabled.\",\n  plugnplayWindowsSupport: \"Plug'n'Play on Windows doesn't support the cache and project to be kept on separate drives\",\n  packageInstalledWithBinaries: 'Installed $0 with binaries:',\n  packageHasBinaries: '$0 has binaries:',\n  packageHasNoBinaries: '$0 has no binaries',\n  packageBinaryNotFound: \"Couldn't find a binary named $0\",\n  couldBeDeduped: '$0 could be deduped from $1 to $2',\n  lockfileNotContainPattern: 'Lockfile does not contain pattern: $0',\n  integrityCheckFailed: 'Integrity check failed',\n  noIntegrityFile: \"Couldn't find an integrity file\",\n  integrityFailedExpectedIsNotAJSON: 'Integrity check: integrity file is not a json',\n  integrityCheckLinkedModulesDontMatch: \"Integrity check: Linked modules don't match\",\n  integrityFlagsDontMatch: \"Integrity check: Flags don't match\",\n  integrityLockfilesDontMatch: \"Integrity check: Lock files don't match\",\n  integrityFailedFilesMissing: 'Integrity check: Files are missing',\n  integrityPatternsDontMatch: \"Integrity check: Top level patterns don't match\",\n  integrityModulesFoldersMissing: 'Integrity check: Some module folders are missing',\n  integritySystemParamsDontMatch: \"Integrity check: System parameters don't match\",\n  packageNotInstalled: '$0 not installed',\n  optionalDepNotInstalled: 'Optional dependency $0 not installed',\n  packageWrongVersion: '$0 is wrong version: expected $1, got $2',\n  packageDontSatisfy: \"$0 doesn't satisfy found match of $1\",\n  lockfileExists: 'Lockfile already exists, not migrating.',\n  pikaManifestExists: 'pika.package.json manifest already exists, not migrating.',\n  noManifestExists: 'No package.json manifest found. Run `pika init` to generate a new pika.package.json manifest.',\n  skippingImport: 'Skipping import of $0 for $1',\n  importFailed: 'Import of $0 for $1 failed, resolving normally.',\n  importResolveFailed: 'Import of $0 failed starting in $1',\n  importResolvedRangeMatch: 'Using version $0 of $1 instead of $2 for $3',\n  importSourceFilesCorrupted: 'Failed to import from package-lock.json, source file(s) corrupted',\n  importPackageLock: 'found npm package-lock.json, converting to pika.lock',\n  importYarnLock: 'found yarn.lock, converting to pika.lock',\n  importNodeModules: 'creating pika.lock from local node_modules folder',\n  packageContainsPikaAsGlobal: 'Installing Pika via Pika will result in you having two separate versions of Pika installed at the same time, which is not recommended. To update Pika please follow https://yarnpkg.com/en/docs/install .',\n  watchStarting: `Starting up`,\n  watchRunning: `Ready! Watching source tree for changes`,\n  watchRebuild: `Rebuilding...`,\n  watchError: `Build error!`,\n  noValidationErrors: `0 Validation Errors found.`,\n  validationErrors: `$0 Validation Error(s) found. Resolve before publishing.`,\n  scopeNotValid: 'The specified scope is not valid.',\n  deprecatedCommand: '$0 is deprecated. Please use $1.',\n  deprecatedListArgs: 'Filtering by arguments is deprecated. Please use the pattern option instead.',\n  implicitFileDeprecated: 'Using the \"file:\" protocol implicitly is deprecated. Please either prepend the protocol or prepend the path $0 with \"./\".',\n  unsupportedNodeVersion: 'You are using Node $0 which is not supported and may encounter bugs or unexpected behavior. Pika supports the following semver range: $1',\n  verboseUpgradeBecauseRequested: 'Considering upgrade of $0 to $1 because it was directly requested.',\n  verboseUpgradeBecauseOutdated: 'Considering upgrade of $0 to $1 because a newer version exists in the registry.',\n  verboseUpgradeNotUnlocking: 'Not unlocking $0 in the lockfile because it is a new or direct dependency.',\n  verboseUpgradeUnlocking: 'Unlocking $0 in the lockfile.',\n  folderMissing: \"Directory $0 doesn't exist\",\n  mutexPortBusy: 'Cannot use the network mutex on port $0. It is probably used by another app.',\n  auditRunning: 'Auditing packages',\n  auditSummary: '$0 vulnerabilities found - Packages audited: $1',\n  auditSummarySeverity: 'Severity:',\n  auditCritical: '$0 Critical',\n  auditHigh: '$0 High',\n  auditModerate: '$0 Moderate',\n  auditLow: '$0 Low',\n  auditInfo: '$0 Info',\n  auditResolveCommand: '# Run $0 to resolve $1 $2',\n  auditSemverMajorChange: 'SEMVER WARNING: Recommended action is a potentially breaking change',\n  auditManualReview: 'Manual Review\\nSome vulnerabilities require your attention to resolve\\n\\nVisit https://go.npm.me/audit-guide for additional guidance',\n  auditRunAuditForDetails: 'Security audit found potential problems. Run \"pika audit\" for additional details.',\n  auditOffline: 'Skipping audit. Security audit cannot be performed in offline mode.'\n};\n\n\n\nvar languages = /*#__PURE__*/Object.freeze({\n    en: messages\n});\n\nfunction stringifyLangArgs(args) {\n  return args.map(function (val) {\n    if (val != null && val.inspect) {\n      return val.inspect();\n    } else {\n      try {\n        const str = JSON.stringify(val) || val + ''; // should match all literal line breaks and\n        // \"u001b\" that follow an odd number of backslashes and convert them to ESC\n        // we do this because the JSON.stringify process has escaped these characters\n\n        return str.replace(/((?:^|[^\\\\])(?:\\\\{2})*)\\\\u001[bB]/g, '$1\\u001b').replace(/[\\\\]r[\\\\]n|([\\\\])?[\\\\]n/g, (match, precededBacklash) => {\n          // precededBacklash not null when \"\\n\" is preceded by a backlash (\"\\\\n\")\n          // match will be \"\\\\n\" and we don't replace it with os.EOL\n          return precededBacklash ? match : os.EOL;\n        });\n      } catch (e) {\n        return util.inspect(val);\n      }\n    }\n  });\n}\nclass BaseReporter {\n  constructor(opts = {}) {\n    const lang = 'en';\n    this.language = lang;\n    this.stdout = opts.stdout || process.stdout;\n    this.stderr = opts.stderr || process.stderr;\n    this.stdin = opts.stdin || this._getStandardInput();\n    this.emoji = !!opts.emoji;\n    this.nonInteractive = !!opts.nonInteractive;\n    this.noProgress = !!opts.noProgress || isCI;\n    this.isVerbose = !!opts.verbose; // @ts-ignore\n\n    this.isTTY = this.stdout.isTTY;\n    this.peakMemory = 0;\n    this.startTime = Date.now();\n    this.format = defaultFormatter;\n  }\n\n  lang(key, ...args) {\n    const msg = languages[this.language][key] || messages[key];\n\n    if (!msg) {\n      throw new ReferenceError(`No message defined for language key ${key}`);\n    } // stringify args\n\n\n    const stringifiedArgs = stringifyLangArgs(args); // replace $0 placeholders with args\n\n    return msg.replace(/\\$(\\d+)/g, (str, i) => {\n      return stringifiedArgs[i];\n    });\n  }\n  /**\n   * `stringifyLangArgs` run `JSON.stringify` on strings too causing\n   * them to appear quoted. This marks them as \"raw\" and prevents\n   * the quoting and escaping\n   */\n\n\n  rawText(str) {\n    return {\n      inspect() {\n        return str;\n      }\n\n    };\n  }\n\n  verbose(msg) {\n    if (this.isVerbose) {\n      this._verbose(msg);\n    }\n  }\n\n  verboseInspect(val) {\n    if (this.isVerbose) {\n      this._verboseInspect(val);\n    }\n  }\n\n  _verbose(msg) {}\n\n  _verboseInspect(val) {}\n\n  _getStandardInput() {\n    let standardInput; // Accessing stdin in a win32 headless process (e.g., Visual Studio) may throw an exception.\n\n    try {\n      standardInput = process.stdin;\n    } catch (e) {\n      console.warn(e.message);\n      delete process.stdin; // @ts-ignore\n\n      process.stdin = new events.EventEmitter();\n      standardInput = process.stdin;\n    }\n\n    return standardInput;\n  }\n\n  initPeakMemoryCounter() {\n    this.checkPeakMemory();\n    this.peakMemoryInterval = setInterval(() => {\n      this.checkPeakMemory();\n    }, 1000); // $FlowFixMe: Node's setInterval returns a Timeout, not a Number\n\n    this.peakMemoryInterval.unref();\n  }\n\n  checkPeakMemory() {\n    const {\n      heapTotal\n    } = process.memoryUsage();\n\n    if (heapTotal > this.peakMemory) {\n      this.peakMemory = heapTotal;\n    }\n  }\n\n  close() {\n    if (this.peakMemoryInterval) {\n      clearInterval(this.peakMemoryInterval);\n      this.peakMemoryInterval = null;\n    }\n  }\n\n  getTotalTime() {\n    return Date.now() - this.startTime;\n  } // TODO\n\n\n  list(key, items, hints) {} // Outputs basic tree structure to console\n\n\n  tree(key, obj, {\n    force = false\n  } = {}) {} // called whenever we begin a step in the CLI.\n\n\n  step(current, total, message, emoji) {} // a error message has been triggered. this however does not always meant an abrupt\n  // program end.\n\n\n  error(message) {} // an info message has been triggered. this provides things like stats and diagnostics.\n\n\n  info(message) {} // a warning message has been triggered.\n\n\n  warn(message) {} // a success message has been triggered.\n\n\n  success(message) {} // a simple log message\n  // TODO: rethink the {force} parameter. In the meantime, please don't use it (cf comments in #4143).\n\n\n  log(message, {\n    force = false\n  } = {}) {} // a shell command has been executed\n\n\n  command(command) {} // inspect and pretty-print any value\n\n\n  inspect(value) {} // the screen shown at the very start of the CLI\n\n\n  header(pkg) {} // the screen shown at the very end of the CLI\n\n\n  footer(showPeakMemory) {} // a table structure\n\n\n  table(head, body) {} // render an activity spinner and return a function that will trigger an update\n\n\n  activity() {\n    return {\n      tick(name) {},\n\n      end() {}\n\n    };\n  } //\n\n\n  activitySet(total, workers) {\n    return {\n      spinners: Array(workers).fill({\n        clear() {},\n\n        setPrefix() {},\n\n        tick() {},\n\n        end() {}\n\n      }),\n\n      end() {}\n\n    };\n  } // render a progress bar and return a function which when called will trigger an update\n\n\n  progress(total) {\n    return function () {};\n  } // utility function to disable progress bar\n\n\n  disableProgress() {\n    this.noProgress = true;\n  }\n\n}\n\n// public\nfunction sortTrees(trees) {\n  return trees.sort(function (tree1, tree2) {\n    return tree1.name.localeCompare(tree2.name);\n  });\n}\nfunction recurseTree(tree, prefix, recurseFunc) {\n  const treeLen = tree.length;\n  const treeEnd = treeLen - 1;\n\n  for (let i = 0; i < treeLen; i++) {\n    const atEnd = i === treeEnd;\n    recurseFunc(tree[i], prefix + getLastIndentChar(atEnd), prefix + getNextIndentChar(atEnd));\n  }\n}\nfunction getFormattedOutput(fmt) {\n  const item = formatColor(fmt.color, fmt.name, fmt.formatter);\n  const suffix = getSuffix(fmt.hint, fmt.formatter);\n  return `${fmt.prefix}─ ${item}${suffix}\\n`;\n}\n\nfunction getNextIndentChar(end) {\n  return end ? '   ' : '│  ';\n}\n\nfunction getLastIndentChar(end) {\n  return end ? '└' : '├';\n}\n\nfunction getSuffix(hint, formatter) {\n  return hint ? ` (${formatter.grey(hint)})` : '';\n}\n\nfunction formatColor(color, strToFormat, formatter) {\n  return color ? formatter[color](strToFormat) : strToFormat;\n}\n\nconst CLEAR_WHOLE_LINE = 0;\nconst CLEAR_RIGHT_OF_CURSOR = 1;\nfunction clearLine(stdout) {\n  if (!chalk.supportsColor) {\n    if (stdout instanceof tty.WriteStream) {\n      if (stdout.columns > 0) {\n        stdout.write(`\\r${' '.repeat(stdout.columns - 1)}`);\n      }\n\n      stdout.write(`\\r`);\n    }\n\n    return;\n  }\n\n  readline.clearLine(stdout, CLEAR_WHOLE_LINE);\n  readline.cursorTo(stdout, 0);\n}\nfunction toStartOfLine(stdout) {\n  if (!chalk.supportsColor) {\n    stdout.write('\\r');\n    return;\n  }\n\n  readline.cursorTo(stdout, 0);\n}\nfunction writeOnNthLine(stdout, n, msg) {\n  if (!chalk.supportsColor) {\n    return;\n  }\n\n  if (n == 0) {\n    readline.cursorTo(stdout, 0);\n    stdout.write(msg);\n    readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);\n    return;\n  }\n\n  readline.cursorTo(stdout, 0);\n  readline.moveCursor(stdout, 0, -n);\n  stdout.write(msg);\n  readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);\n  readline.cursorTo(stdout, 0);\n  readline.moveCursor(stdout, 0, n);\n}\nfunction clearNthLine(stdout, n) {\n  if (!chalk.supportsColor) {\n    return;\n  }\n\n  if (n == 0) {\n    clearLine(stdout);\n    return;\n  }\n\n  readline.cursorTo(stdout, 0);\n  readline.moveCursor(stdout, 0, -n);\n  readline.clearLine(stdout, CLEAR_WHOLE_LINE);\n  readline.moveCursor(stdout, 0, n);\n}\n\nclass ProgressBar {\n  constructor(total, stdout = process.stderr, callback) {\n    this.stdout = stdout;\n    this.total = total;\n    this.chars = ProgressBar.bars[0];\n    this.delay = 60;\n    this.curr = 0;\n    this._callback = callback;\n    clearLine(stdout);\n  }\n\n  tick() {\n    if (this.curr >= this.total) {\n      return;\n    }\n\n    this.curr++; // schedule render\n\n    if (!this.id) {\n      this.id = setTimeout(() => this.render(), this.delay);\n    }\n  }\n\n  cancelTick() {\n    if (this.id) {\n      clearTimeout(this.id);\n      this.id = null;\n    }\n  }\n\n  stop() {\n    // \"stop\" by setting current to end so `tick` becomes noop\n    this.curr = this.total;\n    this.cancelTick();\n    clearLine(this.stdout);\n\n    if (this._callback) {\n      this._callback(this);\n    }\n  }\n\n  render() {\n    // clear throttle\n    this.cancelTick();\n    let ratio = this.curr / this.total;\n    ratio = Math.min(Math.max(ratio, 0), 1); // progress without bar\n\n    let bar = ` ${this.curr}/${this.total}`; // calculate size of actual bar\n    // $FlowFixMe: investigate process.stderr.columns flow error\n    // @ts-ignore\n\n    const availableSpace = Math.max(0, this.stdout.columns - bar.length - 3);\n    const width = Math.min(this.total, availableSpace);\n    const completeLength = Math.round(width * ratio);\n    const complete = this.chars[0].repeat(completeLength);\n    const incomplete = this.chars[1].repeat(width - completeLength);\n    bar = `[${complete}${incomplete}]${bar}`;\n    toStartOfLine(this.stdout);\n    this.stdout.write(bar);\n  }\n\n}\nProgressBar.bars = [['#', '-']];\n\nclass Spinner {\n  constructor(stdout = process.stderr, lineNumber = 0) {\n    this.current = 0;\n    this.prefix = '';\n    this.lineNumber = lineNumber;\n    this.stdout = stdout;\n    this.delay = 60;\n    this.chars = Spinner.spinners[28].split('');\n    this.text = '';\n    this.id = null;\n  }\n\n  setPrefix(prefix) {\n    this.prefix = prefix;\n  }\n\n  setText(text) {\n    this.text = text;\n  }\n\n  start() {\n    this.current = 0;\n    this.render();\n  }\n\n  render() {\n    if (this.id) {\n      clearTimeout(this.id);\n    } // build line ensuring we don't wrap to the next line\n\n\n    let msg = `${this.prefix}${this.chars[this.current]} ${this.text}`; // @ts-ignore\n\n    const columns = typeof this.stdout.columns === 'number' ? this.stdout.columns : 100;\n    msg = msg.slice(0, columns);\n    writeOnNthLine(this.stdout, this.lineNumber, msg);\n    this.current = ++this.current % this.chars.length;\n    this.id = setTimeout(() => this.render(), this.delay);\n  }\n\n  stop() {\n    if (this.id) {\n      clearTimeout(this.id);\n      this.id = null;\n    }\n\n    clearNthLine(this.stdout, this.lineNumber);\n  }\n\n}\nSpinner.spinners = ['|/-\\\\', '⠂-–—–-', '◐◓◑◒', '◴◷◶◵', '◰◳◲◱', '▖▘▝▗', '■□▪▫', '▌▀▐▄', '▉▊▋▌▍▎▏▎▍▌▋▊▉', '▁▃▄▅▆▇█▇▆▅▄▃', '←↖↑↗→↘↓↙', '┤┘┴└├┌┬┐', '◢◣◤◥', '.oO°Oo.', '.oO@*', '🌍🌎🌏', '◡◡ ⊙⊙ ◠◠', '☱☲☴', '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏', '⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓', '⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆', '⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋', '⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁', '⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈', '⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈', '⢄⢂⢁⡁⡈⡐⡠', '⢹⢺⢼⣸⣇⡧⡗⡏', '⣾⣽⣻⢿⡿⣟⣯⣷', '⠁⠂⠄⡀⢀⠠⠐⠈'];\n\nconst auditSeverityColors = {\n  info: chalk.bold,\n  low: chalk.bold,\n  moderate: chalk.yellow,\n  high: chalk.red,\n  critical: chalk.bgRed\n}; // fixes bold on windows\n\nif (process.platform === 'win32' && !(process.env.TERM && /^xterm/i.test(process.env.TERM))) {\n  // @ts-ignore\n  chalk.bold._styles[0].close += '\\u001b[m';\n}\n\nclass ConsoleReporter extends BaseReporter {\n  constructor(opts) {\n    super(opts);\n    this._lastCategorySize = 0;\n    this._spinners = new Set();\n    this.format = chalk;\n    this.format.stripColor = stripAnsi;\n    this.isSilent = !!opts.isSilent;\n  }\n\n  _prependEmoji(msg, emoji) {\n    if (this.emoji && emoji && this.isTTY) {\n      msg = `${emoji}  ${msg}`;\n    }\n\n    return msg;\n  }\n\n  _logCategory(category, color, msg) {\n    this._lastCategorySize = category.length;\n\n    this._log(`${this.format[color](category)} ${msg}`);\n  }\n\n  _verbose(msg) {\n    this._logCategory('verbose', 'grey', `${process.uptime()} ${msg}`);\n  }\n\n  _verboseInspect(obj) {\n    this.inspect(obj);\n  }\n\n  close() {\n    for (const spinner of this._spinners) {\n      spinner.stop();\n    }\n\n    this._spinners.clear();\n\n    this.stopProgress();\n    super.close();\n  }\n\n  table(head, body) {\n    //\n    head = head.map(field => this.format.underline(field)); //\n\n    const rows = [head].concat(body); // get column widths\n\n    const cols = [];\n\n    for (let i = 0; i < head.length; i++) {\n      const widths = rows.map(row => this.format.stripColor(row[i]).length);\n      cols[i] = Math.max(...widths);\n    } //\n\n\n    const builtRows = rows.map(row => {\n      for (let i = 0; i < row.length; i++) {\n        const field = row[i];\n        const padding = cols[i] - this.format.stripColor(field).length;\n        row[i] = field + ' '.repeat(padding);\n      }\n\n      return row.join(' ');\n    });\n    this.log(builtRows.join('\\n'));\n  }\n\n  step(current, total, msg, emoji) {\n    msg = this._prependEmoji(msg, emoji);\n\n    if (msg.endsWith('?')) {\n      msg = `${removeSuffix(msg, '?')}...?`;\n    } else {\n      msg += '...';\n    }\n\n    this.log(`${this.format.dim(`[${current}/${total}]`)} ${msg}`);\n  }\n\n  inspect(value) {\n    if (typeof value !== 'number' && typeof value !== 'string') {\n      value = util.inspect(value, {\n        breakLength: 0,\n        colors: this.isTTY,\n        depth: null,\n        maxArrayLength: null\n      });\n    }\n\n    this.log(String(value), {\n      force: true\n    });\n  }\n\n  list(key, items, hints) {\n    const gutterWidth = (this._lastCategorySize || 2) - 1;\n\n    if (hints) {\n      for (const item of items) {\n        this._log(`${' '.repeat(gutterWidth)}- ${this.format.bold(item)}`);\n\n        this._log(`  ${' '.repeat(gutterWidth)} ${hints[item]}`);\n      }\n    } else {\n      for (const item of items) {\n        this._log(`${' '.repeat(gutterWidth)}- ${item}`);\n      }\n    }\n  }\n\n  header(pkg) {\n    this.log(this.format.bold(`${pkg.name} v${pkg.version}`));\n  }\n\n  footer(showPeakMemory) {\n    this.stopProgress();\n    const totalTime = (this.getTotalTime() / 1000).toFixed(2);\n    let msg = `Done in ${totalTime}s.`;\n\n    if (showPeakMemory) {\n      const peakMemory = (this.peakMemory / 1024 / 1024).toFixed(2);\n      msg += ` Peak memory usage ${peakMemory}MB.`;\n    }\n\n    this.log(this._prependEmoji(msg, '✨'));\n  }\n\n  log(msg, {\n    force = false\n  } = {}) {\n    this._lastCategorySize = 0;\n\n    this._log(msg, {\n      force\n    });\n  }\n\n  _log(msg, {\n    force = false\n  } = {}) {\n    if (this.isSilent && !force) {\n      return;\n    }\n\n    clearLine(this.stdout);\n    this.stdout.write(`${msg}\\n`);\n  }\n\n  success(msg) {\n    this._logCategory('success', 'green', msg);\n  }\n\n  error(msg) {\n    clearLine(this.stderr);\n    this.stderr.write(`${this.format.red('error')} ${msg}\\n`);\n  }\n\n  info(msg) {\n    this._logCategory('info', 'blue', msg);\n  }\n\n  command(command) {\n    this.log(this.format.dim(`$ ${command}`));\n  }\n\n  warn(msg) {\n    clearLine(this.stderr);\n    this.stderr.write(`${this.format.yellow('warning')} ${msg}\\n`);\n  } // handles basic tree output to console\n\n\n  tree(key, trees, {\n    force = false\n  } = {}) {\n    this.stopProgress(); //\n\n    if (this.isSilent && !force) {\n      return;\n    }\n\n    const output = ({\n      name,\n      children,\n      hint,\n      color\n    }, titlePrefix, childrenPrefix) => {\n      const formatter = this.format;\n      const out = getFormattedOutput({\n        prefix: titlePrefix,\n        hint,\n        color,\n        name,\n        formatter\n      });\n      this.stdout.write(out);\n\n      if (children && children.length) {\n        recurseTree(sortTrees(children), childrenPrefix, output);\n      }\n    };\n\n    recurseTree(sortTrees(trees), '', output);\n  }\n\n  activitySet(total, workers) {\n    if (!this.isTTY || this.noProgress) {\n      return super.activitySet(total, workers);\n    }\n\n    const spinners = [];\n    const reporterSpinners = this._spinners;\n\n    for (let i = 1; i < workers; i++) {\n      this.log('');\n    }\n\n    for (let i = 0; i < workers; i++) {\n      const spinner = new Spinner(this.stderr, i);\n      reporterSpinners.add(spinner);\n      spinner.start();\n      let prefix = null;\n      let current = 0;\n\n      const updatePrefix = () => {\n        spinner.setPrefix(`${this.format.dim(`[${current === 0 ? '-' : current}/${total}]`)} `);\n      };\n\n      const clear = () => {\n        prefix = null;\n        current = 0;\n        updatePrefix();\n        spinner.setText('waiting...');\n      };\n\n      clear();\n      spinners.unshift({\n        clear,\n\n        setPrefix(_current, _prefix) {\n          current = _current;\n          prefix = _prefix;\n          spinner.setText(prefix);\n          updatePrefix();\n        },\n\n        tick(msg) {\n          if (prefix) {\n            msg = `${prefix}: ${msg}`;\n          }\n\n          spinner.setText(msg);\n        },\n\n        end() {\n          spinner.stop();\n          reporterSpinners.delete(spinner);\n        }\n\n      });\n    }\n\n    return {\n      spinners,\n      end: () => {\n        for (const spinner of spinners) {\n          spinner.end();\n        }\n\n        readline.moveCursor(this.stdout, 0, -workers + 1);\n      }\n    };\n  }\n\n  activity() {\n    if (!this.isTTY) {\n      return {\n        tick() {},\n\n        end() {}\n\n      };\n    }\n\n    const reporterSpinners = this._spinners;\n    const spinner = new Spinner(this.stderr);\n    spinner.start();\n    reporterSpinners.add(spinner);\n    return {\n      tick(name) {\n        spinner.setText(name);\n      },\n\n      end() {\n        spinner.stop();\n        reporterSpinners.delete(spinner);\n      }\n\n    };\n  }\n\n  progress(count) {\n    if (this.noProgress || count <= 0) {\n      return function () {// noop\n      };\n    }\n\n    if (!this.isTTY) {\n      return function () {// TODO what should the behaviour here be? we could buffer progress messages maybe\n      };\n    } // Clear any potentially old progress bars\n\n\n    this.stopProgress();\n    const bar = this._progressBar = new ProgressBar(count, this.stderr, progress => {\n      if (progress === this._progressBar) {\n        this._progressBar = null;\n      }\n    });\n    bar.render();\n    return function () {\n      bar.tick();\n    };\n  }\n\n  stopProgress() {\n    if (this._progressBar) {\n      this._progressBar.stop();\n    }\n  }\n\n}\n\nfunction _defineProperty(obj, key, value) {\n  if (key in obj) {\n    Object.defineProperty(obj, key, {\n      value: value,\n      enumerable: true,\n      configurable: true,\n      writable: true\n    });\n  } else {\n    obj[key] = value;\n  }\n\n  return obj;\n}\n\nfunction ownKeys(object, enumerableOnly) {\n  var keys = Object.keys(object);\n\n  if (Object.getOwnPropertySymbols) {\n    var symbols = Object.getOwnPropertySymbols(object);\n    if (enumerableOnly) symbols = symbols.filter(function (sym) {\n      return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n    });\n    keys.push.apply(keys, symbols);\n  }\n\n  return keys;\n}\n\nfunction _objectSpread2(target) {\n  for (var i = 1; i < arguments.length; i++) {\n    var source = arguments[i] != null ? arguments[i] : {};\n\n    if (i % 2) {\n      ownKeys(source, true).forEach(function (key) {\n        _defineProperty(target, key, source[key]);\n      });\n    } else if (Object.getOwnPropertyDescriptors) {\n      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n    } else {\n      ownKeys(source).forEach(function (key) {\n        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n      });\n    }\n  }\n\n  return target;\n}\n\nclass JSONReporter extends BaseReporter {\n  constructor(opts) {\n    super(opts);\n    this._activityId = 0;\n    this._progressId = 0;\n  }\n\n  _dump(type, data, error) {\n    let stdout = this.stdout;\n\n    if (error) {\n      stdout = this.stderr;\n    }\n\n    stdout.write(`${JSON.stringify({\n      type,\n      data\n    })}\\n`);\n  }\n\n  _verbose(msg) {\n    this._dump('verbose', msg);\n  }\n\n  list(type, items, hints) {\n    this._dump('list', {\n      type,\n      items,\n      hints\n    });\n  }\n\n  tree(type, trees) {\n    this._dump('tree', {\n      type,\n      trees\n    });\n  }\n\n  step(current, total, message) {\n    this._dump('step', {\n      message,\n      current,\n      total\n    });\n  }\n\n  inspect(value) {\n    this._dump('inspect', value);\n  }\n\n  footer(showPeakMemory) {\n    this._dump('finished', this.getTotalTime());\n  }\n\n  log(msg) {\n    this._dump('log', msg);\n  }\n\n  command(msg) {\n    this._dump('command', msg);\n  }\n\n  table(head, body) {\n    this._dump('table', {\n      head,\n      body\n    });\n  }\n\n  success(msg) {\n    this._dump('success', msg);\n  }\n\n  error(msg) {\n    this._dump('error', msg, true);\n  }\n\n  warn(msg) {\n    this._dump('warning', msg, true);\n  }\n\n  info(msg) {\n    this._dump('info', msg);\n  }\n\n  activitySet(total, workers) {\n    if (!this.isTTY || this.noProgress) {\n      return super.activitySet(total, workers);\n    }\n\n    const id = this._activityId++;\n\n    this._dump('activitySetStart', {\n      id,\n      total,\n      workers\n    });\n\n    const spinners = [];\n\n    for (let i = 0; i < workers; i++) {\n      let current = 0;\n      let header = '';\n      spinners.push({\n        clear() {},\n\n        setPrefix(_current, _header) {\n          current = _current;\n          header = _header;\n        },\n\n        tick: msg => {\n          this._dump('activitySetTick', {\n            id,\n            header,\n            current,\n            worker: i,\n            message: msg\n          });\n        },\n\n        end() {}\n\n      });\n    }\n\n    return {\n      spinners,\n      end: () => {\n        this._dump('activitySetEnd', {\n          id\n        });\n      }\n    };\n  }\n\n  activity() {\n    return this._activity({});\n  }\n\n  _activity(data) {\n    if (!this.isTTY || this.noProgress) {\n      return {\n        tick() {},\n\n        end() {}\n\n      };\n    }\n\n    const id = this._activityId++;\n\n    this._dump('activityStart', _objectSpread2({\n      id\n    }, data));\n\n    return {\n      tick: name => {\n        this._dump('activityTick', {\n          id,\n          name\n        });\n      },\n      end: () => {\n        this._dump('activityEnd', {\n          id\n        });\n      }\n    };\n  }\n\n  progress(total) {\n    if (this.noProgress) {\n      return function () {// noop\n      };\n    }\n\n    const id = this._progressId++;\n    let current = 0;\n\n    this._dump('progressStart', {\n      id,\n      total\n    });\n\n    return () => {\n      current++;\n\n      this._dump('progressTick', {\n        id,\n        current\n      });\n\n      if (current === total) {\n        this._dump('progressFinish', {\n          id\n        });\n      }\n    };\n  }\n\n}\n\n// import os from 'os';\n// import * as path from 'path';\n// import userHome from './util/user-home-dir.js';\n// import {getCacheDir, getConfigDir, getDataDir} from './util/user-dirs.js';\nconst DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDependencies']; // export const OWNED_DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDependencies'];\n\nconst RESOLUTIONS = 'resolutions';\nconst MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES];\n// export const NPM_REGISTRY_RE = /https?:\\/\\/registry\\.npmjs\\.org/g;\n// export const PIKA_DOCS = 'https://yarnpkg.com/en/docs/cli/';\n// export const PIKA_INSTALLER_SH = 'https://yarnpkg.com/install.sh';\n// export const PIKA_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi';\n// export const SELF_UPDATE_VERSION_URL = 'https://www.pikapkg.com/downloads/latest-version';\n// // cache version, bump whenever we make backwards incompatible changes\n// export const CACHE_VERSION = 3;\n// // lockfile version, bump whenever we make backwards incompatible changes\n// export const LOCKFILE_VERSION = 1;\n// // max amount of network requests to perform concurrently\n// export const NETWORK_CONCURRENCY = 8;\n// // HTTP timeout used when downloading packages\n// export const NETWORK_TIMEOUT = 30 * 1000; // in milliseconds\n// // max amount of child processes to execute concurrently\n\nconst CHILD_CONCURRENCY = 5; // export const REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid'];\nconst NODE_PACKAGE_JSON = 'package.json'; // export const PNP_FILENAME = '.pnp';\n// export const POSIX_GLOBAL_PREFIX = `${process.env.DESTDIR || ''}/usr/local`;\n// export const FALLBACK_GLOBAL_PREFIX = path.join(userHome, '.pika');\n// export const META_FOLDER = '.pika-meta';\n// export const INTEGRITY_FILENAME = '.pika-integrity';\n// export const LOCKFILE_FILENAME = 'pika.lock';\n// export const LEGACY_LOCKFILE_FILENAME = 'yarn.lock';\n// export const METADATA_FILENAME = '.pika-metadata.json';\n// export const TARBALL_FILENAME = '.pika-tarball.tgz';\n// export const CLEAN_FILENAME = '.pikaclean';\n// export const NPM_LOCK_FILENAME = 'package-lock.json';\n// export const NPM_SHRINKWRAP_FILENAME = 'npm-shrinkwrap.json';\n\nconst DEFAULT_INDENT = '  '; // export const SINGLE_INSTANCE_PORT = 31997;\n// export const SINGLE_INSTANCE_FILENAME = '.pika-single-instance';\n\nconst ENV_PATH_KEY = getPathKey(process.platform, process.env);\nfunction getPathKey(platform, env) {\n  let pathKey = 'PATH'; // windows calls its path \"Path\" usually, but this is not guaranteed.\n\n  if (platform === 'win32') {\n    pathKey = 'Path';\n\n    for (const key in env) {\n      if (key.toLowerCase() === 'path') {\n        pathKey = key;\n      }\n    }\n  }\n\n  return pathKey;\n} // export const VERSION_COLOR_SCHEME: {[key: string]: VersionColor} = {\n//   major: 'red',\n//   premajor: 'red',\n//   minor: 'yellow',\n//   preminor: 'yellow',\n//   patch: 'green',\n//   prepatch: 'green',\n//   prerelease: 'red',\n//   unchanged: 'white',\n//   unknown: 'red',\n// };\n// export type VersionColor = 'red' | 'yellow' | 'green' | 'white';\n// export type RequestHint = 'dev' | 'optional' | 'resolution' | 'workspaces';\n\nfunction nullify(obj) {\n  if (Array.isArray(obj)) {\n    for (const item of obj) {\n      nullify(item);\n    }\n  } else if (obj !== null && typeof obj === 'object' || typeof obj === 'function') {\n    Object.setPrototypeOf(obj, null); // for..in can only be applied to 'object', not 'function'\n\n    if (typeof obj === 'object') {\n      for (const key in obj) {\n        nullify(obj[key]);\n      }\n    }\n  }\n\n  return obj;\n}\n\nconst unlink = util.promisify(_rimraf);\nconst glob = util.promisify(_glob);\nconst mkdirp = util.promisify(_mkdirp); //\nconst open = util.promisify(fs.open);\nconst writeFile = util.promisify(fs.writeFile);\nconst readlink = util.promisify(fs.readlink);\nconst realpath = util.promisify(fs.realpath);\nconst readdir = util.promisify(fs.readdir);\nconst rename = util.promisify(fs.rename);\nconst access = util.promisify(fs.access);\nconst stat = util.promisify(fs.stat);\nconst exists = util.promisify(fs.exists);\nconst lstat = util.promisify(fs.lstat);\nconst chmod = util.promisify(fs.chmod);\nconst link = util.promisify(fs.link);\nconst copyFile = util.promisify(fs.copyFile);\nconst readFileBuffer = util.promisify(fs.readFile);\nconst readFile = path => {\n  return util.promisify(fs.readFile)(path, {\n    encoding: 'utf-8'\n  });\n}; // export {unlink};\n// export type CopyQueueItem = {\n//   src: string,\n//   dest: string,\n//   type?: string,\n//   onFresh?: () => void,\n//   onDone?: () => void,\n// };\n// type CopyQueue = Array<CopyQueueItem>;\n// type LinkFileAction = {\n//   src: string,\n//   dest: string,\n//   removeDest: boolean,\n// };\n// type CopySymlinkAction = {\n//   dest: string,\n//   linkname: string,\n// };\n// type CopyActions = {\n//   file: Array<CopyFileAction>,\n//   symlink: Array<CopySymlinkAction>,\n//   link: Array<LinkFileAction>,\n// };\n// type CopyOptions = {\n//   onProgress: (dest: string) => void,\n//   onStart: (num: number) => void,\n//   possibleExtraneous: Set<string>,\n//   ignoreBasenames: Array<string>,\n//   artifactFiles: Array<string>,\n// };\n// type FailedFolderQuery = {\n//   error: Error,\n//   folder: string,\n// };\n// type FolderQueryResult = {\n//   skipped: Array<FailedFolderQuery>,\n//   folder?: string,\n// };\n// async function buildActionsForCopy(\n//   queue: CopyQueue,\n//   events: CopyOptions,\n//   possibleExtraneous: Set<string>,\n//   reporter: Reporter,\n// ): Promise<CopyActions> {\n//   const artifactFiles: Set<string> = new Set(events.artifactFiles || []);\n//   const files: Set<string> = new Set();\n//   // initialise events\n//   for (const item of queue) {\n//     const onDone = item.onDone;\n//     item.onDone = () => {\n//       events.onProgress(item.dest);\n//       if (onDone) {\n//         onDone();\n//       }\n//     };\n//   }\n//   events.onStart(queue.length);\n//   // start building actions\n//   const actions: CopyActions = {\n//     file: [],\n//     symlink: [],\n//     link: [],\n//   };\n//   // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items\n//   // at a time due to the requirement to push items onto the queue\n//   while (queue.length) {\n//     const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);\n//     await Promise.all(items.map(build));\n//   }\n//   // simulate the existence of some files to prevent considering them extraneous\n//   for (const file of artifactFiles) {\n//     if (possibleExtraneous.has(file)) {\n//       reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));\n//       possibleExtraneous.delete(file);\n//     }\n//   }\n//   for (const loc of possibleExtraneous) {\n//     if (files.has(loc.toLowerCase())) {\n//       possibleExtraneous.delete(loc);\n//     }\n//   }\n//   return actions;\n//   //\n//   async function build(data: CopyQueueItem): Promise<void> {\n//     const {src, dest, type} = data;\n//     const onFresh = data.onFresh || noop;\n//     const onDone = data.onDone || noop;\n//     // TODO https://github.com/yarnpkg/yarn/issues/3751\n//     // related to bundled dependencies handling\n//     if (files.has(dest.toLowerCase())) {\n//       reporter.verbose(`The case-insensitive file ${dest} shouldn't be copied twice in one bulk copy`);\n//     } else {\n//       files.add(dest.toLowerCase());\n//     }\n//     if (type === 'symlink') {\n//       await mkdirp(path.dirname(dest));\n//       onFresh();\n//       actions.symlink.push({\n//         dest,\n//         linkname: src,\n//       });\n//       onDone();\n//       return;\n//     }\n//     if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {\n//       // ignored file\n//       return;\n//     }\n//     const srcStat = await lstat(src);\n//     let srcFiles;\n//     if (srcStat.isDirectory()) {\n//       srcFiles = await readdir(src);\n//     }\n//     let destStat;\n//     try {\n//       // try accessing the destination\n//       destStat = await lstat(dest);\n//     } catch (e) {\n//       // proceed if destination doesn't exist, otherwise error\n//       if (e.code !== 'ENOENT') {\n//         throw e;\n//       }\n//     }\n//     // if destination exists\n//     if (destStat) {\n//       const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();\n//       const bothFolders = srcStat.isDirectory() && destStat.isDirectory();\n//       const bothFiles = srcStat.isFile() && destStat.isFile();\n//       // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving\n//       // us modes that aren't valid. investigate this, it's generally safe to proceed.\n//       /* if (srcStat.mode !== destStat.mode) {\n//         try {\n//           await access(dest, srcStat.mode);\n//         } catch (err) {}\n//       } */\n//       if (bothFiles && artifactFiles.has(dest)) {\n//         // this file gets changed during build, likely by a custom install script. Don't bother checking it.\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkipArtifact', src));\n//         return;\n//       }\n//       if (bothFiles && srcStat.size === destStat.size && fileDatesEqual(srcStat.mtime, destStat.mtime)) {\n//         // we can safely assume this is the same file\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime));\n//         return;\n//       }\n//       if (bothSymlinks) {\n//         const srcReallink = await readlink(src);\n//         if (srcReallink === (await readlink(dest))) {\n//           // if both symlinks are the same then we can continue on\n//           onDone();\n//           reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));\n//           return;\n//         }\n//       }\n//       if (bothFolders) {\n//         // mark files that aren't in this folder as possibly extraneous\n//         const destFiles = await readdir(dest);\n//         invariant(srcFiles, 'src files not initialised');\n//         for (const file of destFiles) {\n//           if (srcFiles.indexOf(file) < 0) {\n//             const loc = path.join(dest, file);\n//             possibleExtraneous.add(loc);\n//             if ((await lstat(loc)).isDirectory()) {\n//               for (const file of await readdir(loc)) {\n//                 possibleExtraneous.add(path.join(loc, file));\n//               }\n//             }\n//           }\n//         }\n//       }\n//     }\n//     if (destStat && destStat.isSymbolicLink()) {\n//       await unlink(dest);\n//       destStat = null;\n//     }\n//     if (srcStat.isSymbolicLink()) {\n//       onFresh();\n//       const linkname = await readlink(src);\n//       actions.symlink.push({\n//         dest,\n//         linkname,\n//       });\n//       onDone();\n//     } else if (srcStat.isDirectory()) {\n//       if (!destStat) {\n//         reporter.verbose(reporter.lang('verboseFileFolder', dest));\n//         await mkdirp(dest);\n//       }\n//       const destParts = dest.split(path.sep);\n//       while (destParts.length) {\n//         files.add(destParts.join(path.sep).toLowerCase());\n//         destParts.pop();\n//       }\n//       // push all files to queue\n//       invariant(srcFiles, 'src files not initialised');\n//       let remaining = srcFiles.length;\n//       if (!remaining) {\n//         onDone();\n//       }\n//       for (const file of srcFiles) {\n//         queue.push({\n//           dest: path.join(dest, file),\n//           onFresh,\n//           onDone: () => {\n//             if (--remaining === 0) {\n//               onDone();\n//             }\n//           },\n//           src: path.join(src, file),\n//         });\n//       }\n//     } else if (srcStat.isFile()) {\n//       onFresh();\n//       actions.file.push({\n//         src,\n//         dest,\n//         atime: srcStat.atime,\n//         mtime: srcStat.mtime,\n//         mode: srcStat.mode,\n//       });\n//       onDone();\n//     } else {\n//       throw new Error(`unsure how to copy this: ${src}`);\n//     }\n//   }\n// }\n// async function buildActionsForHardlink(\n//   queue: CopyQueue,\n//   events: CopyOptions,\n//   possibleExtraneous: Set<string>,\n//   reporter: Reporter,\n// ): Promise<CopyActions> {\n//   const artifactFiles: Set<string> = new Set(events.artifactFiles || []);\n//   const files: Set<string> = new Set();\n//   // initialise events\n//   for (const item of queue) {\n//     const onDone = item.onDone || noop;\n//     item.onDone = () => {\n//       events.onProgress(item.dest);\n//       onDone();\n//     };\n//   }\n//   events.onStart(queue.length);\n//   // start building actions\n//   const actions: CopyActions = {\n//     file: [],\n//     symlink: [],\n//     link: [],\n//   };\n//   // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items\n//   // at a time due to the requirement to push items onto the queue\n//   while (queue.length) {\n//     const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);\n//     await Promise.all(items.map(build));\n//   }\n//   // simulate the existence of some files to prevent considering them extraneous\n//   for (const file of artifactFiles) {\n//     if (possibleExtraneous.has(file)) {\n//       reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));\n//       possibleExtraneous.delete(file);\n//     }\n//   }\n//   for (const loc of possibleExtraneous) {\n//     if (files.has(loc.toLowerCase())) {\n//       possibleExtraneous.delete(loc);\n//     }\n//   }\n//   return actions;\n//   //\n//   async function build(data: CopyQueueItem): Promise<void> {\n//     const {src, dest} = data;\n//     const onFresh = data.onFresh || noop;\n//     const onDone = data.onDone || noop;\n//     if (files.has(dest.toLowerCase())) {\n//       // Fixes issue https://github.com/yarnpkg/yarn/issues/2734\n//       // When bulk hardlinking we have A -> B structure that we want to hardlink to A1 -> B1,\n//       // package-linker passes that modules A1 and B1 need to be hardlinked,\n//       // the recursive linking algorithm of A1 ends up scheduling files in B1 to be linked twice which will case\n//       // an exception.\n//       onDone();\n//       return;\n//     }\n//     files.add(dest.toLowerCase());\n//     if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {\n//       // ignored file\n//       return;\n//     }\n//     const srcStat = await lstat(src);\n//     let srcFiles;\n//     if (srcStat.isDirectory()) {\n//       srcFiles = await readdir(src);\n//     }\n//     const destExists = await exists(dest);\n//     if (destExists) {\n//       const destStat = await lstat(dest);\n//       const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();\n//       const bothFolders = srcStat.isDirectory() && destStat.isDirectory();\n//       const bothFiles = srcStat.isFile() && destStat.isFile();\n//       if (srcStat.mode !== destStat.mode) {\n//         try {\n//           await access(dest, srcStat.mode);\n//         } catch (err) {\n//           // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving\n//           // us modes that aren't valid. investigate this, it's generally safe to proceed.\n//           reporter.verbose(err);\n//         }\n//       }\n//       if (bothFiles && artifactFiles.has(dest)) {\n//         // this file gets changed during build, likely by a custom install script. Don't bother checking it.\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkipArtifact', src));\n//         return;\n//       }\n//       // correct hardlink\n//       if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) {\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino));\n//         return;\n//       }\n//       if (bothSymlinks) {\n//         const srcReallink = await readlink(src);\n//         if (srcReallink === (await readlink(dest))) {\n//           // if both symlinks are the same then we can continue on\n//           onDone();\n//           reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));\n//           return;\n//         }\n//       }\n//       if (bothFolders) {\n//         // mark files that aren't in this folder as possibly extraneous\n//         const destFiles = await readdir(dest);\n//         invariant(srcFiles, 'src files not initialised');\n//         for (const file of destFiles) {\n//           if (srcFiles.indexOf(file) < 0) {\n//             const loc = path.join(dest, file);\n//             possibleExtraneous.add(loc);\n//             if ((await lstat(loc)).isDirectory()) {\n//               for (const file of await readdir(loc)) {\n//                 possibleExtraneous.add(path.join(loc, file));\n//               }\n//             }\n//           }\n//         }\n//       }\n//     }\n//     if (srcStat.isSymbolicLink()) {\n//       onFresh();\n//       const linkname = await readlink(src);\n//       actions.symlink.push({\n//         dest,\n//         linkname,\n//       });\n//       onDone();\n//     } else if (srcStat.isDirectory()) {\n//       reporter.verbose(reporter.lang('verboseFileFolder', dest));\n//       await mkdirp(dest);\n//       const destParts = dest.split(path.sep);\n//       while (destParts.length) {\n//         files.add(destParts.join(path.sep).toLowerCase());\n//         destParts.pop();\n//       }\n//       // push all files to queue\n//       invariant(srcFiles, 'src files not initialised');\n//       let remaining = srcFiles.length;\n//       if (!remaining) {\n//         onDone();\n//       }\n//       for (const file of srcFiles) {\n//         queue.push({\n//           onFresh,\n//           src: path.join(src, file),\n//           dest: path.join(dest, file),\n//           onDone: () => {\n//             if (--remaining === 0) {\n//               onDone();\n//             }\n//           },\n//         });\n//       }\n//     } else if (srcStat.isFile()) {\n//       onFresh();\n//       actions.link.push({\n//         src,\n//         dest,\n//         removeDest: destExists,\n//       });\n//       onDone();\n//     } else {\n//       throw new Error(`unsure how to copy this: ${src}`);\n//     }\n//   }\n// }\n// export function copy(src: string, dest: string, reporter: Reporter): Promise<void> {\n//   return copyBulk([{src, dest}], reporter);\n// }\n// export async function copyBulk(\n//   queue: CopyQueue,\n//   reporter: Reporter,\n//   _events?: {\n//     onProgress?: (dest: string) => void,\n//     onStart?: (num: number) => void,\n//     possibleExtraneous: Set<string>,\n//     ignoreBasenames?: Array<string>,\n//     artifactFiles?: Array<string>,\n//   },\n// ): Promise<void> {\n//   const events: CopyOptions = {\n//     onStart: (_events && _events.onStart) || noop,\n//     onProgress: (_events && _events.onProgress) || noop,\n//     possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),\n//     ignoreBasenames: (_events && _events.ignoreBasenames) || [],\n//     artifactFiles: (_events && _events.artifactFiles) || [],\n//   };\n//   const actions: CopyActions = await buildActionsForCopy(queue, events, events.possibleExtraneous, reporter);\n//   events.onStart(actions.file.length + actions.symlink.length + actions.link.length);\n//   const fileActions: Array<CopyFileAction> = actions.file;\n//   const currentlyWriting: Map<string, Promise<void>> = new Map();\n//   await promise.queue(\n//     fileActions,\n//     async (data: CopyFileAction): Promise<void> => {\n//       let writePromise;\n//       while ((writePromise = currentlyWriting.get(data.dest))) {\n//         await writePromise;\n//       }\n//       reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest));\n//       const copier = copyFile(data, () => currentlyWriting.delete(data.dest));\n//       currentlyWriting.set(data.dest, copier);\n//       events.onProgress(data.dest);\n//       return copier;\n//     },\n//     CONCURRENT_QUEUE_ITEMS,\n//   );\n//   // we need to copy symlinks last as they could reference files we were copying\n//   const symlinkActions: Array<CopySymlinkAction> = actions.symlink;\n//   await promise.queue(symlinkActions, (data): Promise<void> => {\n//     const linkname = path.resolve(path.dirname(data.dest), data.linkname);\n//     reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));\n//     return symlink(linkname, data.dest);\n//   });\n// }\n// export async function hardlinkBulk(\n//   queue: CopyQueue,\n//   reporter: Reporter,\n//   _events?: {\n//     onProgress?: (dest: string) => void,\n//     onStart?: (num: number) => void,\n//     possibleExtraneous: Set<string>,\n//     artifactFiles?: Array<string>,\n//   },\n// ): Promise<void> {\n//   const events: CopyOptions = {\n//     onStart: (_events && _events.onStart) || noop,\n//     onProgress: (_events && _events.onProgress) || noop,\n//     possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),\n//     artifactFiles: (_events && _events.artifactFiles) || [],\n//     ignoreBasenames: [],\n//   };\n//   const actions: CopyActions = await buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter);\n//   events.onStart(actions.file.length + actions.symlink.length + actions.link.length);\n//   const fileActions: Array<LinkFileAction> = actions.link;\n//   await promise.queue(\n//     fileActions,\n//     async (data): Promise<void> => {\n//       reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest));\n//       if (data.removeDest) {\n//         await unlink(data.dest);\n//       }\n//       await link(data.src, data.dest);\n//     },\n//     CONCURRENT_QUEUE_ITEMS,\n//   );\n//   // we need to copy symlinks last as they could reference files we were copying\n//   const symlinkActions: Array<CopySymlinkAction> = actions.symlink;\n//   await promise.queue(symlinkActions, (data): Promise<void> => {\n//     const linkname = path.resolve(path.dirname(data.dest), data.linkname);\n//     reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));\n//     return symlink(linkname, data.dest);\n//   });\n// }\n// function _readFile(loc: string, encoding: string): Promise<any> {\n//   return new Promise((resolve, reject) => {\n//     fs.readFile(loc, encoding, function(err, content) {\n//       if (err) {\n//         reject(err);\n//       } else {\n//         resolve(content);\n//       }\n//     });\n//   });\n// }\n// export function readFile(loc: string): Promise<string> {\n//   return _readFile(loc, 'utf8').then(normalizeOS);\n// }\n// export function readFileRaw(loc: string): Promise<Buffer> {\n//   return _readFile(loc, 'binary');\n// }\n// export async function readFileAny(files: Array<string>): Promise<string | null> {\n//   for (const file of files) {\n//     if (await exists(file)) {\n//       return readFile(file);\n//     }\n//   }\n//   return null;\n// }\n\nasync function readJson(loc) {\n  return (await readJsonAndFile(loc)).object;\n}\nasync function readJsonAndFile(loc) {\n  const file = await readFile(loc);\n\n  try {\n    return {\n      object: nullify(JSON.parse(stripBOM(file))),\n      content: file\n    };\n  } catch (err) {\n    err.message = `${loc}: ${err.message}`;\n    throw err;\n  }\n}\n//   const stat = await lstat(loc);\n//   const {size, blksize: blockSize} = stat;\n//   return Math.ceil(size / blockSize) * blockSize;\n// }\n// export function normalizeOS(body: string): string {\n//   return body.replace(/\\r\\n/g, '\\n');\n// }\n\nconst cr = '\\r'.charCodeAt(0);\nconst lf = '\\n'.charCodeAt(0);\n\nasync function getEolFromFile(path) {\n  if (!(await exists(path))) {\n    return undefined;\n  }\n\n  const buffer = await readFileBuffer(path);\n\n  for (let i = 0; i < buffer.length; ++i) {\n    if (buffer[i] === cr) {\n      return '\\r\\n';\n    }\n\n    if (buffer[i] === lf) {\n      return '\\n';\n    }\n  }\n\n  return undefined;\n}\n\nasync function writeFilePreservingEol(path, data) {\n  const eol = (await getEolFromFile(path)) || os.EOL;\n\n  if (eol !== '\\n') {\n    data = data.replace(/\\n/g, eol);\n  }\n\n  await writeFile(path, data);\n} // export async function hardlinksWork(dir: string): Promise<boolean> {\n//   const filename = 'test-file' + Math.random();\n//   const file = path.join(dir, filename);\n//   const fileLink = path.join(dir, filename + '-link');\n//   try {\n//     await writeFile(file, 'test');\n//     await link(file, fileLink);\n//   } catch (err) {\n//     return false;\n//   } finally {\n//     await unlink(file);\n//     await unlink(fileLink);\n//   }\n//   return true;\n// }\n// // not a strict polyfill for Node's fs.mkdtemp\n// export async function makeTempDir(prefix?: string): Promise<string> {\n//   const dir = path.join(os.tmpdir(), `pika-${prefix || ''}-${Date.now()}-${Math.random()}`);\n//   await unlink(dir);\n//   await mkdirp(dir);\n//   return dir;\n// }\n// export async function readFirstAvailableStream(paths: Iterable<string>): Promise<?ReadStream> {\n//   for (const path of paths) {\n//     try {\n//       const fd = await open(path, 'r');\n//       return fs.createReadStream(path, {fd});\n//     } catch (err) {\n//       // Try the next one\n//     }\n//   }\n//   return null;\n// }\n// export async function getFirstSuitableFolder(\n//   paths: Iterable<string>,\n//   mode: number = constants.W_OK | constants.X_OK, // eslint-disable-line no-bitwise\n// ): Promise<FolderQueryResult> {\n//   const result: FolderQueryResult = {\n//     skipped: [],\n//     folder: null,\n//   };\n//   for (const folder of paths) {\n//     try {\n//       await mkdirp(folder);\n//       await access(folder, mode);\n//       result.folder = folder;\n//       return result;\n//     } catch (error) {\n//       result.skipped.push({\n//         error,\n//         folder,\n//       });\n//     }\n//   }\n//   return result;\n// }\n\nasync function generatePublishManifest(manifest, config, _dists) {\n  const {\n    name,\n    version,\n    description,\n    keywords,\n    homepage,\n    bugs,\n    bin,\n    license,\n    authors,\n    contributors,\n    man,\n    sideEffects,\n    repository,\n    dependencies,\n    peerDependencies,\n    devDependencies,\n    bundledDependencies,\n    optionalDependencies,\n    engines,\n    enginesStrict,\n    private: priv,\n    publishConfig\n  } = manifest;\n  const newManifest = {\n    name,\n    description,\n    version,\n    license,\n    bin,\n    files: ['dist-*/', 'bin/'],\n    pika: true,\n    sideEffects: sideEffects || false,\n    keywords,\n    homepage,\n    bugs,\n    authors,\n    contributors,\n    man,\n    repository,\n    dependencies: dependencies || {},\n    peerDependencies,\n    devDependencies,\n    bundledDependencies,\n    optionalDependencies,\n    engines,\n    enginesStrict,\n    private: priv,\n    publishConfig\n  };\n  const dists = _dists || (await config.getDistributions());\n\n  for (const [runner, options] of dists) {\n    if (runner.manifest) {\n      await runner.manifest(newManifest, {\n        cwd: config.cwd,\n        isFull: true,\n        manifest,\n        options\n      });\n    }\n  }\n\n  newManifest.pika = true;\n  return newManifest;\n}\nfunction generatePrettyManifest(manifest) {\n  return JSON.stringify(_objectSpread2({}, manifest, {\n    dependencies: Object.keys(manifest.dependencies).length === 0 ? {} : '{ ... }'\n  }), null, 2);\n}\n\nfunction hasWrapper() {\n  return true;\n}\nconst examples = null;\nclass Build {\n  constructor(flags, config, reporter) {\n    this.flags = flags;\n    this.config = config;\n    this.reporter = reporter;\n    this.totalNum = 0;\n    this.out = path.resolve(config.cwd, flags.out || 'pkg/');\n\n    if (this.out === this.config.cwd) {\n      throw new Error('On publish, you cannot write to cwd because a package.json is created');\n    }\n  }\n\n  async cleanup() {\n    const {\n      out\n    } = this;\n    await unlink(path.join(out, '*'));\n  }\n\n  async init(isFull) {\n    const {\n      config,\n      out,\n      reporter,\n      flags\n    } = this;\n    const {\n      cwd\n    } = config;\n    const outPretty = path.relative(cwd, out) + path.sep;\n    const manifest = await config.manifest;\n    const {\n      sourcemap\n    } = manifest['@pika/pack'] || {\n      sourcemap: true\n    };\n    const distRunners = await config.getDistributions();\n    const builderConfig = {\n      out,\n      cwd,\n      reporter: {\n        info: msg => reporter.log(chalk.dim(`      » ${msg}`)),\n        warning: msg => reporter.log(chalk.yellow(`      » ${msg}`)),\n        success: msg => reporter.log(chalk.green(`      » ${msg}`)),\n        created: (filename, entrypoint) => reporter.log(`      📝  ${chalk.green(path.relative(cwd, filename))} ${entrypoint ? chalk.dim(`[${entrypoint}]`) : ''}`)\n      },\n      isFull,\n      manifest,\n      src: {\n        loc: path.join(out, 'dist-src'),\n        entrypoint: path.join(out, 'dist-src', 'index.js'),\n        // TODO: Deprecated, remove\n        options: {},\n        // TODO: Deprecated, remove\n        files: await (async () => {\n          const ignoreSet = new Set([]);\n          ignoreSet.add('**/*/README.md');\n          const files = await glob(`src/**/*`, {\n            cwd,\n            nodir: true,\n            absolute: true,\n            ignore: Array.from(ignoreSet).map(g => path.join('src', g))\n          });\n          return files.filter(fileAbs => !fileAbs.endsWith('.d.ts'));\n        })()\n      }\n    };\n    const steps = [];\n    steps.push(async (curr, total) => {\n      this.reporter.step(curr, total, 'Validating source');\n\n      for (const [runner, options] of distRunners) {\n        if (runner.validate) {\n          const result = await runner.validate(_objectSpread2({}, builderConfig, {\n            options: _objectSpread2({\n              sourcemap\n            }, options)\n          }));\n\n          if (result instanceof Error) {\n            throw result;\n          }\n        }\n      }\n    });\n    steps.push(async (curr, total) => {\n      this.reporter.step(curr, total, `Preparing pipeline`);\n      await this.cleanup();\n      reporter.log(`      ❇️  ${chalk.green(outPretty)}`);\n\n      for (const [runner, options] of distRunners) {\n        await (runner.beforeBuild && runner.beforeBuild(_objectSpread2({}, builderConfig, {\n          options: _objectSpread2({\n            sourcemap\n          }, options)\n        })));\n      }\n    });\n\n    if (distRunners.length === 0) {\n      steps.push(async (curr, total) => {\n        this.reporter.step(curr, total, `Pipeline is empty! See ${chalk.underline('https://github.com/pikapkg/pack')} for help getting started`);\n      });\n    }\n\n    for (const [runner, options] of distRunners) {\n      steps.push(async (curr, total) => {\n        this.reporter.step(curr, total, `Running ${chalk.bold(runner.name)}`); // return Promise.resolve(\n\n        try {\n          await (runner.beforeJob && runner.beforeJob(_objectSpread2({}, builderConfig, {\n            options: _objectSpread2({\n              sourcemap\n            }, options)\n          })));\n          await (runner.build && runner.build(_objectSpread2({}, builderConfig, {\n            options: _objectSpread2({\n              sourcemap\n            }, options)\n          })));\n          await (runner.afterJob && runner.afterJob(_objectSpread2({}, builderConfig, {\n            options: _objectSpread2({\n              sourcemap\n            }, options)\n          })));\n        } catch (err) {\n          if (flags.force) {\n            console.log('      ❗️  ', chalk.red(err.message), chalk.dim('--force, continuing...'));\n          } else {\n            throw err;\n          }\n        } // ).catch(err => {\n        // log(chalk.red(err.message));\n        // reporter.log(\n        //   reporter.lang(\"distFailed\", runner.name, err.code, err.message),\n        //   { force: true }\n        // );\n        // if (err.forceExit === true) {\n        // reporter.log(reporter.lang(\"distExiting\"));\n        // throw err;\n        // return;\n        // }\n        // reporter.log(reporter.lang(\"distContinuing\"));\n        // });\n\n      });\n    }\n\n    steps.push(async (curr, total) => {\n      this.reporter.step(curr, total, `Finalizing package`);\n\n      for (const [runner, options] of distRunners) {\n        await (runner.afterBuild && runner.afterBuild(_objectSpread2({}, builderConfig, {\n          options: _objectSpread2({\n            sourcemap\n          }, options)\n        })));\n      }\n\n      if (await exists(path.join(cwd, 'CHANGELOG'))) {\n        copyFile(path.join(cwd, 'CHANGELOG'), path.join(out, 'CHANGELOG'));\n        reporter.log(chalk.dim(`      » copying CHANGELOG...`));\n      } else if (await exists(path.join(cwd, 'CHANGELOG.md'))) {\n        copyFile(path.join(cwd, 'CHANGELOG.md'), path.join(out, 'CHANGELOG.md'));\n        reporter.log(chalk.dim(`      » copying CHANGELOG.md...`));\n      }\n\n      if (await exists(path.join(cwd, 'LICENSE'))) {\n        copyFile(path.join(cwd, 'LICENSE'), path.join(out, 'LICENSE'));\n        reporter.log(chalk.dim(`      » copying LICENSE...`));\n      } else if (await exists(path.join(cwd, 'LICENSE.md'))) {\n        copyFile(path.join(cwd, 'LICENSE.md'), path.join(out, 'LICENSE.md'));\n        reporter.log(chalk.dim(`      » copying LICENSE.md...`));\n      }\n\n      if (await exists(path.join(cwd, 'README'))) {\n        copyFile(path.join(cwd, 'README'), path.join(out, 'README'));\n        reporter.log(chalk.dim(`      » copying README...`));\n      } else if (await exists(path.join(cwd, 'README.md'))) {\n        copyFile(path.join(cwd, 'README.md'), path.join(out, 'README.md'));\n        reporter.log(chalk.dim(`      » copying README.md...`));\n      }\n\n      const publishManifest = await generatePublishManifest(config._manifest, config, distRunners);\n\n      if (out === cwd) {\n        reporter.log(`NEW MANIFEST:\\n\\n`);\n        reporter.log(generatePrettyManifest(publishManifest));\n        reporter.log(`\\n\\n`);\n      } else {\n        await writeFilePreservingEol(path.join(out, 'package.json'), JSON.stringify(publishManifest, null, DEFAULT_INDENT) + '\\n');\n        reporter.log(`      📝  ` + chalk.green(outPretty + 'package.json'));\n      }\n\n      reporter.log(`      📦  ` + chalk.green(outPretty));\n    });\n    let currentStep = 0;\n\n    for (const step of steps) {\n      await step(++currentStep, steps.length);\n    }\n  }\n\n}\nasync function run(config, reporter, flags, args) {\n  const isProduction = flags.publish;\n  const builder = new Build(flags, config, reporter);\n  await builder.init(isProduction);\n}\n\nvar buildCommand = /*#__PURE__*/Object.freeze({\n    hasWrapper: hasWrapper,\n    examples: examples,\n    Build: Build,\n    run: run\n});\n\nvar typos = {\n  autohr: 'author',\n  autor: 'author',\n  contributers: 'contributors',\n  depdenencies: 'dependencies',\n  dependancies: 'dependencies',\n  dependecies: 'dependencies',\n  depends: 'dependencies',\n  'dev-dependencies': 'devDependencies',\n  devDependences: 'devDependencies',\n  devDepenencies: 'devDependencies',\n  devEependencies: 'devDependencies',\n  devdependencies: 'devDependencies',\n  hampage: 'homepage',\n  hompage: 'homepage',\n  prefereGlobal: 'preferGlobal',\n  publicationConfig: 'publishConfig',\n  repo: 'repository',\n  repostitory: 'repository',\n  script: 'scripts'\n};\n\nconst strings = ['name', 'version'];\nconst dependencyKeys = [// npm registry will include optionalDependencies in dependencies and we'll want to dedupe them from the\n// other fields first\n'optionalDependencies', // it's seemingly common to include a dependency in dependencies and devDependencies of the same name but\n// different ranges, this can cause a lot of issues with our determinism and the behaviour of npm is\n// currently unspecified.\n'dependencies', 'devDependencies'];\n\nfunction isValidName(name) {\n  return !name.match(/[\\/@\\s\\+%:]/) && encodeURIComponent(name) === name;\n}\n\nfunction isValidScopedName(name) {\n  if (name[0] !== '@') {\n    return false;\n  }\n\n  const parts = name.slice(1).split('/');\n  return parts.length === 2 && isValidName(parts[0]) && isValidName(parts[1]);\n}\n\nfunction isValidPackageName(name) {\n  return isValidName(name) || isValidScopedName(name);\n}\nfunction validate (info, isRoot, reporter, warn) {\n  if (isRoot) {\n    for (const key in typos) {\n      if (key in info) {\n        warn(reporter.lang('manifestPotentialTypo', key, typos[key]));\n      }\n    }\n  } // validate name\n\n\n  const {\n    name\n  } = info;\n\n  if (typeof name === 'string') {\n    if (isRoot && isBuiltinModule(name)) {\n      warn(reporter.lang('manifestBuiltinModule', name));\n    } // cannot start with a dot\n\n\n    if (name[0] === '.') {\n      throw new types.MessageError(reporter.lang('manifestNameDot'));\n    } // cannot contain the following characters\n\n\n    if (!isValidPackageName(name)) {\n      throw new types.MessageError(reporter.lang('manifestNameIllegalChars'));\n    } // cannot equal node_modules or favicon.ico\n\n\n    const lower = name.toLowerCase();\n\n    if (lower === 'node_modules' || lower === 'favicon.ico') {\n      throw new types.MessageError(reporter.lang('manifestNameBlacklisted'));\n    }\n  } // Only care if you are trying to publish to npm.\n  // // validate license\n  // if (isRoot && !info.private) {\n  //   if (typeof info.license === 'string') {\n  //     const license = info.license.replace(/\\*$/g, '');\n  //     if (!isValidLicense(license)) {\n  //       warn(reporter.lang('manifestLicenseInvalid'));\n  //     }\n  //   } else {\n  //     warn(reporter.lang('manifestLicenseNone'));\n  //   }\n  // }\n  // validate strings\n\n\n  for (const key of strings) {\n    const val = info[key];\n\n    if (val && typeof val !== 'string') {\n      throw new types.MessageError(reporter.lang('manifestStringExpected', key));\n    }\n  }\n\n  cleanDependencies(info, isRoot, reporter, warn);\n}\nfunction cleanDependencies(info, isRoot, reporter, warn) {\n  // get dependency objects\n  const depTypes = [];\n\n  for (const type of dependencyKeys) {\n    const deps = info[type];\n\n    if (!deps || typeof deps !== 'object') {\n      continue;\n    }\n\n    depTypes.push([type, deps]);\n  } // aggregate all non-trivial deps (not '' or '*')\n\n\n  const nonTrivialDeps = new Map();\n\n  for (const [type, deps] of depTypes) {\n    for (const name of Object.keys(deps)) {\n      const version = deps[name];\n\n      if (!nonTrivialDeps.has(name) && version && version !== '*') {\n        nonTrivialDeps.set(name, {\n          type,\n          version\n        });\n      }\n    }\n  } // overwrite first dep of package with non-trivial version, remove the rest\n\n\n  const setDeps = new Set();\n\n  for (const [type, deps] of depTypes) {\n    for (const name of Object.keys(deps)) {\n      let version = deps[name];\n      const dep = nonTrivialDeps.get(name);\n\n      if (dep) {\n        if (version && version !== '*' && version !== dep.version && isRoot) {\n          // only throw a warning when at the root\n          warn(reporter.lang('manifestDependencyCollision', dep.type, name, dep.version, type, version));\n        }\n\n        version = dep.version;\n      }\n\n      if (setDeps.has(name)) {\n        delete deps[name];\n      } else {\n        deps[name] = version;\n        setDeps.add(name);\n      }\n    }\n  }\n}\n\nfunction isValidLicense(license) {\n  return !!license && validateLicense(license).validForNewPackages;\n}\nfunction stringifyPerson(person) {\n  if (!person || typeof person !== 'object') {\n    return person;\n  }\n\n  const parts = [];\n\n  if (person.name) {\n    parts.push(person.name);\n  }\n\n  const email = person.email || person.mail;\n\n  if (typeof email === 'string') {\n    parts.push(`<${email}>`);\n  }\n\n  const url = person.url || person.web;\n\n  if (typeof url === 'string') {\n    parts.push(`(${url})`);\n  }\n\n  return parts.join(' ');\n}\nfunction parsePerson(person) {\n  if (typeof person !== 'string') {\n    return person;\n  } // format: name (url) <email>\n\n\n  const obj = {};\n  let name = person.match(/^([^\\(<]+)/);\n\n  if (name && name[0].trim()) {\n    obj.name = name[0].trim();\n  }\n\n  const email = person.match(/<([^>]+)>/);\n\n  if (email) {\n    obj.email = email[1];\n  }\n\n  const url = person.match(/\\(([^\\)]+)\\)/);\n\n  if (url) {\n    obj.url = url[1];\n  }\n\n  return obj;\n}\nfunction normalizePerson(person) {\n  return parsePerson(stringifyPerson(person));\n}\nfunction extractDescription(readme) {\n  if (typeof readme !== 'string' || readme === '') {\n    return undefined;\n  } // split into lines\n\n\n  const lines = readme.trim().split('\\n').map(line => line.trim()); // find the start of the first paragraph, ignore headings\n\n  let start = 0;\n\n  for (; start < lines.length; start++) {\n    const line = lines[start];\n\n    if (line && line.match(/^(#|$)/)) {\n      // line isn't empty and isn't a heading so this is the start of a paragraph\n      start++;\n      break;\n    }\n  } // skip newlines from the header to the first line\n\n\n  while (start < lines.length && !lines[start]) {\n    start++;\n  } // continue to the first non empty line\n\n\n  let end = start;\n\n  while (end < lines.length && lines[end]) {\n    end++;\n  }\n\n  return lines.slice(start, end).join(' ');\n}\n\nvar LICENSES = {\n  'Apache-2.0': new RegExp('(licensed under the apache license version the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license$|apache license version january http www apache org licenses terms and conditions for use reproduction and distribution definitions license shall mean the terms and conditions for use reproduction and distribution as defined by sections through of this document licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the license legal entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity for the purposes of this definition control means i the power direct or indirect to cause the direction or management of such entity whether by contract or otherwise or ii ownership of fifty percent or more of the outstanding shares or iii beneficial ownership of such entity you or your shall mean an individual or legal entity exercising permissions granted by this license source form shall mean the preferred form for making modifications including but not limited to software source code documentation source and configuration files object form shall mean any form resulting from mechanical transformation or translation of a source form including but not limited to compiled object code generated documentation and conversions to other media types work shall mean the work of authorship whether in source or object form made available under the license as indicated by a copyright notice that is included in or attached to the work an example is provided in the appendix below derivative works shall mean any work whether in source or object form that is based on or derived from the work and for which the editorial revisions annotations elaborations or other modifications represent as a whole an original work of authorship for the purposes of this license derivative works shall not include works that remain separable from or merely link or bind by name to the interfaces of the work and derivative works thereof contribution shall mean any work of authorship including the original version of the work and any modifications or additions to that work or derivative works thereof that is intentionally submitted to licensor for inclusion in the work by the copyright owner or by an individual or legal entity authorized to submit on behalf of the copyright owner for the purposes of this definition submitted means any form of electronic verbal or written communication sent to the licensor or its representatives including but not limited to communication on electronic mailing lists source code control systems and issue tracking systems that are managed by or on behalf of the licensor for the purpose of discussing and improving the work but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as not a contribution contributor shall mean licensor and any individual or legal entity on behalf of whom a contribution has been received by licensor and subsequently incorporated within the work grant of copyright license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable copyright license to reproduce prepare derivative works of publicly display publicly perform sublicense and distribute the work and such derivative works in source or object form grant of patent license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable except as stated in this section patent license to make have made use offer to sell sell import and otherwise transfer the work where such license applies only to those patent claims licensable by such contributor that are necessarily infringed by their contribution s alone or by combination of their contribution s with the work to which such contribution s was submitted if you institute patent litigation against any entity including a cross claim or counterclaim in a lawsuit alleging that the work or a contribution incorporated within the work constitutes direct or contributory patent infringement then any patent licenses granted to you under this license for that work shall terminate as of the date such litigation is filed redistribution you may reproduce and distribute copies of the work or derivative works thereof in any medium with or without modifications and in source or object form provided that you meet the following conditions a you must give any other recipients of the work or derivative works a copy of this license and b you must cause any modified files to carry prominent notices stating that you changed the files and c you must retain in the source form of any derivative works that you distribute all copyright patent trademark and attribution notices from the source form of the work excluding those notices that do not pertain to any part of the derivative works and d if the work includes a notice text file as part of its distribution then any derivative works that you distribute must include a readable copy of the attribution notices contained within such notice file excluding those notices that do not pertain to any part of the derivative works in at least one of the following places within a notice text file distributed as part of the derivative works within the source form or documentation if provided along with the derivative works or within a display generated by the derivative works if and wherever such third party notices normally appear the contents of the notice file are for informational purposes only and do not modify the license you may add your own attribution notices within derivative works that you distribute alongside or as an addendum to the notice text from the work provided that such additional attribution notices cannot be construed as modifying the license you may add your own copyright statement to your modifications and may provide additional or different license terms and conditions for use reproduction or distribution of your modifications or for any such derivative works as a whole provided your use reproduction and distribution of the work otherwise complies with the conditions stated in this license submission of contributions unless you explicitly state otherwise any contribution intentionally submitted for inclusion in the work by you to the licensor shall be under the terms and conditions of this license without any additional terms or conditions notwithstanding the above nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with licensor regarding such contributions trademarks this license does not grant permission to use the trade names trademarks service marks or product names of the licensor except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the notice file disclaimer of warranty unless required by applicable law or agreed to in writing licensor provides the work and each contributor provides its contributions on an as is basis without warranties or conditions of any kind either express or implied including without limitation any warranties or conditions of title non infringement merchantability or fitness for a particular purpose you are solely responsible for determining the appropriateness of using or redistributing the work and assume any risks associated with your exercise of permissions under this license limitation of liability in no event and under no legal theory whether in tort including negligence contract or otherwise unless required by applicable law such as deliberate and grossly negligent acts or agreed to in writing shall any contributor be liable to you for damages including any direct indirect special incidental or consequential damages of any character arising as a result of this license or out of the use or inability to use the work including but not limited to damages for loss of goodwill work stoppage computer failure or malfunction or any and all other commercial damages or losses even if such contributor has been advised of the possibility of such damages accepting warranty or additional liability while redistributing the work or derivative works thereof you may choose to offer and charge a fee for acceptance of support warranty indemnity or other liability obligations and or rights consistent with this license however in accepting such obligations you may act only on your own behalf and on your sole responsibility not on behalf of any other contributor and only if you agree to indemnify defend and hold each contributor harmless for any liability incurred by or claims asserted against such contributor by reason of your accepting any such warranty or additional liability end of terms and conditions$)', 'g'),\n  'BSD-2-Clause': new RegExp('(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this(.*?| )is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this(.*?| )even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$)', 'g'),\n  'BSD-3-Clause': new RegExp('(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name of(.*?| )nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution the names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall the copyright holders and contributors be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name(.*?| )nor the names of(.*?| )contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by(.*?| )as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$))', 'g'),\n  MIT: new RegExp('permission is hereby granted free of charge to any person obtaining a copy of this software and associated documentation files the software to deal in the software without restriction including without limitation the rights to use copy modify merge publish distribute sublicense and or sell copies of the software and to permit persons to whom the software is furnished to do so subject to the following conditions the above copyright notice and this permission notice shall be included in all copies or substantial portions of the software the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors or copyright holders be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software$', 'g'),\n  Unlicense: new RegExp('this is free and unencumbered software released into the public domain anyone is free to copy modify publish use compile sell or distribute this software either in source code form or as a compiled binary for any purpose commercial or non commercial and by any means in jurisdictions that recognize copyright laws the author or authors of this software dedicate any and all copyright interest in the software to the public domain we make this dedication for the benefit of the public at large and to the detriment of our heirs and successors we intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software for more information please refer to wildcard$', 'g')\n};\n\nfunction clean(str) {\n  return str.replace(/[^A-Za-z\\s]/g, ' ').replace(/[\\s]+/g, ' ').trim().toLowerCase();\n}\n\nconst REGEXES = {\n  Apache: [/Apache License\\b/],\n  BSD: [/BSD\\b/],\n  ISC: [/The ISC License/, /ISC\\b/],\n  MIT: [/MIT\\b/],\n  Unlicense: [/http:\\/\\/unlicense.org\\//],\n  WTFPL: [/DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE/, /WTFPL\\b/]\n};\nfunction inferLicense(license) {\n  // check if we have any explicit licenses\n  const cleanLicense = clean(license);\n\n  for (const licenseName in LICENSES) {\n    const testLicense = LICENSES[licenseName];\n\n    if (cleanLicense.search(testLicense) >= 0) {\n      return licenseName;\n    }\n  } // infer based on some keywords\n\n\n  for (const licenseName in REGEXES) {\n    for (const regex of REGEXES[licenseName]) {\n      if (license.search(regex) >= 0) {\n        return `${licenseName}*`;\n      }\n    }\n  }\n\n  return null;\n}\n\nconst LICENSE_RENAMES = {\n  'MIT/X11': 'MIT',\n  X11: 'MIT'\n};\nvar fix = (async function (info, moduleLoc, reporter, warn) {\n  const files = await readdir(moduleLoc); // clean info.version\n\n  if (typeof info.version === 'string') {\n    info.version = semver.clean(info.version) || info.version;\n  } // if name or version aren't set then set them to empty strings\n\n\n  info.name = info.name || '';\n  info.version = info.version || ''; // if the man field is a string then coerce it to an array\n\n  if (typeof info.man === 'string') {\n    info.man = [info.man];\n  } // if the keywords field is a string then split it on any whitespace\n\n\n  if (typeof info.keywords === 'string') {\n    info.keywords = info.keywords.split(/\\s+/g);\n  } // if there's no contributors field but an authors field then expand it\n\n\n  if (!info.contributors && files.indexOf('AUTHORS') >= 0) {\n    const authorsFilepath = path.join(moduleLoc, 'AUTHORS');\n    const authorsFilestats = await stat(authorsFilepath);\n\n    if (authorsFilestats.isFile()) {\n      let authors = await readFile(authorsFilepath);\n      info.contributors = authors.split(/\\r?\\n/g) // split on lines\n      .map(line => line.replace(/^\\s*#.*$/, '').trim()) // remove comments\n      .filter(line => !!line); // remove empty lines;\n    }\n  } // expand people fields to objects\n\n\n  if (typeof info.author === 'string' || typeof info.author === 'object') {\n    info.author = normalizePerson(info.author);\n  }\n\n  if (Array.isArray(info.contributors)) {\n    info.contributors = info.contributors.map(normalizePerson);\n  }\n\n  if (Array.isArray(info.maintainers)) {\n    info.maintainers = info.maintainers.map(normalizePerson);\n  } // if there's no readme field then load the README file from the cwd\n\n\n  if (!info.readme) {\n    const readmeCandidates = files.filter(filename => {\n      const lower = filename.toLowerCase();\n      return lower === 'readme' || lower.indexOf('readme.') === 0;\n    }).sort((filename1, filename2) => {\n      // favor files with extensions\n      return filename2.indexOf('.') - filename1.indexOf('.');\n    });\n\n    for (const readmeFilename of readmeCandidates) {\n      const readmeFilepath = path.join(moduleLoc, readmeFilename);\n      const readmeFileStats = await stat(readmeFilepath);\n\n      if (readmeFileStats.isFile()) {\n        info.readmeFilename = readmeFilename;\n        info.readme = await readFile(readmeFilepath);\n        break;\n      }\n    }\n  } // if there's no description then take the first paragraph from the readme\n\n\n  if (!info.description && info.readme) {\n    const desc = extractDescription(info.readme);\n\n    if (desc) {\n      info.description = desc;\n    }\n  } // support array of engine keys\n\n\n  if (Array.isArray(info.engines)) {\n    const engines = {};\n\n    for (const str of info.engines) {\n      if (typeof str === 'string') {\n        const [name, ...patternParts] = str.trim().split(/ +/g);\n        engines[name] = patternParts.join(' ');\n      }\n    }\n\n    info.engines = engines;\n  } // allow bugs to be specified as a string, expand it to an object with a single url prop\n\n\n  if (typeof info.bugs === 'string') {\n    info.bugs = {\n      url: info.bugs\n    };\n  } // normalize homepage url to http\n\n\n  if (typeof info.homepage === 'string') {\n    const parts = nodeUrl.parse(info.homepage);\n    parts.protocol = parts.protocol || 'http:';\n\n    if (parts.pathname && !parts.hostname) {\n      parts.hostname = parts.pathname;\n      parts.pathname = '';\n    }\n\n    info.homepage = nodeUrl.format(parts);\n  } // if the `bin` field is as string then expand it to an object with a single property\n  // based on the original `bin` field and `name field`\n  // { name: \"foo\", bin: \"cli.js\" } -> { name: \"foo\", bin: { foo: \"cli.js\" } }\n\n\n  if (typeof info.name === 'string' && typeof info.bin === 'string' && info.bin.length > 0) {\n    // Remove scoped package name for consistency with NPM's bin field fixing behaviour\n    const name = info.name.replace(/^@[^\\/]+\\//, '');\n    info.bin = {\n      [name]: info.bin\n    };\n  } // bundleDependencies is an alias for bundledDependencies\n\n\n  if (info.bundledDependencies) {\n    info.bundleDependencies = info.bundledDependencies;\n    delete info.bundledDependencies;\n  }\n\n  let scripts; // dummy script object to shove file inferred scripts onto\n\n  if (info.scripts && typeof info.scripts === 'object') {\n    scripts = info.scripts;\n  } else {\n    scripts = {};\n  } // if there's a server.js file and no start script then set it to `node server.js`\n\n\n  if (!scripts.start && files.indexOf('server.js') >= 0) {\n    scripts.start = 'node server';\n  } // if there's a binding.gyp file and no install script then set it to `node-gyp rebuild`\n\n\n  if (!scripts.install && files.indexOf('binding.gyp') >= 0) {\n    scripts.install = 'node-gyp rebuild';\n  } // set scripts if we've polluted the empty object\n\n\n  if (Object.keys(scripts).length) {\n    info.scripts = scripts;\n  }\n\n  const dirs = info.directories;\n\n  if (dirs && typeof dirs === 'object') {\n    const binDir = dirs.bin;\n\n    if (!info.bin && binDir && typeof binDir === 'string') {\n      const bin = info.bin = {};\n      const fullBinDir = path.join(moduleLoc, binDir);\n\n      if (await exists(fullBinDir)) {\n        for (const scriptName of await readdir(fullBinDir)) {\n          if (scriptName[0] === '.') {\n            continue;\n          }\n\n          bin[scriptName] = path.join('.', binDir, scriptName);\n        }\n      } else {\n        warn(reporter.lang('manifestDirectoryNotFound', binDir, info.name));\n      }\n    }\n\n    const manDir = dirs.man;\n\n    if (!info.man && typeof manDir === 'string') {\n      const man = info.man = [];\n      const fullManDir = path.join(moduleLoc, manDir);\n\n      if (await exists(fullManDir)) {\n        for (const filename of await readdir(fullManDir)) {\n          if (/^(.*?)\\.[0-9]$/.test(filename)) {\n            man.push(path.join('.', manDir, filename));\n          }\n        }\n      } else {\n        warn(reporter.lang('manifestDirectoryNotFound', manDir, info.name));\n      }\n    }\n  }\n\n  delete info.directories; // normalize licenses field\n\n  const licenses = info.licenses;\n\n  if (Array.isArray(licenses) && !info.license) {\n    let licenseTypes = [];\n\n    for (let license of licenses) {\n      if (license && typeof license === 'object') {\n        license = license.type;\n      }\n\n      if (typeof license === 'string') {\n        licenseTypes.push(license);\n      }\n    }\n\n    licenseTypes = licenseTypes.filter(isValidLicense);\n\n    if (licenseTypes.length === 1) {\n      info.license = licenseTypes[0];\n    } else if (licenseTypes.length) {\n      info.license = `(${licenseTypes.join(' OR ')})`;\n    }\n  }\n\n  const license = info.license; // normalize license\n\n  if (license && typeof license === 'object') {\n    info.license = license.type;\n  } // get license file\n\n\n  const licenseFile = files.find(filename => {\n    const lower = filename.toLowerCase();\n    return lower === 'license' || lower.startsWith('license.') || lower === 'unlicense' || lower.startsWith('unlicense.');\n  });\n\n  if (licenseFile) {\n    const licenseFilepath = path.join(moduleLoc, licenseFile);\n    const licenseFileStats = await stat(licenseFilepath);\n\n    if (licenseFileStats.isFile()) {\n      const licenseContent = await readFile(licenseFilepath);\n      const inferredLicense = inferLicense(licenseContent);\n      info.licenseText = licenseContent;\n      const license = info.license;\n\n      if (typeof license === 'string') {\n        if (inferredLicense && isValidLicense(inferredLicense) && !isValidLicense(license)) {\n          // some packages don't specify their license version but we can infer it based on their license file\n          const basicLicense = license.toLowerCase().replace(/(-like|\\*)$/g, '');\n          const expandedLicense = inferredLicense.toLowerCase();\n\n          if (expandedLicense.startsWith(basicLicense)) {\n            // TODO consider doing something to notify the user\n            info.license = inferredLicense;\n          }\n        }\n      } else if (inferredLicense) {\n        // if there's no license then infer it based on the license file\n        info.license = inferredLicense;\n      } else {\n        // valid expression to refer to a license in a file\n        info.license = `SEE LICENSE IN ${licenseFile}`;\n      }\n    }\n  }\n\n  if (typeof info.license === 'string') {\n    // sometimes licenses are known by different names, reduce them\n    info.license = LICENSE_RENAMES[info.license] || info.license;\n  } else if (typeof info.readme === 'string') {\n    // the license might be at the bottom of the README\n    const inferredLicense = inferLicense(info.readme);\n\n    if (inferredLicense) {\n      info.license = inferredLicense;\n    }\n  } // get notice file\n\n\n  const noticeFile = files.find(filename => {\n    const lower = filename.toLowerCase();\n    return lower === 'notice' || lower.startsWith('notice.');\n  });\n\n  if (noticeFile) {\n    const noticeFilepath = path.join(moduleLoc, noticeFile);\n    const noticeFileStats = await stat(noticeFilepath);\n\n    if (noticeFileStats.isFile()) {\n      info.noticeText = await readFile(noticeFilepath);\n    }\n  }\n\n  for (const dependencyType of MANIFEST_FIELDS) {\n    const dependencyList = info[dependencyType];\n\n    if (dependencyList && typeof dependencyList === 'object') {\n      delete dependencyList['//'];\n\n      for (const name in dependencyList) {\n        dependencyList[name] = dependencyList[name] || '';\n      }\n    }\n  }\n});\n\nvar normalizeManifest = (async function (info, moduleLoc, config, isRoot) {\n  // Append dependencies\n  // if (depInfo) {\n  //   info.dependencies = depInfo.main;\n  //   info.devDependencies = depInfo.dev;\n  // }\n  // create human readable name\n  const {\n    name,\n    version\n  } = info;\n  let human;\n\n  if (typeof name === 'string') {\n    human = name;\n  }\n\n  if (human && typeof version === 'string' && version) {\n    human += `@${version}`;\n  }\n\n  if (isRoot && info._loc) {\n    human = path.relative(config.cwd, info._loc);\n  }\n\n  function warn(msg) {\n    if (human) {\n      msg = `${human}: ${msg}`;\n    }\n\n    config.reporter.warn(msg);\n  }\n\n  await fix(info, moduleLoc, config.reporter, warn);\n\n  try {\n    validate(info, isRoot, config.reporter, warn);\n  } catch (err) {\n    if (human) {\n      err.message = `${human}: ${err.message}`;\n    }\n\n    throw err;\n  }\n\n  return info;\n});\n\nclass BlockingQueue {\n  constructor(alias, maxConcurrency = Infinity) {\n    this.concurrencyQueue = [];\n    this.maxConcurrency = maxConcurrency;\n    this.runningCount = 0;\n    this.warnedStuck = false;\n    this.alias = alias;\n    this.first = true;\n    this.running = nullify() || {};\n    this.queue = nullify() || {};\n    this.stuckTick = this.stuckTick.bind(this);\n  }\n\n  stillActive() {\n    if (this.stuckTimer) {\n      clearTimeout(this.stuckTimer);\n    }\n\n    this.stuckTimer = setTimeout(this.stuckTick, 5000); // We need to check the existence of unref because of https://github.com/facebook/jest/issues/4559\n    // $FlowFixMe: Node's setInterval returns a Timeout, not a Number\n\n    this.stuckTimer.unref && this.stuckTimer.unref();\n  }\n\n  stuckTick() {\n    if (this.runningCount === 1) {\n      this.warnedStuck = true;\n      console.log(`The ${JSON.stringify(this.alias)} blocking queue may be stuck. 5 seconds ` + `without any activity with 1 worker: ${Object.keys(this.running)[0]}`);\n    }\n  }\n\n  push(key, factory) {\n    if (this.first) {\n      this.first = false;\n    } else {\n      this.stillActive();\n    }\n\n    return new Promise((resolve, reject) => {\n      // we're already running so push ourselves to the queue\n      const queue = this.queue[key] = this.queue[key] || [];\n      queue.push({\n        factory,\n        resolve,\n        reject\n      });\n\n      if (!this.running[key]) {\n        this.shift(key);\n      }\n    });\n  }\n\n  shift(key) {\n    if (this.running[key]) {\n      delete this.running[key];\n      this.runningCount--;\n\n      if (this.stuckTimer) {\n        clearTimeout(this.stuckTimer);\n        this.stuckTimer = null;\n      }\n\n      if (this.warnedStuck) {\n        this.warnedStuck = false;\n        console.log(`${JSON.stringify(this.alias)} blocking queue finally resolved. Nothing to worry about.`);\n      }\n    }\n\n    const queue = this.queue[key];\n\n    if (!queue) {\n      return;\n    }\n\n    const {\n      resolve,\n      reject,\n      factory\n    } = queue.shift();\n\n    if (!queue.length) {\n      delete this.queue[key];\n    }\n\n    const next = () => {\n      this.shift(key);\n      this.shiftConcurrencyQueue();\n    };\n\n    const run = () => {\n      this.running[key] = true;\n      this.runningCount++;\n      factory().then(function (val) {\n        resolve(val);\n        next();\n        return null;\n      }).catch(function (err) {\n        reject(err);\n        next();\n      });\n    };\n\n    this.maybePushConcurrencyQueue(run);\n  }\n\n  maybePushConcurrencyQueue(run) {\n    if (this.runningCount < this.maxConcurrency) {\n      run();\n    } else {\n      this.concurrencyQueue.push(run);\n    }\n  }\n\n  shiftConcurrencyQueue() {\n    if (this.runningCount < this.maxConcurrency) {\n      const fn = this.concurrencyQueue.shift();\n\n      if (fn) {\n        fn();\n      }\n    }\n  }\n\n}\n\nclass ProcessSpawnError extends types.MessageError {\n  constructor(msg, code, process) {\n    super(msg);\n    this.code = code;\n    this.process = process;\n  }\n\n}\nclass ProcessTermError extends types.MessageError {}\n\n/* global child_process$spawnOpts */\nconst queue = new BlockingQueue('child', CHILD_CONCURRENCY); // TODO: this uid check is kinda whack\n\nlet uid = 0;\nconst spawnedProcesses = {};\nfunction forwardSignalToSpawnedProcesses(signal) {\n  for (const key of Object.keys(spawnedProcesses)) {\n    spawnedProcesses[key].kill(signal);\n  }\n}\nfunction spawn(program, args, opts = {}, onData) {\n  const key = opts.cwd || String(++uid);\n  return queue.push(key, () => new Promise((resolve, reject) => {\n    const proc = child_process.spawn(program, args, opts);\n\n    spawnedProcesses[key] = proc;\n    let processingDone = false;\n    let processClosed = false;\n    let err = null;\n    let stdout = '';\n    proc.on('error', err => {\n      if (err.code === 'ENOENT') {\n        reject(new ProcessSpawnError(`Couldn't find the binary ${program}`, err.code, program));\n      } else {\n        reject(err);\n      }\n    });\n\n    function updateStdout(chunk) {\n      stdout += chunk;\n\n      if (onData) {\n        onData(chunk);\n      }\n    }\n\n    function finish() {\n      delete spawnedProcesses[key];\n\n      if (err) {\n        reject(err);\n      } else {\n        resolve(stdout.trim());\n      }\n    }\n\n    if (typeof opts.process === 'function') {\n      opts.process(proc, updateStdout, reject, function () {\n        if (processClosed) {\n          finish();\n        } else {\n          processingDone = true;\n        }\n      });\n    } else {\n      if (proc.stderr) {\n        proc.stderr.on('data', updateStdout);\n      }\n\n      if (proc.stdout) {\n        proc.stdout.on('data', updateStdout);\n      }\n\n      processingDone = true;\n    }\n\n    proc.on('close', (code, signal) => {\n      if (signal || code >= 1) {\n        err = new ProcessTermError(['Command failed.', signal ? `Exit signal: ${signal}` : `Exit code: ${code}`, `Command: ${program}`, `Arguments: ${args.join(' ')}`, `Directory: ${opts.cwd || process.cwd()}`, `Output:\\n${stdout.trim()}`].join('\\n'));\n        err.EXIT_SIGNAL = signal;\n        err.EXIT_CODE = code;\n      }\n\n      if (processingDone || err) {\n        finish();\n      } else {\n        processClosed = true;\n      }\n    });\n  }));\n}\n\nfunction fixCmdWinSlashes(cmd) {\n  function findQuotes(quoteSymbol) {\n    const quotes = [];\n\n    const addQuote = (_, index) => {\n      quotes.push({\n        from: index,\n        to: index + _.length\n      });\n      return _;\n    };\n\n    const regEx = new RegExp(quoteSymbol + '.*' + quoteSymbol);\n    cmd.replace(regEx, addQuote);\n    return quotes;\n  }\n\n  const quotes = findQuotes('\"').concat(findQuotes(\"'\"));\n\n  function isInsideQuotes(index) {\n    return quotes.reduce((result, quote) => {\n      return result || quote.from <= index && index <= quote.to;\n    }, false);\n  }\n\n  const cmdPrePattern = '((?:^|&&|&|\\\\|\\\\||\\\\|)\\\\s*)';\n  const cmdPattern = '(\".*?\"|\\'.*?\\'|\\\\S*)';\n  const regExp = new RegExp(`${cmdPrePattern}${cmdPattern}`, 'g');\n  return cmd.replace(regExp, (whole, pre, cmd, index) => {\n    if ((pre[0] === '&' || pre[0] === '|') && isInsideQuotes(index)) {\n      return whole;\n    }\n\n    return pre + cmd.replace(/\\//g, '\\\\');\n  });\n}\n\n// // We treat these configs as internal, thus not expose them to process.env.\n// // This helps us avoid some gyp issues when building native modules.\n// // See https://github.com/yarnpkg/yarn/issues/2286.\n// const IGNORE_CONFIG_KEYS = ['lastUpdateCheck'];\n// async function getPnpParameters(config: Config): Promise<Array<string>> {\n//   if (await fs.exists(`${config.lockfileFolder}/${constants.PNP_FILENAME}`)) {\n//     return ['-r', `${config.lockfileFolder}/${constants.PNP_FILENAME}`];\n//   } else {\n//     return [];\n//   }\n// }\n// let wrappersFolder = null;\n// export async function getWrappersFolder(config: Config): Promise<string> {\n//   if (wrappersFolder) {\n//     return wrappersFolder;\n//   }\n//   wrappersFolder = await fs.makeTempDir();\n//   await makePortableProxyScript(process.execPath, wrappersFolder, {\n//     proxyBasename: 'node',\n//     prependArguments: [...(await getPnpParameters(config))],\n//   });\n//   await makePortableProxyScript(process.execPath, wrappersFolder, {\n//     proxyBasename: 'pika',\n//     prependArguments: [process.argv[1]],\n//   });\n//   return wrappersFolder;\n// }\n// const INVALID_CHAR_REGEX = /\\W/g;\n\nasync function makeEnv() {\n  // stage: string,\n  // cwd: string,\n  // config: Config,\n  const env = _objectSpread2({\n    NODE: process.execPath,\n    INIT_CWD: process.cwd()\n  }, process.env);\n\n  return env;\n} //   // Merge in the `env` object specified in .pikarc\n//   const customEnv = config.getOption('env');\n//   if (customEnv && typeof customEnv === 'object') {\n//     Object.assign(env, customEnv);\n//   }\n//   env.npm_lifecycle_event = stage;\n//   env.npm_node_execpath = env.NODE;\n//   env.npm_execpath = env.npm_execpath || (process.mainModule && process.mainModule.filename);\n//   // Set the env to production for npm compat if production mode.\n//   // https://github.com/npm/npm/blob/30d75e738b9cb7a6a3f9b50e971adcbe63458ed3/lib/utils/lifecycle.js#L336\n//   if (config.production) {\n//     env.NODE_ENV = 'production';\n//   }\n//   // Note: npm_config_argv environment variable contains output of nopt - command-line\n//   // parser used by npm. Since we use other parser, we just roughly emulate it's output. (See: #684)\n//   env.npm_config_argv = JSON.stringify({\n//     remain: [],\n//     cooked: config.commandName === 'run' ? [config.commandName, stage] : [config.commandName],\n//     original: process.argv.slice(2),\n//   });\n//   const manifest = await config.maybeReadManifest(cwd);\n//   if (manifest) {\n//     if (manifest.scripts && Object.prototype.hasOwnProperty.call(manifest.scripts, stage)) {\n//       env.npm_lifecycle_script = manifest.scripts[stage];\n//     }\n//     // add npm_package_*\n//     const queue = [['', manifest]];\n//     while (queue.length) {\n//       const [key, val] = queue.pop();\n//       if (typeof val === 'object') {\n//         for (const subKey in val) {\n//           const fullKey = [key, subKey].filter(Boolean).join('_');\n//           if (fullKey && fullKey[0] !== '_' && !IGNORE_MANIFEST_KEYS.has(fullKey)) {\n//             queue.push([fullKey, val[subKey]]);\n//           }\n//         }\n//       } else {\n//         let cleanVal = String(val);\n//         if (cleanVal.indexOf('\\n') >= 0) {\n//           cleanVal = JSON.stringify(cleanVal);\n//         }\n//         //replacing invalid chars with underscore\n//         const cleanKey = key.replace(INVALID_CHAR_REGEX, '_');\n//         env[`npm_package_${cleanKey}`] = cleanVal;\n//       }\n//     }\n//   }\n//   // add npm_config_* and npm_package_config_* from pika config\n//   const keys: Set<string> = new Set([\n//     ...Object.keys(config.registries.pika.config),\n//     ...Object.keys(config.registries.npm.config),\n//   ]);\n//   const cleaned = Array.from(keys)\n//     .filter(key => !key.match(/:_/) && IGNORE_CONFIG_KEYS.indexOf(key) === -1)\n//     .map(key => {\n//       let val = config.getOption(key);\n//       if (!val) {\n//         val = '';\n//       } else if (typeof val === 'number') {\n//         val = '' + val;\n//       } else if (typeof val !== 'string') {\n//         val = JSON.stringify(val);\n//       }\n//       if (val.indexOf('\\n') >= 0) {\n//         val = JSON.stringify(val);\n//       }\n//       return [key, val];\n//     });\n//   // add npm_config_*\n//   for (const [key, val] of cleaned) {\n//     const cleanKey = key.replace(/^_+/, '');\n//     const envKey = `npm_config_${cleanKey}`.replace(INVALID_CHAR_REGEX, '_');\n//     env[envKey] = val;\n//   }\n//   // add npm_package_config_*\n//   if (manifest && manifest.name) {\n//     const packageConfigPrefix = `${manifest.name}:`;\n//     for (const [key, val] of cleaned) {\n//       if (key.indexOf(packageConfigPrefix) !== 0) {\n//         continue;\n//       }\n//       const cleanKey = key.replace(/^_+/, '').replace(packageConfigPrefix, '');\n//       const envKey = `npm_package_config_${cleanKey}`.replace(INVALID_CHAR_REGEX, '_');\n//       env[envKey] = val;\n//     }\n//   }\n//   // split up the path\n//   const envPath = env[constants.ENV_PATH_KEY];\n//   const pathParts = envPath ? envPath.split(path.delimiter) : [];\n//   // Include the directory that contains node so that we can guarantee that the scripts\n//   // will always run with the exact same Node release than the one use to run Pika\n//   const execBin = path.dirname(process.execPath);\n//   if (pathParts.indexOf(execBin) === -1) {\n//     pathParts.unshift(execBin);\n//   }\n//   // Include node-gyp version that was bundled with the current Node.js version,\n//   // if available.\n//   pathParts.unshift(path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'node-gyp-bin'));\n//   pathParts.unshift(\n//     path.join(path.dirname(process.execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin'),\n//   );\n//   // Include node-gyp version from homebrew managed npm, if available.\n//   pathParts.unshift(\n//     path.join(path.dirname(process.execPath), '..', 'libexec', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin'),\n//   );\n//   // Add global bin folder if it is not present already, as some packages depend\n//   // on a globally-installed version of node-gyp.\n//   const globalBin = await getGlobalBinFolder(config, {});\n//   if (pathParts.indexOf(globalBin) === -1) {\n//     pathParts.unshift(globalBin);\n//   }\n//   // Add node_modules .bin folders to the PATH\n//   for (const registry of Object.keys(registries)) {\n//     const binFolder = path.join(config.registries[registry].folder, '.bin');\n//     if (config.workspacesEnabled && config.workspaceRootFolder) {\n//       pathParts.unshift(path.join(config.workspaceRootFolder, binFolder));\n//     }\n//     pathParts.unshift(path.join(config.linkFolder, binFolder));\n//     pathParts.unshift(path.join(cwd, binFolder));\n//     if (config.modulesFolder) {\n//       pathParts.unshift(path.join(config.modulesFolder, '.bin'));\n//     }\n//   }\n//   if (await fs.exists(`${config.lockfileFolder}/${constants.PNP_FILENAME}`)) {\n//     // TODO: Fix. import()? Do we even like that it does this?\n//     throw new Error(\"pnp temporarily not supported\");\n//     const pnpApi = {}; //dynamicRequire(`${config.lockfileFolder}/${constants.PNP_FILENAME}`);\n//     const packageLocator = pnpApi.findPackageLocator(`${config.cwd}/`);\n//     const packageInformation = pnpApi.getPackageInformation(packageLocator);\n//     for (const [name, reference] of packageInformation.packageDependencies.entries()) {\n//       const dependencyInformation = pnpApi.getPackageInformation({name, reference});\n//       if (!dependencyInformation || !dependencyInformation.packageLocation) {\n//         continue;\n//       }\n//       pathParts.unshift(`${dependencyInformation.packageLocation}/.bin`);\n//     }\n//   }\n//   pathParts.unshift(await getWrappersFolder(config));\n//   // join path back together\n//   env[constants.ENV_PATH_KEY] = pathParts.join(path.delimiter);\n//   return env;\n// }\n\nasync function executeLifecycleScript({\n  // config,\n  cwd,\n  cmd,\n  args,\n  isInteractive,\n  onProgress,\n  customShell\n}) {\n  const env = await makeEnv(); // await checkForGypIfNeeded(config, cmd, env[constants.ENV_PATH_KEY].split(path.delimiter));\n\n  if (process.platform === 'win32' && (!customShell || customShell === 'cmd')) {\n    // handle windows run scripts starting with a relative path\n    cmd = fixCmdWinSlashes(cmd);\n  } // By default (non-interactive), pipe everything to the terminal and run child process detached\n  // as long as it's not Windows (since windows does not have /dev/tty)\n\n\n  let stdio = ['ignore', 'pipe', 'pipe'];\n  let detached = process.platform !== 'win32';\n\n  if (isInteractive) {\n    stdio = 'inherit';\n    detached = false;\n  }\n\n  const shell = customShell || true;\n  const stdout = await spawn(cmd, args, {\n    cwd,\n    env,\n    stdio,\n    detached,\n    shell\n  }, onProgress);\n  return {\n    cwd,\n    command: cmd,\n    stdout\n  };\n}\n// // /**\n// //  * Special case: Some packages depend on node-gyp, but don't specify this in\n// //  * their package.json dependencies. They assume that node-gyp is available\n// //  * globally. We need to detect this case and show an error message.\n// //  */\n// function checkForGypIfNeeded(config: Config, cmd: string, paths: Array<string>): Promise<void> {\n//   if (cmd.substr(0, cmd.indexOf(' ')) !== 'node-gyp') {\n//     return Promise.resolve();\n//   }\n//   // Ensure this only runs once, rather than multiple times in parallel.\n//   if (!checkGypPromise) {\n//     checkGypPromise = _checkForGyp(config, paths);\n//   }\n//   return checkGypPromise;\n// }\n// async function _checkForGyp(config: Config, paths: Array<string>): Promise<void> {\n//   const {reporter} = config;\n//   // Check every directory in the PATH\n//   const allChecks = await Promise.all(paths.map(dir => fs.exists(path.join(dir, 'node-gyp'))));\n//   if (allChecks.some(Boolean)) {\n//     // node-gyp is available somewhere\n//     return;\n//   }\n//   reporter.info(reporter.lang('packageRequiresNodeGyp'));\n// }\n// export async function execFromDistributions(config: Config, cwd: string, dist: string, step: string): Promise<void> {\n//   const pkg = await config.maybeReadManifest(cwd);\n//   if (!pkg || !pkg.distributions || !pkg.distributions[dist] || typeof pkg.distributions[dist][step] !== 'string') {\n//     return false;\n//   }\n//   const cmd: ?string = pkg.distributions[dist][step];\n//   await execCommand({stage: 'build', config, cmd, cwd, isInteractive: true});\n//   return true;\n// }\n// export async function execFromManifest(config: Config, commandName: string, cwd: string): Promise<void> {\n//   const pkg = await config.maybeReadManifest(cwd);\n//   if (!pkg || !pkg.scripts) {\n//     return;\n//   }\n//   const cmd: ?string = pkg.scripts[commandName];\n//   if (cmd) {\n//     await execCommand({stage: commandName, config, cmd, cwd, isInteractive: true});\n//   }\n// }\n// export async function execCommand({\n//   stage,\n//   config,\n//   cmd,\n//   cwd,\n//   isInteractive,\n//   customShell,\n// }: {\n//   stage: string;\n//   config: Config;\n//   cmd: string;\n//   cwd: string;\n//   isInteractive: boolean;\n//   customShell?: string;\n// }): Promise<void> {\n//   const {reporter} = config;\n//   try {\n//     reporter.command(cmd);\n//     await executeLifecycleScript({config, cwd, cmd, isInteractive, customShell});\n//     return Promise.resolve();\n//   } catch (err) {\n//     if (err instanceof ProcessTermError) {\n//       throw new MessageError(\n//         err.EXIT_SIGNAL\n//           ? reporter.lang('commandFailedWithSignal', err.EXIT_SIGNAL)\n//           : reporter.lang('commandFailedWithCode', err.EXIT_CODE),\n//       );\n//     } else {\n//       throw err;\n//     }\n//   }\n// }\n\nclass Config {\n  constructor(reporter, cwd, flags) {\n    this.reporter = reporter; // Ensure the cwd is always an absolute path.\n\n    this.cwd = path.resolve(cwd || process.cwd());\n    this.flags = flags;\n  }\n\n  async loadPackageManifest() {\n    const loc = path.join(this.cwd, NODE_PACKAGE_JSON);\n\n    if (await exists(loc)) {\n      const info = await this.readJson(loc, readJsonAndFile);\n      this._manifest = _objectSpread2({}, info.object);\n      this.manifest = await normalizeManifest(info.object, this.cwd, this, true);\n      return this.manifest;\n    } else {\n      return null;\n    }\n  }\n\n  readJson(loc, factory = readJson) {\n    try {\n      return factory(loc);\n    } catch (err) {\n      if (err instanceof SyntaxError) {\n        throw new types.MessageError(this.reporter.lang('jsonError', loc, err.message));\n      } else {\n        throw err;\n      }\n    }\n  }\n\n  async getDistributions() {\n    const raw = this.manifest[`@pika/pack`] || {};\n    const override = this.flags.pipeline && JSON.parse(this.flags.pipeline);\n    const cwd = this.cwd;\n\n    function cleanRawDistObject(rawVal) {\n      if (Array.isArray(rawVal)) {\n        let importStr = rawVal[0].startsWith('./') || rawVal[0].startsWith('../') ? path.join(cwd, rawVal[0]) : rawVal[0];\n        return [_objectSpread2({}, importFrom(cwd, importStr), {\n          name: rawVal[0]\n        }), rawVal[1] || {}];\n      }\n\n      if (typeof rawVal === 'string') {\n        return [{\n          build: ({\n            cwd\n          }) => {\n            return executeLifecycleScript({\n              // config: this,\n              args: [],\n              cwd,\n              cmd: rawVal,\n              isInteractive: false\n            });\n          }\n        }, {}];\n      }\n\n      if (!rawVal) {\n        throw new Error('Cannot be false');\n      }\n\n      return false;\n    }\n\n    const pipeline = override || raw.pipeline || [];\n    return pipeline.map(cleanRawDistObject).filter(Boolean);\n  }\n\n}\n\nfunction forwardSignalAndExit(signal) {\n  forwardSignalToSpawnedProcesses(signal); // We want to exit immediately here since `SIGTERM` means that\n  // If we lose stdout messages due to abrupt exit, shoot the messenger?\n\n  process.exit(1); // eslint-disable-line no-process-exit\n}\n\nfunction handleSignals() {\n  process.on('SIGTERM', () => {\n    forwardSignalAndExit('SIGTERM');\n  });\n}\n\nconst FALSY_STRINGS = new Set(['0', 'false']);\nfunction boolify(val) {\n  return !FALSY_STRINGS.has(val.toString().toLowerCase());\n}\nfunction boolifyWithDefault(val, defaultResult) {\n  return val === '' || val === null || val === undefined ? defaultResult : boolify(val);\n}\n\nconst currentFilename = uri2path((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.js', document.baseURI).href)));\n\nfunction getVersion() {\n  const packageJsonContent = fs.readFileSync(path.resolve(currentFilename, '../../package.json'), {\n    encoding: 'utf-8'\n  });\n  const {\n    version\n  } = nullify(JSON.parse(stripBOM(packageJsonContent)));\n  return version;\n}\n\nfunction printHelp() {\n  console.log(`\n${chalk.bold(`@pika/pack`)} - Build npm packages without the mess.\n${chalk.bold('Options:')}\n    --cwd               Set the current working directory.\n    --out               Set the output directory. Defaults to \"pkg/\".\n    --pipeline          Set a build pipeline via JSON string.\n    --force             Continue with the build when a build plugin fails or throws an exception.\n    --json              Log output as JSON.\n    --verbose           Log additional debugging information.\n    --silent            Log almost nothing.\n    --help              Print help.\n    --version, -v       Print version.\n    `.trim());\n}\n\nasync function cli(args) {\n  const version = getVersion();\n  loudRejection();\n  handleSignals(); // Handle special flags\n\n  if (args.find(arg => arg === '--version' || arg === '-v')) {\n    console.log(version.trim());\n    process.exitCode = 0;\n    return;\n  }\n\n  if (args.find(arg => arg === '--help')) {\n    printHelp();\n    process.exitCode = 0;\n    return;\n  } // Handle the legacy CLI interface\n\n\n  if (args[2] === 'publish') {\n    console.log(`The publish flow has moved to the @pika/cli package (included with this package).\nUpdate your publish script to: ${chalk.bold('pika publish [flags]')}\n`);\n    process.exitCode = 1;\n    return;\n  }\n\n  if (args[2] === 'build') {\n    console.log(chalk.yellow(`Note: This CLI was recently deprecated. Update your build script to: ${chalk.bold('pika build [flags]')}`));\n    args.splice(2, 1);\n  }\n\n  const flags = yargs(args);\n  const cwd = flags.cwd || process.cwd();\n  const Reporter = flags.json ? JSONReporter : ConsoleReporter;\n  const reporter = new Reporter({\n    emoji: true,\n    verbose: flags.verbose,\n    isSilent: boolifyWithDefault(process.env.PIKA_SILENT, false) || flags.silent\n  });\n\n  const exit = (exitCode = 0) => {\n    process.exitCode = exitCode;\n    reporter.close();\n  };\n\n  const command = buildCommand;\n  reporter.initPeakMemoryCounter();\n  const outputWrapperEnabled = boolifyWithDefault(process.env.PIKA_WRAP_OUTPUT, true);\n  const shouldWrapOutput = outputWrapperEnabled && !flags.json && command.hasWrapper();\n\n  if (shouldWrapOutput) {\n    reporter.header({\n      name: '@pika/pack',\n      version\n    });\n  }\n\n  const run = () => {\n    invariant(command, 'missing command');\n    return command.run(config, reporter, flags, args).then(exitCode => {\n      if (shouldWrapOutput) {\n        reporter.footer(false);\n      }\n\n      return exitCode;\n    });\n  };\n\n  function onUnexpectedError(err) {\n    function indent(str) {\n      return '\\n  ' + str.trim().split('\\n').join('\\n  ');\n    }\n\n    const log = [];\n    log.push(`Arguments: ${indent(process.argv.join(' '))}`);\n    log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`);\n    log.push(`Pika version: ${indent(version)}`);\n    log.push(`Node version: ${indent(process.versions.node)}`);\n    log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`);\n    log.push(`Trace: ${indent(err.stack)}`);\n    reporter.error(reporter.lang('unexpectedError', err.message));\n  }\n\n  const config = new Config(reporter, cwd, flags);\n  await config.loadPackageManifest();\n\n  try {\n    // option \"no-progress\" stored in pika config\n    const noProgressConfig = false; //config.registries.pika.getOption('no-progress');\n\n    if (noProgressConfig) {\n      reporter.disableProgress();\n    } // verbose logs outputs process.uptime() with this line we can sync uptime to absolute time on the computer\n\n\n    reporter.verbose(`current time: ${new Date().toISOString()}`);\n    return run().then(exit);\n  } catch (err) {\n    reporter.verbose(err.stack);\n\n    if (err instanceof types.MessageError) {\n      reporter.error(err.message);\n    } else {\n      onUnexpectedError(err);\n    }\n\n    return exit(1);\n  }\n}\n\nexports.cli = cli;\n//# sourceMappingURL=index.js.map\n"
  },
  {
    "path": "checkpoint/dist-src/commands/build.js",
    "content": "import chalk from 'chalk';\nimport * as path from 'path';\nimport { DEFAULT_INDENT } from '../constants.js';\nimport * as fs from '../util/fs.js';\nimport { generatePrettyManifest, generatePublishManifest } from '../util/normalize-manifest/for-publish.js';\nexport function hasWrapper() {\n    return true;\n}\nexport const examples = null;\nexport class Build {\n    constructor(flags, config, reporter) {\n        this.flags = flags;\n        this.config = config;\n        this.reporter = reporter;\n        this.totalNum = 0;\n        this.out = path.resolve(config.cwd, flags.out || 'pkg/');\n        if (this.out === this.config.cwd) {\n            throw new Error('On publish, you cannot write to cwd because a package.json is created');\n        }\n    }\n    async cleanup() {\n        const { out } = this;\n        await fs.unlink(path.join(out, '*'));\n    }\n    async init(isFull) {\n        const { config, out, reporter, flags } = this;\n        const { cwd } = config;\n        const outPretty = path.relative(cwd, out) + path.sep;\n        const manifest = await config.manifest;\n        const { sourcemap } = manifest['@pika/pack'] || { sourcemap: true };\n        const distRunners = await config.getDistributions();\n        const builderConfig = {\n            out,\n            cwd,\n            reporter: {\n                info: msg => reporter.log(chalk.dim(`      » ${msg}`)),\n                warning: msg => reporter.log(chalk.yellow(`      » ${msg}`)),\n                success: msg => reporter.log(chalk.green(`      » ${msg}`)),\n                created: (filename, entrypoint) => reporter.log(`      📝  ${chalk.green(path.relative(cwd, filename))} ${entrypoint ? chalk.dim(`[${entrypoint}]`) : ''}`),\n            },\n            isFull,\n            manifest,\n            src: {\n                loc: path.join(out, 'dist-src'),\n                entrypoint: path.join(out, 'dist-src', 'index.js'),\n                // TODO: Deprecated, remove\n                options: {},\n                // TODO: Deprecated, remove\n                files: await (async () => {\n                    const ignoreSet = new Set([]);\n                    ignoreSet.add('**/*/README.md');\n                    const files = await fs.glob(`src/**/*`, {\n                        cwd,\n                        nodir: true,\n                        absolute: true,\n                        ignore: Array.from(ignoreSet).map(g => path.join('src', g)),\n                    });\n                    return files.filter(fileAbs => !fileAbs.endsWith('.d.ts'));\n                })(),\n            },\n        };\n        const steps = [];\n        steps.push(async (curr, total) => {\n            this.reporter.step(curr, total, 'Validating source');\n            for (const [runner, options] of distRunners) {\n                if (runner.validate) {\n                    const result = await runner.validate({\n                        ...builderConfig,\n                        options: { sourcemap, ...options },\n                    });\n                    if (result instanceof Error) {\n                        throw result;\n                    }\n                }\n            }\n        });\n        steps.push(async (curr, total) => {\n            this.reporter.step(curr, total, `Preparing pipeline`);\n            await this.cleanup();\n            reporter.log(`      ❇️  ${chalk.green(outPretty)}`);\n            for (const [runner, options] of distRunners) {\n                await (runner.beforeBuild &&\n                    runner.beforeBuild({\n                        ...builderConfig,\n                        options: { sourcemap, ...options },\n                    }));\n            }\n        });\n        if (distRunners.length === 0) {\n            steps.push(async (curr, total) => {\n                this.reporter.step(curr, total, `Pipeline is empty! See ${chalk.underline('https://github.com/pikapkg/pack')} for help getting started`);\n            });\n        }\n        for (const [runner, options] of distRunners) {\n            steps.push(async (curr, total) => {\n                this.reporter.step(curr, total, `Running ${chalk.bold(runner.name)}`);\n                // return Promise.resolve(\n                try {\n                    await (runner.beforeJob &&\n                        runner.beforeJob({\n                            ...builderConfig,\n                            options: { sourcemap, ...options },\n                        }));\n                    await (runner.build &&\n                        runner.build({\n                            ...builderConfig,\n                            options: { sourcemap, ...options },\n                        }));\n                    await (runner.afterJob &&\n                        runner.afterJob({\n                            ...builderConfig,\n                            options: { sourcemap, ...options },\n                        }));\n                }\n                catch (err) {\n                    if (flags.force) {\n                        console.log('      ❗️  ', chalk.red(err.message), chalk.dim('--force, continuing...'));\n                    }\n                    else {\n                        throw err;\n                    }\n                }\n                // ).catch(err => {\n                // log(chalk.red(err.message));\n                // reporter.log(\n                //   reporter.lang(\"distFailed\", runner.name, err.code, err.message),\n                //   { force: true }\n                // );\n                // if (err.forceExit === true) {\n                // reporter.log(reporter.lang(\"distExiting\"));\n                // throw err;\n                // return;\n                // }\n                // reporter.log(reporter.lang(\"distContinuing\"));\n                // });\n            });\n        }\n        steps.push(async (curr, total) => {\n            this.reporter.step(curr, total, `Finalizing package`);\n            for (const [runner, options] of distRunners) {\n                await (runner.afterBuild &&\n                    runner.afterBuild({\n                        ...builderConfig,\n                        options: { sourcemap, ...options },\n                    }));\n            }\n            if (await fs.exists(path.join(cwd, 'CHANGELOG'))) {\n                fs.copyFile(path.join(cwd, 'CHANGELOG'), path.join(out, 'CHANGELOG'));\n                reporter.log(chalk.dim(`      » copying CHANGELOG...`));\n            }\n            else if (await fs.exists(path.join(cwd, 'CHANGELOG.md'))) {\n                fs.copyFile(path.join(cwd, 'CHANGELOG.md'), path.join(out, 'CHANGELOG.md'));\n                reporter.log(chalk.dim(`      » copying CHANGELOG.md...`));\n            }\n            if (await fs.exists(path.join(cwd, 'LICENSE'))) {\n                fs.copyFile(path.join(cwd, 'LICENSE'), path.join(out, 'LICENSE'));\n                reporter.log(chalk.dim(`      » copying LICENSE...`));\n            }\n            else if (await fs.exists(path.join(cwd, 'LICENSE.md'))) {\n                fs.copyFile(path.join(cwd, 'LICENSE.md'), path.join(out, 'LICENSE.md'));\n                reporter.log(chalk.dim(`      » copying LICENSE.md...`));\n            }\n            if (await fs.exists(path.join(cwd, 'README'))) {\n                fs.copyFile(path.join(cwd, 'README'), path.join(out, 'README'));\n                reporter.log(chalk.dim(`      » copying README...`));\n            }\n            else if (await fs.exists(path.join(cwd, 'README.md'))) {\n                fs.copyFile(path.join(cwd, 'README.md'), path.join(out, 'README.md'));\n                reporter.log(chalk.dim(`      » copying README.md...`));\n            }\n            const publishManifest = await generatePublishManifest(config._manifest, config, distRunners);\n            if (out === cwd) {\n                reporter.log(`NEW MANIFEST:\\n\\n`);\n                reporter.log(generatePrettyManifest(publishManifest));\n                reporter.log(`\\n\\n`);\n            }\n            else {\n                await fs.writeFilePreservingEol(path.join(out, 'package.json'), JSON.stringify(publishManifest, null, DEFAULT_INDENT) + '\\n');\n                reporter.log(`      📝  ` + chalk.green(outPretty + 'package.json'));\n            }\n            reporter.log(`      📦  ` + chalk.green(outPretty));\n        });\n        let currentStep = 0;\n        for (const step of steps) {\n            await step(++currentStep, steps.length);\n        }\n    }\n}\nexport async function run(config, reporter, flags, args) {\n    const isProduction = flags.publish;\n    const builder = new Build(flags, config, reporter);\n    await builder.init(isProduction);\n}\n"
  },
  {
    "path": "checkpoint/dist-src/config.js",
    "content": "import * as path from 'path';\nimport * as constants from './constants.js';\nimport { MessageError } from '@pika/types';\nimport * as fs from './util/fs.js';\nimport normalizeManifest from './util/normalize-manifest/index.js';\nimport executeLifecycleScript from './util/execute-lifecycle-script.js';\nimport importFrom from 'import-from';\n;\n;\nexport default class Config {\n    constructor(reporter, cwd, flags) {\n        this.reporter = reporter;\n        // Ensure the cwd is always an absolute path.\n        this.cwd = path.resolve(cwd || process.cwd());\n        this.flags = flags;\n    }\n    async loadPackageManifest() {\n        const loc = path.join(this.cwd, constants.NODE_PACKAGE_JSON);\n        if (await fs.exists(loc)) {\n            const info = await this.readJson(loc, fs.readJsonAndFile);\n            this._manifest = { ...info.object };\n            this.manifest = await normalizeManifest(info.object, this.cwd, this, true);\n            return this.manifest;\n        }\n        else {\n            return null;\n        }\n    }\n    readJson(loc, factory = fs.readJson) {\n        try {\n            return factory(loc);\n        }\n        catch (err) {\n            if (err instanceof SyntaxError) {\n                throw new MessageError(this.reporter.lang('jsonError', loc, err.message));\n            }\n            else {\n                throw err;\n            }\n        }\n    }\n    async getDistributions() {\n        const raw = this.manifest[`@pika/pack`] || {};\n        const override = this.flags.pipeline && JSON.parse(this.flags.pipeline);\n        const cwd = this.cwd;\n        function cleanRawDistObject(rawVal) {\n            if (Array.isArray(rawVal)) {\n                let importStr = (rawVal[0].startsWith('./') || rawVal[0].startsWith('../')) ? path.join(cwd, rawVal[0]) : rawVal[0];\n                return [{ ...importFrom(cwd, importStr), name: rawVal[0] }, rawVal[1] || {}];\n            }\n            if (typeof rawVal === 'string') {\n                return [{ build: ({ cwd }) => {\n                            return executeLifecycleScript({\n                                // config: this,\n                                args: [],\n                                cwd,\n                                cmd: rawVal,\n                                isInteractive: false\n                            });\n                        } }, {}];\n            }\n            if (!rawVal) {\n                throw new Error('Cannot be false');\n            }\n            return false;\n        }\n        const pipeline = override || raw.pipeline || [];\n        return pipeline.map(cleanRawDistObject).filter(Boolean);\n    }\n}\n"
  },
  {
    "path": "checkpoint/dist-src/constants.js",
    "content": "// import os from 'os';\n// import * as path from 'path';\n// import userHome from './util/user-home-dir.js';\n// import {getCacheDir, getConfigDir, getDataDir} from './util/user-dirs.js';\nexport const DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDependencies'];\n// export const OWNED_DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDependencies'];\nexport const RESOLUTIONS = 'resolutions';\nexport const MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES];\nexport const SUPPORTED_NODE_VERSIONS = '>=8.5.0';\n// export const PIKA_REGISTRY = 'https://registry.npmjs.org';\n// export const NPM_REGISTRY_RE = /https?:\\/\\/registry\\.npmjs\\.org/g;\n// export const PIKA_DOCS = 'https://yarnpkg.com/en/docs/cli/';\n// export const PIKA_INSTALLER_SH = 'https://yarnpkg.com/install.sh';\n// export const PIKA_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi';\n// export const SELF_UPDATE_VERSION_URL = 'https://www.pikapkg.com/downloads/latest-version';\n// // cache version, bump whenever we make backwards incompatible changes\n// export const CACHE_VERSION = 3;\n// // lockfile version, bump whenever we make backwards incompatible changes\n// export const LOCKFILE_VERSION = 1;\n// // max amount of network requests to perform concurrently\n// export const NETWORK_CONCURRENCY = 8;\n// // HTTP timeout used when downloading packages\n// export const NETWORK_TIMEOUT = 30 * 1000; // in milliseconds\n// // max amount of child processes to execute concurrently\nexport const CHILD_CONCURRENCY = 5;\n// export const REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid'];\n// function getPreferredCacheDirectories(): Array<string> {\n//   const preferredCacheDirectories = [getCacheDir()];\n//   if (process.getuid) {\n//     // $FlowFixMe: process.getuid exists, dammit\n//     preferredCacheDirectories.push(path.join(os.tmpdir(), `.pika-cache-${process.getuid()}`));\n//   }\n//   preferredCacheDirectories.push(path.join(os.tmpdir(), `.pika-cache`));\n//   return preferredCacheDirectories;\n// }\n// export const PREFERRED_MODULE_CACHE_DIRECTORIES = getPreferredCacheDirectories();\n// export const CONFIG_DIRECTORY = getConfigDir();\n// export const DATA_DIRECTORY = getDataDir();\n// export const LINK_REGISTRY_DIRECTORY = path.join(DATA_DIRECTORY, 'link');\n// export const GLOBAL_MODULE_DIRECTORY = path.join(DATA_DIRECTORY, 'global');\n// export const NODE_BIN_PATH = process.execPath;\nexport const NODE_MODULES_FOLDER = 'node_modules';\nexport const NODE_PACKAGE_JSON = 'package.json';\n// export const PNP_FILENAME = '.pnp';\n// export const POSIX_GLOBAL_PREFIX = `${process.env.DESTDIR || ''}/usr/local`;\n// export const FALLBACK_GLOBAL_PREFIX = path.join(userHome, '.pika');\n// export const META_FOLDER = '.pika-meta';\n// export const INTEGRITY_FILENAME = '.pika-integrity';\n// export const LOCKFILE_FILENAME = 'pika.lock';\n// export const LEGACY_LOCKFILE_FILENAME = 'yarn.lock';\n// export const METADATA_FILENAME = '.pika-metadata.json';\n// export const TARBALL_FILENAME = '.pika-tarball.tgz';\n// export const CLEAN_FILENAME = '.pikaclean';\n// export const NPM_LOCK_FILENAME = 'package-lock.json';\n// export const NPM_SHRINKWRAP_FILENAME = 'npm-shrinkwrap.json';\nexport const DEFAULT_INDENT = '  ';\n// export const SINGLE_INSTANCE_PORT = 31997;\n// export const SINGLE_INSTANCE_FILENAME = '.pika-single-instance';\nexport const ENV_PATH_KEY = getPathKey(process.platform, process.env);\nexport function getPathKey(platform, env) {\n    let pathKey = 'PATH';\n    // windows calls its path \"Path\" usually, but this is not guaranteed.\n    if (platform === 'win32') {\n        pathKey = 'Path';\n        for (const key in env) {\n            if (key.toLowerCase() === 'path') {\n                pathKey = key;\n            }\n        }\n    }\n    return pathKey;\n}\n// export const VERSION_COLOR_SCHEME: {[key: string]: VersionColor} = {\n//   major: 'red',\n//   premajor: 'red',\n//   minor: 'yellow',\n//   preminor: 'yellow',\n//   patch: 'green',\n//   prepatch: 'green',\n//   prerelease: 'red',\n//   unchanged: 'white',\n//   unknown: 'red',\n// };\n// export type VersionColor = 'red' | 'yellow' | 'green' | 'white';\n// export type RequestHint = 'dev' | 'optional' | 'resolution' | 'workspaces';\n"
  },
  {
    "path": "checkpoint/dist-src/errors.js",
    "content": "import { MessageError } from '@pika/types';\nexport class ProcessSpawnError extends MessageError {\n    constructor(msg, code, process) {\n        super(msg);\n        this.code = code;\n        this.process = process;\n    }\n}\nexport class SecurityError extends MessageError {\n}\nexport class ProcessTermError extends MessageError {\n}\nexport class ResponseError extends Error {\n    constructor(msg, responseCode) {\n        super(msg);\n        this.responseCode = responseCode;\n    }\n}\nexport class OneTimePasswordError extends Error {\n}\n"
  },
  {
    "path": "checkpoint/dist-src/index.js",
    "content": "import * as path from 'path';\nimport chalk from 'chalk';\nimport * as fs from 'fs';\nimport invariant from 'invariant';\nimport loudRejection from 'loud-rejection';\nimport { ConsoleReporter, JSONReporter } from './reporters/index.js';\nimport * as buildCommand from './commands/build.js';\nimport { MessageError } from '@pika/types';\nimport Config from './config.js';\nimport handleSignals from './util/signal-handler.js';\nimport { boolifyWithDefault } from './util/conversion.js';\nimport map from './util/map.js';\nimport stripBOM from 'strip-bom';\nimport uri2path from 'file-uri-to-path';\nimport yargs from 'yargs-parser';\n// @ts-ignore\nconst currentFilename = uri2path(import.meta.url);\nfunction getVersion() {\n    const packageJsonContent = fs.readFileSync(path.resolve(currentFilename, '../../package.json'), { encoding: 'utf-8' });\n    const { version } = map(JSON.parse(stripBOM(packageJsonContent)));\n    return version;\n}\nfunction printHelp() {\n    console.log(`\n${chalk.bold(`@pika/pack`)} - Build npm packages without the mess.\n${chalk.bold('Options:')}\n    --cwd               Set the current working directory.\n    --out               Set the output directory. Defaults to \"pkg/\".\n    --pipeline          Set a build pipeline via JSON string.\n    --force             Continue with the build when a build plugin fails or throws an exception.\n    --json              Log output as JSON.\n    --verbose           Log additional debugging information.\n    --silent            Log almost nothing.\n    --help              Print help.\n    --version, -v       Print version.\n    `.trim());\n}\nexport async function cli(args) {\n    const version = getVersion();\n    loudRejection();\n    handleSignals();\n    // Handle special flags\n    if (args.find(arg => arg === '--version' || arg === '-v')) {\n        console.log(version.trim());\n        process.exitCode = 0;\n        return;\n    }\n    if (args.find(arg => arg === '--help')) {\n        printHelp();\n        process.exitCode = 0;\n        return;\n    }\n    // Handle the legacy CLI interface\n    if (args[2] === 'publish') {\n        console.log(`The publish flow has moved to the @pika/cli package (included with this package).\nUpdate your publish script to: ${chalk.bold('pika publish [flags]')}\n`);\n        process.exitCode = 1;\n        return;\n    }\n    if (args[2] === 'build') {\n        console.log(chalk.yellow(`Note: This CLI was recently deprecated. Update your build script to: ${chalk.bold('pika build [flags]')}`));\n        args.splice(2, 1);\n    }\n    const flags = yargs(args);\n    const cwd = flags.cwd || process.cwd();\n    const Reporter = flags.json ? JSONReporter : ConsoleReporter;\n    const reporter = new Reporter({\n        emoji: true,\n        verbose: flags.verbose,\n        isSilent: boolifyWithDefault(process.env.PIKA_SILENT, false) || flags.silent,\n    });\n    const exit = (exitCode = 0) => {\n        process.exitCode = exitCode;\n        reporter.close();\n    };\n    const command = buildCommand;\n    reporter.initPeakMemoryCounter();\n    const outputWrapperEnabled = boolifyWithDefault(process.env.PIKA_WRAP_OUTPUT, true);\n    const shouldWrapOutput = outputWrapperEnabled && !flags.json && command.hasWrapper();\n    if (shouldWrapOutput) {\n        reporter.header({ name: '@pika/pack', version });\n    }\n    const run = () => {\n        invariant(command, 'missing command');\n        return command.run(config, reporter, flags, args).then(exitCode => {\n            if (shouldWrapOutput) {\n                reporter.footer(false);\n            }\n            return exitCode;\n        });\n    };\n    function onUnexpectedError(err) {\n        function indent(str) {\n            return '\\n  ' + str.trim().split('\\n').join('\\n  ');\n        }\n        const log = [];\n        log.push(`Arguments: ${indent(process.argv.join(' '))}`);\n        log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`);\n        log.push(`Pika version: ${indent(version)}`);\n        log.push(`Node version: ${indent(process.versions.node)}`);\n        log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`);\n        log.push(`Trace: ${indent(err.stack)}`);\n        reporter.error(reporter.lang('unexpectedError', err.message));\n    }\n    const config = new Config(reporter, cwd, flags);\n    await config.loadPackageManifest();\n    try {\n        // option \"no-progress\" stored in pika config\n        const noProgressConfig = false; //config.registries.pika.getOption('no-progress');\n        if (noProgressConfig) {\n            reporter.disableProgress();\n        }\n        // verbose logs outputs process.uptime() with this line we can sync uptime to absolute time on the computer\n        reporter.verbose(`current time: ${new Date().toISOString()}`);\n        return run().then(exit);\n    }\n    catch (err) {\n        reporter.verbose(err.stack);\n        if (err instanceof MessageError) {\n            reporter.error(err.message);\n        }\n        else {\n            onUnexpectedError(err);\n        }\n        return exit(1);\n    }\n}\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/base-reporter.js",
    "content": "import { defaultFormatter } from './format.js';\nimport * as languages from './lang/index.js';\nimport * as isCI from 'is-ci';\nimport * as os from 'os';\nimport * as util from 'util';\nimport { EventEmitter } from 'events';\nexport function stringifyLangArgs(args) {\n    return args.map(function (val) {\n        if (val != null && val.inspect) {\n            return val.inspect();\n        }\n        else {\n            try {\n                const str = JSON.stringify(val) || val + '';\n                // should match all literal line breaks and\n                // \"u001b\" that follow an odd number of backslashes and convert them to ESC\n                // we do this because the JSON.stringify process has escaped these characters\n                return str\n                    .replace(/((?:^|[^\\\\])(?:\\\\{2})*)\\\\u001[bB]/g, '$1\\u001b')\n                    .replace(/[\\\\]r[\\\\]n|([\\\\])?[\\\\]n/g, (match, precededBacklash) => {\n                    // precededBacklash not null when \"\\n\" is preceded by a backlash (\"\\\\n\")\n                    // match will be \"\\\\n\" and we don't replace it with os.EOL\n                    return precededBacklash ? match : os.EOL;\n                });\n            }\n            catch (e) {\n                return util.inspect(val);\n            }\n        }\n    });\n}\nexport default class BaseReporter {\n    constructor(opts = {}) {\n        const lang = 'en';\n        this.language = lang;\n        this.stdout = opts.stdout || process.stdout;\n        this.stderr = opts.stderr || process.stderr;\n        this.stdin = opts.stdin || this._getStandardInput();\n        this.emoji = !!opts.emoji;\n        this.nonInteractive = !!opts.nonInteractive;\n        this.noProgress = !!opts.noProgress || isCI;\n        this.isVerbose = !!opts.verbose;\n        // @ts-ignore\n        this.isTTY = this.stdout.isTTY;\n        this.peakMemory = 0;\n        this.startTime = Date.now();\n        this.format = defaultFormatter;\n    }\n    lang(key, ...args) {\n        const msg = languages[this.language][key] || languages.en[key];\n        if (!msg) {\n            throw new ReferenceError(`No message defined for language key ${key}`);\n        }\n        // stringify args\n        const stringifiedArgs = stringifyLangArgs(args);\n        // replace $0 placeholders with args\n        return msg.replace(/\\$(\\d+)/g, (str, i) => {\n            return stringifiedArgs[i];\n        });\n    }\n    /**\n     * `stringifyLangArgs` run `JSON.stringify` on strings too causing\n     * them to appear quoted. This marks them as \"raw\" and prevents\n     * the quoting and escaping\n     */\n    rawText(str) {\n        return {\n            inspect() {\n                return str;\n            },\n        };\n    }\n    verbose(msg) {\n        if (this.isVerbose) {\n            this._verbose(msg);\n        }\n    }\n    verboseInspect(val) {\n        if (this.isVerbose) {\n            this._verboseInspect(val);\n        }\n    }\n    _verbose(msg) { }\n    _verboseInspect(val) { }\n    _getStandardInput() {\n        let standardInput;\n        // Accessing stdin in a win32 headless process (e.g., Visual Studio) may throw an exception.\n        try {\n            standardInput = process.stdin;\n        }\n        catch (e) {\n            console.warn(e.message);\n            delete process.stdin;\n            // @ts-ignore\n            process.stdin = new EventEmitter();\n            standardInput = process.stdin;\n        }\n        return standardInput;\n    }\n    initPeakMemoryCounter() {\n        this.checkPeakMemory();\n        this.peakMemoryInterval = setInterval(() => {\n            this.checkPeakMemory();\n        }, 1000);\n        // $FlowFixMe: Node's setInterval returns a Timeout, not a Number\n        this.peakMemoryInterval.unref();\n    }\n    checkPeakMemory() {\n        const { heapTotal } = process.memoryUsage();\n        if (heapTotal > this.peakMemory) {\n            this.peakMemory = heapTotal;\n        }\n    }\n    close() {\n        if (this.peakMemoryInterval) {\n            clearInterval(this.peakMemoryInterval);\n            this.peakMemoryInterval = null;\n        }\n    }\n    getTotalTime() {\n        return Date.now() - this.startTime;\n    }\n    // TODO\n    list(key, items, hints) { }\n    // Outputs basic tree structure to console\n    tree(key, obj, { force = false } = {}) { }\n    // called whenever we begin a step in the CLI.\n    step(current, total, message, emoji) { }\n    // a error message has been triggered. this however does not always meant an abrupt\n    // program end.\n    error(message) { }\n    // an info message has been triggered. this provides things like stats and diagnostics.\n    info(message) { }\n    // a warning message has been triggered.\n    warn(message) { }\n    // a success message has been triggered.\n    success(message) { }\n    // a simple log message\n    // TODO: rethink the {force} parameter. In the meantime, please don't use it (cf comments in #4143).\n    log(message, { force = false } = {}) { }\n    // a shell command has been executed\n    command(command) { }\n    // inspect and pretty-print any value\n    inspect(value) { }\n    // the screen shown at the very start of the CLI\n    header(pkg) { }\n    // the screen shown at the very end of the CLI\n    footer(showPeakMemory) { }\n    // a table structure\n    table(head, body) { }\n    // render an activity spinner and return a function that will trigger an update\n    activity() {\n        return {\n            tick(name) { },\n            end() { },\n        };\n    }\n    //\n    activitySet(total, workers) {\n        return {\n            spinners: Array(workers).fill({\n                clear() { },\n                setPrefix() { },\n                tick() { },\n                end() { },\n            }),\n            end() { },\n        };\n    }\n    // render a progress bar and return a function which when called will trigger an update\n    progress(total) {\n        return function () { };\n    }\n    // utility function to disable progress bar\n    disableProgress() {\n        this.noProgress = true;\n    }\n}\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/console/console-reporter.js",
    "content": "import chalk from 'chalk';\nimport * as readline from 'readline';\nimport stripAnsi from 'strip-ansi';\nimport { inspect } from 'util';\nimport { removeSuffix } from '../../util/misc.js';\nimport BaseReporter from '../base-reporter.js';\nimport { getFormattedOutput, recurseTree, sortTrees } from './helpers/tree-helper.js';\nimport Progress from './progress-bar.js';\nimport Spinner from './spinner-progress.js';\nimport { clearLine } from './util.js';\nconst AUDIT_COL_WIDTHS = [15, 62];\nconst auditSeverityColors = {\n    info: chalk.bold,\n    low: chalk.bold,\n    moderate: chalk.yellow,\n    high: chalk.red,\n    critical: chalk.bgRed,\n};\n// fixes bold on windows\nif (process.platform === 'win32' && !(process.env.TERM && /^xterm/i.test(process.env.TERM))) {\n    // @ts-ignore\n    chalk.bold._styles[0].close += '\\u001b[m';\n}\nexport default class ConsoleReporter extends BaseReporter {\n    constructor(opts) {\n        super(opts);\n        this._lastCategorySize = 0;\n        this._spinners = new Set();\n        this.format = chalk;\n        this.format.stripColor = stripAnsi;\n        this.isSilent = !!opts.isSilent;\n    }\n    _prependEmoji(msg, emoji) {\n        if (this.emoji && emoji && this.isTTY) {\n            msg = `${emoji}  ${msg}`;\n        }\n        return msg;\n    }\n    _logCategory(category, color, msg) {\n        this._lastCategorySize = category.length;\n        this._log(`${this.format[color](category)} ${msg}`);\n    }\n    _verbose(msg) {\n        this._logCategory('verbose', 'grey', `${process.uptime()} ${msg}`);\n    }\n    _verboseInspect(obj) {\n        this.inspect(obj);\n    }\n    close() {\n        for (const spinner of this._spinners) {\n            spinner.stop();\n        }\n        this._spinners.clear();\n        this.stopProgress();\n        super.close();\n    }\n    table(head, body) {\n        //\n        head = head.map((field) => this.format.underline(field));\n        //\n        const rows = [head].concat(body);\n        // get column widths\n        const cols = [];\n        for (let i = 0; i < head.length; i++) {\n            const widths = rows.map((row) => this.format.stripColor(row[i]).length);\n            cols[i] = Math.max(...widths);\n        }\n        //\n        const builtRows = rows.map((row) => {\n            for (let i = 0; i < row.length; i++) {\n                const field = row[i];\n                const padding = cols[i] - this.format.stripColor(field).length;\n                row[i] = field + ' '.repeat(padding);\n            }\n            return row.join(' ');\n        });\n        this.log(builtRows.join('\\n'));\n    }\n    step(current, total, msg, emoji) {\n        msg = this._prependEmoji(msg, emoji);\n        if (msg.endsWith('?')) {\n            msg = `${removeSuffix(msg, '?')}...?`;\n        }\n        else {\n            msg += '...';\n        }\n        this.log(`${this.format.dim(`[${current}/${total}]`)} ${msg}`);\n    }\n    inspect(value) {\n        if (typeof value !== 'number' && typeof value !== 'string') {\n            value = inspect(value, {\n                breakLength: 0,\n                colors: this.isTTY,\n                depth: null,\n                maxArrayLength: null,\n            });\n        }\n        this.log(String(value), { force: true });\n    }\n    list(key, items, hints) {\n        const gutterWidth = (this._lastCategorySize || 2) - 1;\n        if (hints) {\n            for (const item of items) {\n                this._log(`${' '.repeat(gutterWidth)}- ${this.format.bold(item)}`);\n                this._log(`  ${' '.repeat(gutterWidth)} ${hints[item]}`);\n            }\n        }\n        else {\n            for (const item of items) {\n                this._log(`${' '.repeat(gutterWidth)}- ${item}`);\n            }\n        }\n    }\n    header(pkg) {\n        this.log(this.format.bold(`${pkg.name} v${pkg.version}`));\n    }\n    footer(showPeakMemory) {\n        this.stopProgress();\n        const totalTime = (this.getTotalTime() / 1000).toFixed(2);\n        let msg = `Done in ${totalTime}s.`;\n        if (showPeakMemory) {\n            const peakMemory = (this.peakMemory / 1024 / 1024).toFixed(2);\n            msg += ` Peak memory usage ${peakMemory}MB.`;\n        }\n        this.log(this._prependEmoji(msg, '✨'));\n    }\n    log(msg, { force = false } = {}) {\n        this._lastCategorySize = 0;\n        this._log(msg, { force });\n    }\n    _log(msg, { force = false } = {}) {\n        if (this.isSilent && !force) {\n            return;\n        }\n        clearLine(this.stdout);\n        this.stdout.write(`${msg}\\n`);\n    }\n    success(msg) {\n        this._logCategory('success', 'green', msg);\n    }\n    error(msg) {\n        clearLine(this.stderr);\n        this.stderr.write(`${this.format.red('error')} ${msg}\\n`);\n    }\n    info(msg) {\n        this._logCategory('info', 'blue', msg);\n    }\n    command(command) {\n        this.log(this.format.dim(`$ ${command}`));\n    }\n    warn(msg) {\n        clearLine(this.stderr);\n        this.stderr.write(`${this.format.yellow('warning')} ${msg}\\n`);\n    }\n    // handles basic tree output to console\n    tree(key, trees, { force = false } = {}) {\n        this.stopProgress();\n        //\n        if (this.isSilent && !force) {\n            return;\n        }\n        const output = ({ name, children, hint, color }, titlePrefix, childrenPrefix) => {\n            const formatter = this.format;\n            const out = getFormattedOutput({\n                prefix: titlePrefix,\n                hint,\n                color,\n                name,\n                formatter,\n            });\n            this.stdout.write(out);\n            if (children && children.length) {\n                recurseTree(sortTrees(children), childrenPrefix, output);\n            }\n        };\n        recurseTree(sortTrees(trees), '', output);\n    }\n    activitySet(total, workers) {\n        if (!this.isTTY || this.noProgress) {\n            return super.activitySet(total, workers);\n        }\n        const spinners = [];\n        const reporterSpinners = this._spinners;\n        for (let i = 1; i < workers; i++) {\n            this.log('');\n        }\n        for (let i = 0; i < workers; i++) {\n            const spinner = new Spinner(this.stderr, i);\n            reporterSpinners.add(spinner);\n            spinner.start();\n            let prefix = null;\n            let current = 0;\n            const updatePrefix = () => {\n                spinner.setPrefix(`${this.format.dim(`[${current === 0 ? '-' : current}/${total}]`)} `);\n            };\n            const clear = () => {\n                prefix = null;\n                current = 0;\n                updatePrefix();\n                spinner.setText('waiting...');\n            };\n            clear();\n            spinners.unshift({\n                clear,\n                setPrefix(_current, _prefix) {\n                    current = _current;\n                    prefix = _prefix;\n                    spinner.setText(prefix);\n                    updatePrefix();\n                },\n                tick(msg) {\n                    if (prefix) {\n                        msg = `${prefix}: ${msg}`;\n                    }\n                    spinner.setText(msg);\n                },\n                end() {\n                    spinner.stop();\n                    reporterSpinners.delete(spinner);\n                },\n            });\n        }\n        return {\n            spinners,\n            end: () => {\n                for (const spinner of spinners) {\n                    spinner.end();\n                }\n                readline.moveCursor(this.stdout, 0, -workers + 1);\n            },\n        };\n    }\n    activity() {\n        if (!this.isTTY) {\n            return {\n                tick() { },\n                end() { },\n            };\n        }\n        const reporterSpinners = this._spinners;\n        const spinner = new Spinner(this.stderr);\n        spinner.start();\n        reporterSpinners.add(spinner);\n        return {\n            tick(name) {\n                spinner.setText(name);\n            },\n            end() {\n                spinner.stop();\n                reporterSpinners.delete(spinner);\n            },\n        };\n    }\n    progress(count) {\n        if (this.noProgress || count <= 0) {\n            return function () {\n                // noop\n            };\n        }\n        if (!this.isTTY) {\n            return function () {\n                // TODO what should the behaviour here be? we could buffer progress messages maybe\n            };\n        }\n        // Clear any potentially old progress bars\n        this.stopProgress();\n        const bar = (this._progressBar = new Progress(count, this.stderr, (progress) => {\n            if (progress === this._progressBar) {\n                this._progressBar = null;\n            }\n        }));\n        bar.render();\n        return function () {\n            bar.tick();\n        };\n    }\n    stopProgress() {\n        if (this._progressBar) {\n            this._progressBar.stop();\n        }\n    }\n}\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/console/helpers/tree-helper.js",
    "content": "// public\nexport function sortTrees(trees) {\n    return trees.sort(function (tree1, tree2) {\n        return tree1.name.localeCompare(tree2.name);\n    });\n}\nexport function recurseTree(tree, prefix, recurseFunc) {\n    const treeLen = tree.length;\n    const treeEnd = treeLen - 1;\n    for (let i = 0; i < treeLen; i++) {\n        const atEnd = i === treeEnd;\n        recurseFunc(tree[i], prefix + getLastIndentChar(atEnd), prefix + getNextIndentChar(atEnd));\n    }\n}\nexport function getFormattedOutput(fmt) {\n    const item = formatColor(fmt.color, fmt.name, fmt.formatter);\n    const suffix = getSuffix(fmt.hint, fmt.formatter);\n    return `${fmt.prefix}─ ${item}${suffix}\\n`;\n}\nfunction getNextIndentChar(end) {\n    return end ? '   ' : '│  ';\n}\nfunction getLastIndentChar(end) {\n    return end ? '└' : '├';\n}\nfunction getSuffix(hint, formatter) {\n    return hint ? ` (${formatter.grey(hint)})` : '';\n}\nfunction formatColor(color, strToFormat, formatter) {\n    return color ? formatter[color](strToFormat) : strToFormat;\n}\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/console/progress-bar.js",
    "content": "import { clearLine, toStartOfLine } from './util.js';\nexport default class ProgressBar {\n    constructor(total, stdout = process.stderr, callback) {\n        this.stdout = stdout;\n        this.total = total;\n        this.chars = ProgressBar.bars[0];\n        this.delay = 60;\n        this.curr = 0;\n        this._callback = callback;\n        clearLine(stdout);\n    }\n    tick() {\n        if (this.curr >= this.total) {\n            return;\n        }\n        this.curr++;\n        // schedule render\n        if (!this.id) {\n            this.id = setTimeout(() => this.render(), this.delay);\n        }\n    }\n    cancelTick() {\n        if (this.id) {\n            clearTimeout(this.id);\n            this.id = null;\n        }\n    }\n    stop() {\n        // \"stop\" by setting current to end so `tick` becomes noop\n        this.curr = this.total;\n        this.cancelTick();\n        clearLine(this.stdout);\n        if (this._callback) {\n            this._callback(this);\n        }\n    }\n    render() {\n        // clear throttle\n        this.cancelTick();\n        let ratio = this.curr / this.total;\n        ratio = Math.min(Math.max(ratio, 0), 1);\n        // progress without bar\n        let bar = ` ${this.curr}/${this.total}`;\n        // calculate size of actual bar\n        // $FlowFixMe: investigate process.stderr.columns flow error\n        // @ts-ignore\n        const availableSpace = Math.max(0, this.stdout.columns - bar.length - 3);\n        const width = Math.min(this.total, availableSpace);\n        const completeLength = Math.round(width * ratio);\n        const complete = this.chars[0].repeat(completeLength);\n        const incomplete = this.chars[1].repeat(width - completeLength);\n        bar = `[${complete}${incomplete}]${bar}`;\n        toStartOfLine(this.stdout);\n        this.stdout.write(bar);\n    }\n}\nProgressBar.bars = [['#', '-']];\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/console/spinner-progress.js",
    "content": "import { writeOnNthLine, clearNthLine } from './util.js';\nexport default class Spinner {\n    constructor(stdout = process.stderr, lineNumber = 0) {\n        this.current = 0;\n        this.prefix = '';\n        this.lineNumber = lineNumber;\n        this.stdout = stdout;\n        this.delay = 60;\n        this.chars = Spinner.spinners[28].split('');\n        this.text = '';\n        this.id = null;\n    }\n    setPrefix(prefix) {\n        this.prefix = prefix;\n    }\n    setText(text) {\n        this.text = text;\n    }\n    start() {\n        this.current = 0;\n        this.render();\n    }\n    render() {\n        if (this.id) {\n            clearTimeout(this.id);\n        }\n        // build line ensuring we don't wrap to the next line\n        let msg = `${this.prefix}${this.chars[this.current]} ${this.text}`;\n        // @ts-ignore\n        const columns = typeof this.stdout.columns === 'number' ? this.stdout.columns : 100;\n        msg = msg.slice(0, columns);\n        writeOnNthLine(this.stdout, this.lineNumber, msg);\n        this.current = ++this.current % this.chars.length;\n        this.id = setTimeout(() => this.render(), this.delay);\n    }\n    stop() {\n        if (this.id) {\n            clearTimeout(this.id);\n            this.id = null;\n        }\n        clearNthLine(this.stdout, this.lineNumber);\n    }\n}\nSpinner.spinners = [\n    '|/-\\\\',\n    '⠂-–—–-',\n    '◐◓◑◒',\n    '◴◷◶◵',\n    '◰◳◲◱',\n    '▖▘▝▗',\n    '■□▪▫',\n    '▌▀▐▄',\n    '▉▊▋▌▍▎▏▎▍▌▋▊▉',\n    '▁▃▄▅▆▇█▇▆▅▄▃',\n    '←↖↑↗→↘↓↙',\n    '┤┘┴└├┌┬┐',\n    '◢◣◤◥',\n    '.oO°Oo.',\n    '.oO@*',\n    '🌍🌎🌏',\n    '◡◡ ⊙⊙ ◠◠',\n    '☱☲☴',\n    '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏',\n    '⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓',\n    '⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆',\n    '⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋',\n    '⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁',\n    '⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈',\n    '⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈',\n    '⢄⢂⢁⡁⡈⡐⡠',\n    '⢹⢺⢼⣸⣇⡧⡗⡏',\n    '⣾⣽⣻⢿⡿⣟⣯⣷',\n    '⠁⠂⠄⡀⢀⠠⠐⠈',\n];\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/console/util.js",
    "content": "import * as tty from 'tty';\nimport * as readline from 'readline';\nimport chalk from 'chalk';\nconst CLEAR_WHOLE_LINE = 0;\nconst CLEAR_RIGHT_OF_CURSOR = 1;\nexport function clearLine(stdout) {\n    if (!chalk.supportsColor) {\n        if (stdout instanceof tty.WriteStream) {\n            if (stdout.columns > 0) {\n                stdout.write(`\\r${' '.repeat(stdout.columns - 1)}`);\n            }\n            stdout.write(`\\r`);\n        }\n        return;\n    }\n    readline.clearLine(stdout, CLEAR_WHOLE_LINE);\n    readline.cursorTo(stdout, 0);\n}\nexport function toStartOfLine(stdout) {\n    if (!chalk.supportsColor) {\n        stdout.write('\\r');\n        return;\n    }\n    readline.cursorTo(stdout, 0);\n}\nexport function writeOnNthLine(stdout, n, msg) {\n    if (!chalk.supportsColor) {\n        return;\n    }\n    if (n == 0) {\n        readline.cursorTo(stdout, 0);\n        stdout.write(msg);\n        readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);\n        return;\n    }\n    readline.cursorTo(stdout, 0);\n    readline.moveCursor(stdout, 0, -n);\n    stdout.write(msg);\n    readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);\n    readline.cursorTo(stdout, 0);\n    readline.moveCursor(stdout, 0, n);\n}\nexport function clearNthLine(stdout, n) {\n    if (!chalk.supportsColor) {\n        return;\n    }\n    if (n == 0) {\n        clearLine(stdout);\n        return;\n    }\n    readline.cursorTo(stdout, 0);\n    readline.moveCursor(stdout, 0, -n);\n    readline.clearLine(stdout, CLEAR_WHOLE_LINE);\n    readline.moveCursor(stdout, 0, n);\n}\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/format.js",
    "content": "function formatFunction(...strs) {\n    return strs.join(' ');\n}\nexport const defaultFormatter = {\n    bold: formatFunction,\n    dim: formatFunction,\n    italic: formatFunction,\n    underline: formatFunction,\n    inverse: formatFunction,\n    strikethrough: formatFunction,\n    black: formatFunction,\n    red: formatFunction,\n    green: formatFunction,\n    yellow: formatFunction,\n    blue: formatFunction,\n    magenta: formatFunction,\n    cyan: formatFunction,\n    white: formatFunction,\n    gray: formatFunction,\n    grey: formatFunction,\n    stripColor: formatFunction,\n};\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/index.js",
    "content": "export { default as ConsoleReporter } from './console/console-reporter';\nexport { default as JSONReporter } from './json-reporter';\nexport { default as NoopReporter } from './noop-reporter';\nexport { default as Reporter } from './base-reporter';\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/json-reporter.js",
    "content": "import BaseReporter from './base-reporter.js';\nexport default class JSONReporter extends BaseReporter {\n    constructor(opts) {\n        super(opts);\n        this._activityId = 0;\n        this._progressId = 0;\n    }\n    _dump(type, data, error) {\n        let stdout = this.stdout;\n        if (error) {\n            stdout = this.stderr;\n        }\n        stdout.write(`${JSON.stringify({ type, data })}\\n`);\n    }\n    _verbose(msg) {\n        this._dump('verbose', msg);\n    }\n    list(type, items, hints) {\n        this._dump('list', { type, items, hints });\n    }\n    tree(type, trees) {\n        this._dump('tree', { type, trees });\n    }\n    step(current, total, message) {\n        this._dump('step', { message, current, total });\n    }\n    inspect(value) {\n        this._dump('inspect', value);\n    }\n    footer(showPeakMemory) {\n        this._dump('finished', this.getTotalTime());\n    }\n    log(msg) {\n        this._dump('log', msg);\n    }\n    command(msg) {\n        this._dump('command', msg);\n    }\n    table(head, body) {\n        this._dump('table', { head, body });\n    }\n    success(msg) {\n        this._dump('success', msg);\n    }\n    error(msg) {\n        this._dump('error', msg, true);\n    }\n    warn(msg) {\n        this._dump('warning', msg, true);\n    }\n    info(msg) {\n        this._dump('info', msg);\n    }\n    activitySet(total, workers) {\n        if (!this.isTTY || this.noProgress) {\n            return super.activitySet(total, workers);\n        }\n        const id = this._activityId++;\n        this._dump('activitySetStart', { id, total, workers });\n        const spinners = [];\n        for (let i = 0; i < workers; i++) {\n            let current = 0;\n            let header = '';\n            spinners.push({\n                clear() { },\n                setPrefix(_current, _header) {\n                    current = _current;\n                    header = _header;\n                },\n                tick: msg => {\n                    this._dump('activitySetTick', {\n                        id,\n                        header,\n                        current,\n                        worker: i,\n                        message: msg,\n                    });\n                },\n                end() { },\n            });\n        }\n        return {\n            spinners,\n            end: () => {\n                this._dump('activitySetEnd', { id });\n            },\n        };\n    }\n    activity() {\n        return this._activity({});\n    }\n    _activity(data) {\n        if (!this.isTTY || this.noProgress) {\n            return {\n                tick() { },\n                end() { },\n            };\n        }\n        const id = this._activityId++;\n        this._dump('activityStart', { id, ...data });\n        return {\n            tick: (name) => {\n                this._dump('activityTick', { id, name });\n            },\n            end: () => {\n                this._dump('activityEnd', { id });\n            },\n        };\n    }\n    progress(total) {\n        if (this.noProgress) {\n            return function () {\n                // noop\n            };\n        }\n        const id = this._progressId++;\n        let current = 0;\n        this._dump('progressStart', { id, total });\n        return () => {\n            current++;\n            this._dump('progressTick', { id, current });\n            if (current === total) {\n                this._dump('progressFinish', { id });\n            }\n        };\n    }\n}\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/lang/en.js",
    "content": "const messages = {\n    upToDate: 'Already up-to-date.',\n    folderInSync: 'Folder in sync.',\n    nothingToInstall: 'Nothing to install.',\n    resolvingPackages: 'Resolving packages',\n    checkingManifest: 'Validating package.json',\n    fetchingPackages: 'Fetching packages',\n    linkingDependencies: 'Linking dependencies',\n    rebuildingPackages: 'Rebuilding all packages',\n    buildingFreshPackages: 'Building fresh packages',\n    cleaningModules: 'Cleaning modules',\n    bumpingVersion: 'Bumping version',\n    savingHar: 'Saving HAR file: $0',\n    answer: 'Answer?',\n    usage: 'Usage',\n    installCommandRenamed: '`install` has been replaced with `add` to add new dependencies. Run $0 instead.',\n    globalFlagRemoved: '`--global` has been deprecated. Please run $0 instead.',\n    waitingInstance: 'Waiting for the other pika instance to finish (pid $0, inside $1)',\n    waitingNamedInstance: 'Waiting for the other pika instance to finish ($0)',\n    offlineRetrying: 'There appears to be trouble with your network connection. Retrying...',\n    internalServerErrorRetrying: 'There appears to be trouble with the npm registry (returned $1). Retrying...',\n    clearedCache: 'Cleared cache.',\n    couldntClearPackageFromCache: \"Couldn't clear package $0 from cache\",\n    clearedPackageFromCache: 'Cleared package $0 from cache',\n    packWroteTarball: 'Wrote tarball to $0.',\n    helpExamples: '  Examples:\\n$0\\n',\n    helpCommands: '  Commands:\\n$0\\n',\n    helpCommandsMore: '  Run `$0` for more information on specific commands.',\n    helpLearnMore: '  Visit $0 to learn more about Pika.\\n',\n    manifestPotentialTypo: 'Potential typo $0, did you mean $1?',\n    manifestBuiltinModule: '$0 is also the name of a node core module',\n    manifestNameDot: \"Name can't start with a dot\",\n    manifestNameIllegalChars: 'Name contains illegal characters',\n    manifestNameBlacklisted: 'Name is blacklisted',\n    manifestLicenseInvalid: 'License should be a valid SPDX license expression',\n    manifestLicenseNone: 'No license field',\n    manifestStringExpected: '$0 is not a string',\n    manifestDependencyCollision: '$0 has dependency $1 with range $2 that collides with a dependency in $3 of the same name with version $4',\n    manifestDirectoryNotFound: 'Unable to read $0 directory of module $1',\n    verboseFileCopy: 'Copying $0 to $1.',\n    verboseFileLink: 'Creating hardlink at $0 to $1.',\n    verboseFileSymlink: 'Creating symlink at $0 to $1.',\n    verboseFileSkip: 'Skipping copying of file $0 as the file at $1 is the same size ($2) and mtime ($3).',\n    verboseFileSkipSymlink: 'Skipping copying of $0 as the file at $1 is the same symlink ($2).',\n    verboseFileSkipHardlink: 'Skipping copying of $0 as the file at $1 is the same hardlink ($2).',\n    verboseFileRemoveExtraneous: 'Removing extraneous file $0.',\n    verboseFilePhantomExtraneous: \"File $0 would be marked as extraneous but has been removed as it's listed as a phantom file.\",\n    verboseFileSkipArtifact: 'Skipping copying of $0 as the file is marked as a built artifact and subject to change.',\n    verboseFileFolder: 'Creating directory $0.',\n    verboseRequestStart: 'Performing $0 request to $1.',\n    verboseRequestFinish: 'Request $0 finished with status code $1.',\n    configSet: 'Set $0 to $1.',\n    configDelete: 'Deleted $0.',\n    configNpm: 'npm config',\n    configPika: 'pika config',\n    couldntFindPackagejson: \"Couldn't find a package.json file in $0\",\n    couldntFindMatch: \"Couldn't find match for $0 in $1 for $2.\",\n    couldntFindPackageInCache: \"Couldn't find any versions for $0 that matches $1 in our cache (possible versions are $2). This is usually caused by a missing entry in the lockfile, running Pika without the --offline flag may help fix this issue.\",\n    couldntFindVersionThatMatchesRange: \"Couldn't find any versions for $0 that matches $1\",\n    chooseVersionFromList: 'Please choose a version of $0 from this list:',\n    moduleNotInManifest: \"This module isn't specified in a package.json file.\",\n    moduleAlreadyInManifest: '$0 is already in $1. Please remove existing entry first before adding it to $2.',\n    unknownFolderOrTarball: \"Passed folder/tarball doesn't exist,\",\n    unknownPackage: \"Couldn't find package $0.\",\n    unknownPackageName: \"Couldn't find package name.\",\n    unknownUser: \"Couldn't find user $0.\",\n    unknownRegistryResolver: 'Unknown registry resolver $0',\n    userNotAnOwner: \"User $0 isn't an owner of this package.\",\n    invalidVersionArgument: 'Use the $0 flag to create a new version.',\n    invalidVersion: 'Invalid version supplied.',\n    requiredVersionInRange: 'Required version in range.',\n    packageNotFoundRegistry: \"Couldn't find package $0 on the $1 registry.\",\n    requiredPackageNotFoundRegistry: \"Couldn't find package $0 required by $1 on the $2 registry.\",\n    doesntExist: \"Package $1 refers to a non-existing file '$0'.\",\n    missingRequiredPackageKey: `Package $0 doesn't have a $1.`,\n    invalidAccess: 'Invalid argument for access, expected public or restricted.',\n    invalidCommand: 'Invalid subcommand. Try $0',\n    invalidGistFragment: 'Invalid gist fragment $0.',\n    invalidHostedGitFragment: 'Invalid hosted git fragment $0.',\n    invalidFragment: 'Invalid fragment $0.',\n    invalidPackageName: 'Invalid package name.',\n    invalidPackageVersion: \"Can't add $0: invalid package version $1.\",\n    couldntFindManifestIn: \"Couldn't find manifest in $0.\",\n    shrinkwrapWarning: 'npm-shrinkwrap.json found. This will not be updated or respected. See https://yarnpkg.com/en/docs/migrating-from-npm for more information.',\n    npmLockfileWarning: 'package-lock.json found. Your project contains lock files generated by tools other than Pika. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json.',\n    lockfileOutdated: 'Outdated lockfile. Please run `pika install` and try again.',\n    lockfileMerged: 'Merge conflict detected in pika.lock and successfully merged.',\n    lockfileConflict: 'A merge conflict was found in pika.lock but it could not be successfully merged, regenerating pika.lock from scratch.',\n    ignoredScripts: 'Ignored scripts due to flag.',\n    missingAddDependencies: 'Missing list of packages to add to your project.',\n    yesWarning: 'The yes flag has been set. This will automatically answer yes to all questions, which may have security implications.',\n    networkWarning: \"You don't appear to have an internet connection. Try the --offline flag to use the cache for registry queries.\",\n    flatGlobalError: 'The package $0 requires a flat dependency graph. Add `\"flat\": true` to your package.json and try again.',\n    noName: `Package doesn't have a name.`,\n    noVersion: `Package doesn't have a version.`,\n    answerRequired: 'An answer is required.',\n    missingWhyDependency: 'Missing package name, folder or path to file to identify why a package has been installed',\n    bugReport: 'If you think this is a bug, please open a bug report with the information provided in $0.',\n    unexpectedError: 'An unexpected error occurred: $0.',\n    jsonError: 'Error parsing JSON at $0, $1.',\n    noPermission: 'Cannot create $0 due to insufficient permissions.',\n    noGlobalFolder: 'Cannot find a suitable global folder. Tried these: $0',\n    allDependenciesUpToDate: 'All of your dependencies are up to date.',\n    legendColorsForVersionUpdates: 'Color legend : \\n $0    : Major Update backward-incompatible updates \\n $1 : Minor Update backward-compatible features \\n $2  : Patch Update backward-compatible bug fixes',\n    frozenLockfileError: 'Your lockfile needs to be updated, but pika was run with `--frozen-lockfile`.',\n    fileWriteError: 'Could not write file $0: $1',\n    fileDeleteError: 'Could not delete file $0: $1',\n    multiplePackagesCantUnpackInSameDestination: 'Pattern $0 is trying to unpack in the same destination $1 as pattern $2. This could result in non-deterministic behavior, skipping.',\n    incorrectLockfileEntry: 'Lockfile has incorrect entry for $0. Ignoring it.',\n    invalidResolutionName: 'Resolution field $0 does not end with a valid package name and will be ignored',\n    invalidResolutionVersion: 'Resolution field $0 has an invalid version entry and may be ignored',\n    incompatibleResolutionVersion: 'Resolution field $0 is incompatible with requested version $1',\n    pikaOutdated: \"Your current version of Pika is out of date. The latest version is $0, while you're on $1.\",\n    pikaOutdatedInstaller: 'To upgrade, download the latest installer at $0.',\n    pikaOutdatedCommand: 'To upgrade, run the following command:',\n    tooManyArguments: 'Too many arguments, maximum of $0.',\n    tooFewArguments: 'Not enough arguments, expected at least $0.',\n    noArguments: \"This command doesn't require any arguments.\",\n    ownerRemoving: 'Removing owner $0 from package $1.',\n    ownerRemoved: 'Owner removed.',\n    ownerRemoveError: \"Couldn't remove owner.\",\n    ownerGetting: 'Getting owners for package $0',\n    ownerGettingFailed: \"Couldn't get list of owners.\",\n    ownerAlready: 'This user is already an owner of this package.',\n    ownerAdded: 'Added owner.',\n    ownerAdding: 'Adding owner $0 to package $1',\n    ownerAddingFailed: \"Couldn't add owner.\",\n    ownerNone: 'No owners.',\n    teamCreating: 'Creating team',\n    teamRemoving: 'Removing team',\n    teamAddingUser: 'Adding user to team',\n    teamRemovingUser: 'Removing user from team',\n    teamListing: 'Listing teams',\n    distFailed: `⚠️  Distribution \"$0\" failed to build: $1 $2`,\n    distExiting: `   Exiting...`,\n    distContinuing: `   Continuing...`,\n    cleaning: 'Cleaning modules',\n    cleanCreatingFile: 'Creating $0',\n    cleanCreatedFile: 'Created $0. Please review the contents of this file then run \"pika autoclean --force\" to perform a clean.',\n    cleanAlreadyExists: '$0 already exists. To revert to the default file, delete $0 then rerun this command.',\n    cleanRequiresForce: 'This command required the \"--force\" flag to perform the clean. This is a destructive operation. Files specified in $0 will be deleted.',\n    cleanDoesNotExist: '$0 does not exist. Autoclean will delete files specified by $0. Run \"autoclean --init\" to create $0 with the default entries.',\n    binLinkCollision: \"There's already a linked binary called $0 in your global Pika bin. Could not link this package's $0 bin entry.\",\n    linkCollision: \"There's already a package called $0 registered. This command has had no effect. If this command was run in another folder with the same name, the other folder is still linked. Please run pika unlink in the other folder if you want to register this folder.\",\n    linkMissing: 'No registered package found called $0.',\n    linkRegistered: 'Registered $0.',\n    linkRegisteredMessage: 'You can now run `pika link $0` in the projects where you want to use this package and it will be used instead.',\n    linkUnregistered: 'Unregistered $0.',\n    linkUnregisteredMessage: 'You can now run `pika unlink $0` in the projects where you no longer want to use this package.',\n    linkUsing: 'Using linked package for $0.',\n    linkDisusing: 'Removed linked package $0.',\n    linkDisusingMessage: 'You will need to run `pika` to re-install the package that was linked.',\n    linkTargetMissing: 'The target of linked package $0 is missing. Removing link.',\n    createInvalidBin: 'Invalid bin entry found in package $0.',\n    createMissingPackage: 'Package not found - this is probably an internal error, and should be reported at https://github.com/yarnpkg/yarn/issues.',\n    workspacesAddRootCheck: 'Running this command will add the dependency to the workspace root rather than the workspace itself, which might not be what you want - if you really meant it, make it explicit by running this command again with the -W flag (or --ignore-workspace-root-check).',\n    workspacesRemoveRootCheck: 'Running this command will remove the dependency from the workspace root rather than the workspace itself, which might not be what you want - if you really meant it, make it explicit by running this command again with the -W flag (or --ignore-workspace-root-check).',\n    workspacesFocusRootCheck: 'This command can only be run inside an individual workspace.',\n    workspacesRequirePrivateProjects: 'Workspaces can only be enabled in private projects.',\n    workspacesSettingMustBeArray: 'The workspaces field in package.json must be an array.',\n    workspacesDisabled: 'Your project root defines workspaces but the feature is disabled in your Pika config. Please check \"workspaces-experimental\" in your .pikarc file.',\n    workspacesNohoistRequirePrivatePackages: 'nohoist config is ignored in $0 because it is not a private package. If you think nohoist should be allowed in public packages, please submit an issue for your use case.',\n    workspacesNohoistDisabled: `$0 defines nohoist but the feature is disabled in your Pika config (\"workspaces-nohoist-experimental\" in .pikarc file)`,\n    workspaceRootNotFound: \"Cannot find the root of your workspace - are you sure you're currently in a workspace?\",\n    workspaceMissingWorkspace: 'Missing workspace name.',\n    workspaceMissingCommand: 'Missing command name.',\n    workspaceUnknownWorkspace: 'Unknown workspace $0.',\n    workspaceVersionMandatory: 'Missing version in workspace at $0, ignoring.',\n    workspaceNameMandatory: 'Missing name in workspace at $0, ignoring.',\n    workspaceNameDuplicate: 'There are more than one workspace with name $0',\n    cacheFolderSkipped: 'Skipping preferred cache folder $0 because it is not writable.',\n    cacheFolderMissing: \"Pika hasn't been able to find a cache folder it can use. Please use the explicit --cache-folder option to tell it what location to use, or make one of the preferred locations writable.\",\n    cacheFolderSelected: 'Selected the next writable cache folder in the list, will be $0.',\n    execMissingCommand: 'Missing command name.',\n    noScriptsAvailable: 'There are no scripts specified inside package.json.',\n    noBinAvailable: 'There are no binary scripts available.',\n    dashDashDeprecation: `From Pika 1.0 onwards, scripts don't require \"--\" for options to be forwarded. In a future version, any explicit \"--\" will be forwarded as-is to the scripts.`,\n    commandNotSpecified: 'No command specified.',\n    binCommands: 'Commands available from binary scripts: ',\n    possibleCommands: 'Project commands',\n    commandQuestion: 'Which command would you like to run?',\n    commandFailedWithCode: 'Command failed with exit code $0.',\n    commandFailedWithSignal: 'Command failed with signal $0.',\n    packageRequiresNodeGyp: 'This package requires node-gyp, which is not currently installed. Pika will attempt to automatically install it. If this fails, you can run \"pika global add node-gyp\" to manually install it.',\n    nodeGypAutoInstallFailed: 'Failed to auto-install node-gyp. Please run \"pika global add node-gyp\" manually. Error: $0',\n    foundIncompatible: 'Found incompatible module',\n    incompatibleEngine: 'The engine $0 is incompatible with this module. Expected version $1. Got $2',\n    incompatibleCPU: 'The CPU architecture $0 is incompatible with this module.',\n    incompatibleOS: 'The platform $0 is incompatible with this module.',\n    invalidEngine: 'The engine $0 appears to be invalid.',\n    optionalCompatibilityExcluded: '$0 is an optional dependency and failed compatibility check. Excluding it from installation.',\n    optionalModuleFail: 'This module is OPTIONAL, you can safely ignore this error',\n    optionalModuleScriptFail: 'Error running install script for optional dependency: $0',\n    optionalModuleCleanupFail: 'Could not cleanup build artifacts from failed install: $0',\n    unmetPeer: '$0 has unmet peer dependency $1.',\n    incorrectPeer: '$0 has incorrect peer dependency $1.',\n    selectedPeer: 'Selecting $1 at level $2 as the peer dependency of $0.',\n    missingBundledDependency: '$0 is missing a bundled dependency $1. This should be reported to the package maintainer.',\n    savedNewDependency: 'Saved 1 new dependency.',\n    savedNewDependencies: 'Saved $0 new dependencies.',\n    directDependencies: 'Direct dependencies',\n    allDependencies: 'All dependencies',\n    foundWarnings: 'Found $0 warnings.',\n    foundErrors: 'Found $0 errors.',\n    savedLockfile: 'Saved lockfile.',\n    noRequiredLockfile: 'No lockfile in this directory. Run `pika install` to generate one.',\n    noLockfileFound: 'No lockfile found.',\n    invalidSemver: 'Invalid semver version',\n    newVersion: 'New version',\n    currentVersion: 'Current version',\n    noVersionOnPublish: 'Proceeding with current version',\n    manualVersionResolution: 'Unable to find a suitable version for $0, please choose one by typing one of the numbers below:',\n    manualVersionResolutionOption: '$0 which resolved to $1',\n    createdTag: 'Created tag.',\n    createdTagFail: \"Couldn't add tag.\",\n    deletedTag: 'Deleted tag.',\n    deletedTagFail: \"Couldn't delete tag.\",\n    gettingTags: 'Getting tags',\n    deletingTags: 'Deleting tag',\n    creatingTag: 'Creating tag $0 = $1',\n    whyStart: 'Why do we have the module $0?',\n    whyFinding: 'Finding dependency',\n    whyCalculating: 'Calculating file sizes',\n    whyUnknownMatch: \"We couldn't find a match!\",\n    whyInitGraph: 'Initialising dependency graph',\n    whyWhoKnows: \"We don't know why this module exists\",\n    whyDiskSizeWithout: 'Disk size without dependencies: $0',\n    whyDiskSizeUnique: 'Disk size with unique dependencies: $0',\n    whyDiskSizeTransitive: 'Disk size with transitive dependencies: $0',\n    whySharedDependencies: 'Number of shared dependencies: $0',\n    whyHoistedTo: `Has been hoisted to $0`,\n    whyHoistedFromSimple: `This module exists because it's hoisted from $0.`,\n    whyNotHoistedSimple: `This module exists here because it's in the nohoist list $0.`,\n    whyDependedOnSimple: `This module exists because $0 depends on it.`,\n    whySpecifiedSimple: `This module exists because it's specified in $0.`,\n    whyReasons: 'Reasons this module exists',\n    whyHoistedFrom: 'Hoisted from $0',\n    whyNotHoisted: `in the nohoist list $0`,\n    whyDependedOn: '$0 depends on it',\n    whySpecified: `Specified in $0`,\n    whyMatch: `\\r=> Found $0`,\n    uninstalledPackages: 'Uninstalled packages.',\n    uninstallRegenerate: 'Regenerating lockfile and installing missing dependencies',\n    cleanRemovedFiles: 'Removed $0 files',\n    cleanSavedSize: 'Saved $0 MB.',\n    configFileFound: 'Found configuration file $0.',\n    configPossibleFile: 'Checking for configuration file $0.',\n    npmUsername: 'npm username',\n    npmPassword: 'npm password',\n    npmEmail: 'npm email',\n    npmOneTimePassword: 'npm one-time password',\n    loggingIn: 'Logging in',\n    loggedIn: 'Logged in.',\n    notRevokingEnvToken: 'Not revoking login token, specified via environment variable.',\n    notRevokingConfigToken: 'Not revoking login token, specified via config file.',\n    noTokenToRevoke: 'No login token to revoke.',\n    revokingToken: 'Revoking token',\n    revokedToken: 'Revoked login token.',\n    loginAsPublic: 'Logging in as public',\n    incorrectCredentials: 'Incorrect username or password.',\n    incorrectOneTimePassword: 'Incorrect one-time password.',\n    twoFactorAuthenticationEnabled: 'Two factor authentication enabled.',\n    clearedCredentials: 'Cleared login credentials.',\n    publishFail: \"Couldn't publish package: $0\",\n    publishPrivate: 'Package marked as private, not publishing.',\n    published: 'Published.',\n    publishing: 'Publishing',\n    nonInteractiveNoVersionSpecified: 'You must specify a new version with --new-version when running with --non-interactive.',\n    nonInteractiveNoToken: \"No token found and can't prompt for login when running with --non-interactive.\",\n    infoFail: 'Received invalid response from npm.',\n    malformedRegistryResponse: 'Received malformed response from registry for $0. The registry may be down.',\n    registryNoVersions: 'No valid versions found for $0. The package may be unpublished.',\n    cantRequestOffline: \"Can't make a request in offline mode ($0)\",\n    requestManagerNotSetupHAR: 'RequestManager was not setup to capture HAR files',\n    requestError: 'Request $0 returned a $1',\n    requestFailed: 'Request failed $0',\n    tarballNotInNetworkOrCache: '$0: Tarball is not in network and can not be located in cache ($1)',\n    fetchBadHashWithPath: \"Integrity check failed for $0 (computed integrity doesn't match our records, got $2)\",\n    fetchBadIntegrityAlgorithm: 'Integrity checked failed for $0 (none of the specified algorithms are supported)',\n    fetchErrorCorrupt: '$0. Mirror tarball appears to be corrupt. You can resolve this by running:\\n\\n  rm -rf $1\\n  pika install',\n    errorExtractingTarball: 'Extracting tar content of $1 failed, the file appears to be corrupt: $0',\n    updateInstalling: 'Installing $0...',\n    hostedGitResolveError: 'Error connecting to repository. Please, check the url.',\n    unknownFetcherFor: 'Unknown fetcher for $0',\n    downloadGitWithoutCommit: 'Downloading the git repo $0 over plain git without a commit hash',\n    downloadHTTPWithoutCommit: 'Downloading the git repo $0 over HTTP without a commit hash',\n    unplugDisabled: \"Packages can only be unplugged when Plug'n'Play is enabled.\",\n    plugnplayWindowsSupport: \"Plug'n'Play on Windows doesn't support the cache and project to be kept on separate drives\",\n    packageInstalledWithBinaries: 'Installed $0 with binaries:',\n    packageHasBinaries: '$0 has binaries:',\n    packageHasNoBinaries: '$0 has no binaries',\n    packageBinaryNotFound: \"Couldn't find a binary named $0\",\n    couldBeDeduped: '$0 could be deduped from $1 to $2',\n    lockfileNotContainPattern: 'Lockfile does not contain pattern: $0',\n    integrityCheckFailed: 'Integrity check failed',\n    noIntegrityFile: \"Couldn't find an integrity file\",\n    integrityFailedExpectedIsNotAJSON: 'Integrity check: integrity file is not a json',\n    integrityCheckLinkedModulesDontMatch: \"Integrity check: Linked modules don't match\",\n    integrityFlagsDontMatch: \"Integrity check: Flags don't match\",\n    integrityLockfilesDontMatch: \"Integrity check: Lock files don't match\",\n    integrityFailedFilesMissing: 'Integrity check: Files are missing',\n    integrityPatternsDontMatch: \"Integrity check: Top level patterns don't match\",\n    integrityModulesFoldersMissing: 'Integrity check: Some module folders are missing',\n    integritySystemParamsDontMatch: \"Integrity check: System parameters don't match\",\n    packageNotInstalled: '$0 not installed',\n    optionalDepNotInstalled: 'Optional dependency $0 not installed',\n    packageWrongVersion: '$0 is wrong version: expected $1, got $2',\n    packageDontSatisfy: \"$0 doesn't satisfy found match of $1\",\n    lockfileExists: 'Lockfile already exists, not migrating.',\n    pikaManifestExists: 'pika.package.json manifest already exists, not migrating.',\n    noManifestExists: 'No package.json manifest found. Run `pika init` to generate a new pika.package.json manifest.',\n    skippingImport: 'Skipping import of $0 for $1',\n    importFailed: 'Import of $0 for $1 failed, resolving normally.',\n    importResolveFailed: 'Import of $0 failed starting in $1',\n    importResolvedRangeMatch: 'Using version $0 of $1 instead of $2 for $3',\n    importSourceFilesCorrupted: 'Failed to import from package-lock.json, source file(s) corrupted',\n    importPackageLock: 'found npm package-lock.json, converting to pika.lock',\n    importYarnLock: 'found yarn.lock, converting to pika.lock',\n    importNodeModules: 'creating pika.lock from local node_modules folder',\n    packageContainsPikaAsGlobal: 'Installing Pika via Pika will result in you having two separate versions of Pika installed at the same time, which is not recommended. To update Pika please follow https://yarnpkg.com/en/docs/install .',\n    watchStarting: `Starting up`,\n    watchRunning: `Ready! Watching source tree for changes`,\n    watchRebuild: `Rebuilding...`,\n    watchError: `Build error!`,\n    noValidationErrors: `0 Validation Errors found.`,\n    validationErrors: `$0 Validation Error(s) found. Resolve before publishing.`,\n    scopeNotValid: 'The specified scope is not valid.',\n    deprecatedCommand: '$0 is deprecated. Please use $1.',\n    deprecatedListArgs: 'Filtering by arguments is deprecated. Please use the pattern option instead.',\n    implicitFileDeprecated: 'Using the \"file:\" protocol implicitly is deprecated. Please either prepend the protocol or prepend the path $0 with \"./\".',\n    unsupportedNodeVersion: 'You are using Node $0 which is not supported and may encounter bugs or unexpected behavior. Pika supports the following semver range: $1',\n    verboseUpgradeBecauseRequested: 'Considering upgrade of $0 to $1 because it was directly requested.',\n    verboseUpgradeBecauseOutdated: 'Considering upgrade of $0 to $1 because a newer version exists in the registry.',\n    verboseUpgradeNotUnlocking: 'Not unlocking $0 in the lockfile because it is a new or direct dependency.',\n    verboseUpgradeUnlocking: 'Unlocking $0 in the lockfile.',\n    folderMissing: \"Directory $0 doesn't exist\",\n    mutexPortBusy: 'Cannot use the network mutex on port $0. It is probably used by another app.',\n    auditRunning: 'Auditing packages',\n    auditSummary: '$0 vulnerabilities found - Packages audited: $1',\n    auditSummarySeverity: 'Severity:',\n    auditCritical: '$0 Critical',\n    auditHigh: '$0 High',\n    auditModerate: '$0 Moderate',\n    auditLow: '$0 Low',\n    auditInfo: '$0 Info',\n    auditResolveCommand: '# Run $0 to resolve $1 $2',\n    auditSemverMajorChange: 'SEMVER WARNING: Recommended action is a potentially breaking change',\n    auditManualReview: 'Manual Review\\nSome vulnerabilities require your attention to resolve\\n\\nVisit https://go.npm.me/audit-guide for additional guidance',\n    auditRunAuditForDetails: 'Security audit found potential problems. Run \"pika audit\" for additional details.',\n    auditOffline: 'Skipping audit. Security audit cannot be performed in offline mode.',\n};\nexport default messages;\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/lang/index.js",
    "content": "import en from './en.js';\nexport { en };\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/noop-reporter.js",
    "content": "import BaseReporter from './base-reporter.js';\nexport default class NoopReporter extends BaseReporter {\n    lang(key, ...args) {\n        return 'do nothing';\n    }\n    verbose(msg) { }\n    verboseInspect(val) { }\n    initPeakMemoryCounter() { }\n    checkPeakMemory() { }\n    close() { }\n    getTotalTime() {\n        return 0;\n    }\n    list(key, items, hints) { }\n    tree(key, obj) { }\n    step(current, total, message, emoji) { }\n    error(message) { }\n    info(message) { }\n    warn(message) { }\n    success(message) { }\n    log(message) { }\n    command(command) { }\n    inspect(value) { }\n    header(pkg) { }\n    footer(showPeakMemory) { }\n    table(head, body) { }\n    activity() {\n        return {\n            tick(name) { },\n            end() { },\n        };\n    }\n    activitySet(total, workers) {\n        return {\n            spinners: Array(workers).fill({\n                clear() { },\n                setPrefix() { },\n                tick() { },\n                end() { },\n            }),\n            end() { },\n        };\n    }\n    progress(total) {\n        return function () { };\n    }\n    disableProgress() {\n        this.noProgress = true;\n    }\n}\n"
  },
  {
    "path": "checkpoint/dist-src/reporters/types.js",
    "content": ""
  },
  {
    "path": "checkpoint/dist-src/types.js",
    "content": ""
  },
  {
    "path": "checkpoint/dist-src/util/babel-plugin-import-rewrite.js",
    "content": "// @flow\nimport * as nodeFs from 'fs';\nimport * as nodePath from 'path';\nimport * as url from 'url';\nimport chalk from 'chalk';\nimport { validateDynamicImportArguments } from './babel-validate-specifier.js';\nconst BareIdentifierFormat = /^((?:@[^\\/]+\\/)?[^\\/]+)(\\/.*)?$/;\nfunction log(symbol, fileName, errors) {\n    if (!Array.isArray(errors)) {\n        errors = [errors];\n    }\n    console.log(`${symbol}  `, chalk.bold(fileName));\n    for (const error of errors) {\n        console.log(`  ${chalk.dim('≫')} ${error}`);\n    }\n}\nexport default function transform({ template, types: t }) {\n    function rewriteImport(specifier, { opts, file }) {\n        const { deps, addExtensions } = opts;\n        try {\n            url.parse(specifier);\n        }\n        catch (err) {\n            return;\n        }\n        // URL w/o protocol\n        if (specifier.substr(0, 2) === '//') {\n            return; // Leave it alone\n        }\n        // Local path\n        if (['.', '/'].indexOf(specifier.charAt(0)) >= 0) {\n            if (addExtensions) {\n                const extname = nodePath.extname(specifier);\n                if (extname === '.js') {\n                    return;\n                }\n                if (extname) {\n                    console.warn('Unexpected file extension:', specifier);\n                    return;\n                }\n                const resolvedPath = nodePath.resolve(nodePath.dirname(file.opts.filename), specifier);\n                try {\n                    const stat = nodeFs.lstatSync(resolvedPath);\n                    if (stat.isDirectory()) {\n                        return specifier + '/index';\n                    }\n                }\n                catch (err) {\n                    // do nothing\n                }\n                return specifier + '.js';\n            }\n            return;\n        }\n        // A 'bare' identifier\n        const match = BareIdentifierFormat.exec(specifier);\n        if (deps && match) {\n            const packageName = match[1];\n            // const file = match[2] || '';\n            return deps[packageName];\n        }\n    }\n    return {\n        visitor: {\n            'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration'(path, { opts, file }) {\n                if (!path.node.source) {\n                    return;\n                }\n                const rewrittenSpecifier = rewriteImport(path.node.source.value, { opts, file });\n                if (rewrittenSpecifier) {\n                    path.node.source.value = rewrittenSpecifier;\n                }\n            },\n            Import(path, { opts, file }) {\n                const errors = validateDynamicImportArguments(path);\n                if (errors.size > 0) {\n                    return;\n                }\n                const [importPath] = path.parent.arguments;\n                const rewrittenSpecifier = rewriteImport(importPath.value, { opts, file });\n                if (rewrittenSpecifier) {\n                    importPath.value = rewrittenSpecifier;\n                }\n            },\n        },\n    };\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/babel-validate-specifier.js",
    "content": "// @flow\nimport chalk from 'chalk';\nfunction getLineCol(node) {\n    const loc = node.loc.start;\n    return chalk.dim(`[${loc.line}:${loc.column}]`);\n}\nexport function validateDynamicImportArguments(path) {\n    if (path.parent.arguments.length !== 1) {\n        return new Set([\n            `${getLineCol(path.node)} \"\\`import()\\` only accepts 1 argument, but got ${path.parent.arguments.length}`,\n        ]);\n    }\n    const [argNode] = path.parent.arguments;\n    if (argNode.type !== 'StringLiteral') {\n        return new Set([\n            `${getLineCol(path.node)} Pika expects strings as \\`import()\\` arguments. Treating this as an absolute file path.`,\n        ]);\n    }\n    return new Set();\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/blocking-queue.js",
    "content": "import map from './map.js';\nexport default class BlockingQueue {\n    constructor(alias, maxConcurrency = Infinity) {\n        this.concurrencyQueue = [];\n        this.maxConcurrency = maxConcurrency;\n        this.runningCount = 0;\n        this.warnedStuck = false;\n        this.alias = alias;\n        this.first = true;\n        this.running = map() || {};\n        this.queue = map() || {};\n        this.stuckTick = this.stuckTick.bind(this);\n    }\n    stillActive() {\n        if (this.stuckTimer) {\n            clearTimeout(this.stuckTimer);\n        }\n        this.stuckTimer = setTimeout(this.stuckTick, 5000);\n        // We need to check the existence of unref because of https://github.com/facebook/jest/issues/4559\n        // $FlowFixMe: Node's setInterval returns a Timeout, not a Number\n        this.stuckTimer.unref && this.stuckTimer.unref();\n    }\n    stuckTick() {\n        if (this.runningCount === 1) {\n            this.warnedStuck = true;\n            console.log(`The ${JSON.stringify(this.alias)} blocking queue may be stuck. 5 seconds ` +\n                `without any activity with 1 worker: ${Object.keys(this.running)[0]}`);\n        }\n    }\n    push(key, factory) {\n        if (this.first) {\n            this.first = false;\n        }\n        else {\n            this.stillActive();\n        }\n        return new Promise((resolve, reject) => {\n            // we're already running so push ourselves to the queue\n            const queue = (this.queue[key] = this.queue[key] || []);\n            queue.push({ factory, resolve, reject });\n            if (!this.running[key]) {\n                this.shift(key);\n            }\n        });\n    }\n    shift(key) {\n        if (this.running[key]) {\n            delete this.running[key];\n            this.runningCount--;\n            if (this.stuckTimer) {\n                clearTimeout(this.stuckTimer);\n                this.stuckTimer = null;\n            }\n            if (this.warnedStuck) {\n                this.warnedStuck = false;\n                console.log(`${JSON.stringify(this.alias)} blocking queue finally resolved. Nothing to worry about.`);\n            }\n        }\n        const queue = this.queue[key];\n        if (!queue) {\n            return;\n        }\n        const { resolve, reject, factory } = queue.shift();\n        if (!queue.length) {\n            delete this.queue[key];\n        }\n        const next = () => {\n            this.shift(key);\n            this.shiftConcurrencyQueue();\n        };\n        const run = () => {\n            this.running[key] = true;\n            this.runningCount++;\n            factory()\n                .then(function (val) {\n                resolve(val);\n                next();\n                return null;\n            })\n                .catch(function (err) {\n                reject(err);\n                next();\n            });\n        };\n        this.maybePushConcurrencyQueue(run);\n    }\n    maybePushConcurrencyQueue(run) {\n        if (this.runningCount < this.maxConcurrency) {\n            run();\n        }\n        else {\n            this.concurrencyQueue.push(run);\n        }\n    }\n    shiftConcurrencyQueue() {\n        if (this.runningCount < this.maxConcurrency) {\n            const fn = this.concurrencyQueue.shift();\n            if (fn) {\n                fn();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/child.js",
    "content": "/* global child_process$spawnOpts */\nimport * as constants from '../constants.js';\nimport BlockingQueue from './blocking-queue.js';\nimport { ProcessSpawnError, ProcessTermError } from '../errors.js';\nimport { promisify } from './promise.js';\nimport { exec as _exec, spawn as _spawn } from 'child_process';\nexport const queue = new BlockingQueue('child', constants.CHILD_CONCURRENCY);\n// TODO: this uid check is kinda whack\nlet uid = 0;\nexport const exec = promisify(_exec);\nconst spawnedProcesses = {};\nexport function forwardSignalToSpawnedProcesses(signal) {\n    for (const key of Object.keys(spawnedProcesses)) {\n        spawnedProcesses[key].kill(signal);\n    }\n}\nexport function spawn(program, args, opts = {}, onData) {\n    const key = opts.cwd || String(++uid);\n    return queue.push(key, () => new Promise((resolve, reject) => {\n        const proc = _spawn(program, args, opts);\n        spawnedProcesses[key] = proc;\n        let processingDone = false;\n        let processClosed = false;\n        let err = null;\n        let stdout = '';\n        proc.on('error', (err) => {\n            if (err.code === 'ENOENT') {\n                reject(new ProcessSpawnError(`Couldn't find the binary ${program}`, err.code, program));\n            }\n            else {\n                reject(err);\n            }\n        });\n        function updateStdout(chunk) {\n            stdout += chunk;\n            if (onData) {\n                onData(chunk);\n            }\n        }\n        function finish() {\n            delete spawnedProcesses[key];\n            if (err) {\n                reject(err);\n            }\n            else {\n                resolve(stdout.trim());\n            }\n        }\n        if (typeof opts.process === 'function') {\n            opts.process(proc, updateStdout, reject, function () {\n                if (processClosed) {\n                    finish();\n                }\n                else {\n                    processingDone = true;\n                }\n            });\n        }\n        else {\n            if (proc.stderr) {\n                proc.stderr.on('data', updateStdout);\n            }\n            if (proc.stdout) {\n                proc.stdout.on('data', updateStdout);\n            }\n            processingDone = true;\n        }\n        proc.on('close', (code, signal) => {\n            if (signal || code >= 1) {\n                err = new ProcessTermError([\n                    'Command failed.',\n                    signal ? `Exit signal: ${signal}` : `Exit code: ${code}`,\n                    `Command: ${program}`,\n                    `Arguments: ${args.join(' ')}`,\n                    `Directory: ${opts.cwd || process.cwd()}`,\n                    `Output:\\n${stdout.trim()}`,\n                ].join('\\n'));\n                err.EXIT_SIGNAL = signal;\n                err.EXIT_CODE = code;\n            }\n            if (processingDone || err) {\n                finish();\n            }\n            else {\n                processClosed = true;\n            }\n        });\n    }));\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/conversion.js",
    "content": "const FALSY_STRINGS = new Set(['0', 'false']);\nexport function boolify(val) {\n    return !FALSY_STRINGS.has(val.toString().toLowerCase());\n}\nexport function boolifyWithDefault(val, defaultResult) {\n    return val === '' || val === null || val === undefined ? defaultResult : boolify(val);\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/execute-lifecycle-script.js",
    "content": "import * as child from './child.js';\nimport { fixCmdWinSlashes } from './fix-cmd-win-slashes.js';\n// export const IGNORE_MANIFEST_KEYS: Set<string> = new Set(['readme', 'notice', 'licenseText']);\n// // We treat these configs as internal, thus not expose them to process.env.\n// // This helps us avoid some gyp issues when building native modules.\n// // See https://github.com/yarnpkg/yarn/issues/2286.\n// const IGNORE_CONFIG_KEYS = ['lastUpdateCheck'];\n// async function getPnpParameters(config: Config): Promise<Array<string>> {\n//   if (await fs.exists(`${config.lockfileFolder}/${constants.PNP_FILENAME}`)) {\n//     return ['-r', `${config.lockfileFolder}/${constants.PNP_FILENAME}`];\n//   } else {\n//     return [];\n//   }\n// }\n// let wrappersFolder = null;\n// export async function getWrappersFolder(config: Config): Promise<string> {\n//   if (wrappersFolder) {\n//     return wrappersFolder;\n//   }\n//   wrappersFolder = await fs.makeTempDir();\n//   await makePortableProxyScript(process.execPath, wrappersFolder, {\n//     proxyBasename: 'node',\n//     prependArguments: [...(await getPnpParameters(config))],\n//   });\n//   await makePortableProxyScript(process.execPath, wrappersFolder, {\n//     proxyBasename: 'pika',\n//     prependArguments: [process.argv[1]],\n//   });\n//   return wrappersFolder;\n// }\n// const INVALID_CHAR_REGEX = /\\W/g;\nexport async function makeEnv() {\n    // stage: string,\n    // cwd: string,\n    // config: Config,\n    const env = {\n        NODE: process.execPath,\n        INIT_CWD: process.cwd(),\n        // This lets `process.env.NODE` to override our `process.execPath`.\n        // This is a bit confusing but it is how `npm` was designed so we\n        // try to be compatible with that.\n        ...process.env,\n    };\n    return env;\n}\n//   // Merge in the `env` object specified in .pikarc\n//   const customEnv = config.getOption('env');\n//   if (customEnv && typeof customEnv === 'object') {\n//     Object.assign(env, customEnv);\n//   }\n//   env.npm_lifecycle_event = stage;\n//   env.npm_node_execpath = env.NODE;\n//   env.npm_execpath = env.npm_execpath || (process.mainModule && process.mainModule.filename);\n//   // Set the env to production for npm compat if production mode.\n//   // https://github.com/npm/npm/blob/30d75e738b9cb7a6a3f9b50e971adcbe63458ed3/lib/utils/lifecycle.js#L336\n//   if (config.production) {\n//     env.NODE_ENV = 'production';\n//   }\n//   // Note: npm_config_argv environment variable contains output of nopt - command-line\n//   // parser used by npm. Since we use other parser, we just roughly emulate it's output. (See: #684)\n//   env.npm_config_argv = JSON.stringify({\n//     remain: [],\n//     cooked: config.commandName === 'run' ? [config.commandName, stage] : [config.commandName],\n//     original: process.argv.slice(2),\n//   });\n//   const manifest = await config.maybeReadManifest(cwd);\n//   if (manifest) {\n//     if (manifest.scripts && Object.prototype.hasOwnProperty.call(manifest.scripts, stage)) {\n//       env.npm_lifecycle_script = manifest.scripts[stage];\n//     }\n//     // add npm_package_*\n//     const queue = [['', manifest]];\n//     while (queue.length) {\n//       const [key, val] = queue.pop();\n//       if (typeof val === 'object') {\n//         for (const subKey in val) {\n//           const fullKey = [key, subKey].filter(Boolean).join('_');\n//           if (fullKey && fullKey[0] !== '_' && !IGNORE_MANIFEST_KEYS.has(fullKey)) {\n//             queue.push([fullKey, val[subKey]]);\n//           }\n//         }\n//       } else {\n//         let cleanVal = String(val);\n//         if (cleanVal.indexOf('\\n') >= 0) {\n//           cleanVal = JSON.stringify(cleanVal);\n//         }\n//         //replacing invalid chars with underscore\n//         const cleanKey = key.replace(INVALID_CHAR_REGEX, '_');\n//         env[`npm_package_${cleanKey}`] = cleanVal;\n//       }\n//     }\n//   }\n//   // add npm_config_* and npm_package_config_* from pika config\n//   const keys: Set<string> = new Set([\n//     ...Object.keys(config.registries.pika.config),\n//     ...Object.keys(config.registries.npm.config),\n//   ]);\n//   const cleaned = Array.from(keys)\n//     .filter(key => !key.match(/:_/) && IGNORE_CONFIG_KEYS.indexOf(key) === -1)\n//     .map(key => {\n//       let val = config.getOption(key);\n//       if (!val) {\n//         val = '';\n//       } else if (typeof val === 'number') {\n//         val = '' + val;\n//       } else if (typeof val !== 'string') {\n//         val = JSON.stringify(val);\n//       }\n//       if (val.indexOf('\\n') >= 0) {\n//         val = JSON.stringify(val);\n//       }\n//       return [key, val];\n//     });\n//   // add npm_config_*\n//   for (const [key, val] of cleaned) {\n//     const cleanKey = key.replace(/^_+/, '');\n//     const envKey = `npm_config_${cleanKey}`.replace(INVALID_CHAR_REGEX, '_');\n//     env[envKey] = val;\n//   }\n//   // add npm_package_config_*\n//   if (manifest && manifest.name) {\n//     const packageConfigPrefix = `${manifest.name}:`;\n//     for (const [key, val] of cleaned) {\n//       if (key.indexOf(packageConfigPrefix) !== 0) {\n//         continue;\n//       }\n//       const cleanKey = key.replace(/^_+/, '').replace(packageConfigPrefix, '');\n//       const envKey = `npm_package_config_${cleanKey}`.replace(INVALID_CHAR_REGEX, '_');\n//       env[envKey] = val;\n//     }\n//   }\n//   // split up the path\n//   const envPath = env[constants.ENV_PATH_KEY];\n//   const pathParts = envPath ? envPath.split(path.delimiter) : [];\n//   // Include the directory that contains node so that we can guarantee that the scripts\n//   // will always run with the exact same Node release than the one use to run Pika\n//   const execBin = path.dirname(process.execPath);\n//   if (pathParts.indexOf(execBin) === -1) {\n//     pathParts.unshift(execBin);\n//   }\n//   // Include node-gyp version that was bundled with the current Node.js version,\n//   // if available.\n//   pathParts.unshift(path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'node-gyp-bin'));\n//   pathParts.unshift(\n//     path.join(path.dirname(process.execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin'),\n//   );\n//   // Include node-gyp version from homebrew managed npm, if available.\n//   pathParts.unshift(\n//     path.join(path.dirname(process.execPath), '..', 'libexec', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin'),\n//   );\n//   // Add global bin folder if it is not present already, as some packages depend\n//   // on a globally-installed version of node-gyp.\n//   const globalBin = await getGlobalBinFolder(config, {});\n//   if (pathParts.indexOf(globalBin) === -1) {\n//     pathParts.unshift(globalBin);\n//   }\n//   // Add node_modules .bin folders to the PATH\n//   for (const registry of Object.keys(registries)) {\n//     const binFolder = path.join(config.registries[registry].folder, '.bin');\n//     if (config.workspacesEnabled && config.workspaceRootFolder) {\n//       pathParts.unshift(path.join(config.workspaceRootFolder, binFolder));\n//     }\n//     pathParts.unshift(path.join(config.linkFolder, binFolder));\n//     pathParts.unshift(path.join(cwd, binFolder));\n//     if (config.modulesFolder) {\n//       pathParts.unshift(path.join(config.modulesFolder, '.bin'));\n//     }\n//   }\n//   if (await fs.exists(`${config.lockfileFolder}/${constants.PNP_FILENAME}`)) {\n//     // TODO: Fix. import()? Do we even like that it does this?\n//     throw new Error(\"pnp temporarily not supported\");\n//     const pnpApi = {}; //dynamicRequire(`${config.lockfileFolder}/${constants.PNP_FILENAME}`);\n//     const packageLocator = pnpApi.findPackageLocator(`${config.cwd}/`);\n//     const packageInformation = pnpApi.getPackageInformation(packageLocator);\n//     for (const [name, reference] of packageInformation.packageDependencies.entries()) {\n//       const dependencyInformation = pnpApi.getPackageInformation({name, reference});\n//       if (!dependencyInformation || !dependencyInformation.packageLocation) {\n//         continue;\n//       }\n//       pathParts.unshift(`${dependencyInformation.packageLocation}/.bin`);\n//     }\n//   }\n//   pathParts.unshift(await getWrappersFolder(config));\n//   // join path back together\n//   env[constants.ENV_PATH_KEY] = pathParts.join(path.delimiter);\n//   return env;\n// }\nexport async function executeLifecycleScript({ \n// config,\ncwd, cmd, args, isInteractive, onProgress, customShell, }) {\n    const env = await makeEnv();\n    // await checkForGypIfNeeded(config, cmd, env[constants.ENV_PATH_KEY].split(path.delimiter));\n    if (process.platform === 'win32' && (!customShell || customShell === 'cmd')) {\n        // handle windows run scripts starting with a relative path\n        cmd = fixCmdWinSlashes(cmd);\n    }\n    // By default (non-interactive), pipe everything to the terminal and run child process detached\n    // as long as it's not Windows (since windows does not have /dev/tty)\n    let stdio = ['ignore', 'pipe', 'pipe'];\n    let detached = process.platform !== 'win32';\n    if (isInteractive) {\n        stdio = 'inherit';\n        detached = false;\n    }\n    const shell = customShell || true;\n    const stdout = await child.spawn(cmd, args, { cwd, env, stdio, detached, shell }, onProgress);\n    return { cwd, command: cmd, stdout };\n}\nexport default executeLifecycleScript;\n// let checkGypPromise: Promise<void> = null;\n// // /**\n// //  * Special case: Some packages depend on node-gyp, but don't specify this in\n// //  * their package.json dependencies. They assume that node-gyp is available\n// //  * globally. We need to detect this case and show an error message.\n// //  */\n// function checkForGypIfNeeded(config: Config, cmd: string, paths: Array<string>): Promise<void> {\n//   if (cmd.substr(0, cmd.indexOf(' ')) !== 'node-gyp') {\n//     return Promise.resolve();\n//   }\n//   // Ensure this only runs once, rather than multiple times in parallel.\n//   if (!checkGypPromise) {\n//     checkGypPromise = _checkForGyp(config, paths);\n//   }\n//   return checkGypPromise;\n// }\n// async function _checkForGyp(config: Config, paths: Array<string>): Promise<void> {\n//   const {reporter} = config;\n//   // Check every directory in the PATH\n//   const allChecks = await Promise.all(paths.map(dir => fs.exists(path.join(dir, 'node-gyp'))));\n//   if (allChecks.some(Boolean)) {\n//     // node-gyp is available somewhere\n//     return;\n//   }\n//   reporter.info(reporter.lang('packageRequiresNodeGyp'));\n// }\n// export async function execFromDistributions(config: Config, cwd: string, dist: string, step: string): Promise<void> {\n//   const pkg = await config.maybeReadManifest(cwd);\n//   if (!pkg || !pkg.distributions || !pkg.distributions[dist] || typeof pkg.distributions[dist][step] !== 'string') {\n//     return false;\n//   }\n//   const cmd: ?string = pkg.distributions[dist][step];\n//   await execCommand({stage: 'build', config, cmd, cwd, isInteractive: true});\n//   return true;\n// }\n// export async function execFromManifest(config: Config, commandName: string, cwd: string): Promise<void> {\n//   const pkg = await config.maybeReadManifest(cwd);\n//   if (!pkg || !pkg.scripts) {\n//     return;\n//   }\n//   const cmd: ?string = pkg.scripts[commandName];\n//   if (cmd) {\n//     await execCommand({stage: commandName, config, cmd, cwd, isInteractive: true});\n//   }\n// }\n// export async function execCommand({\n//   stage,\n//   config,\n//   cmd,\n//   cwd,\n//   isInteractive,\n//   customShell,\n// }: {\n//   stage: string;\n//   config: Config;\n//   cmd: string;\n//   cwd: string;\n//   isInteractive: boolean;\n//   customShell?: string;\n// }): Promise<void> {\n//   const {reporter} = config;\n//   try {\n//     reporter.command(cmd);\n//     await executeLifecycleScript({config, cwd, cmd, isInteractive, customShell});\n//     return Promise.resolve();\n//   } catch (err) {\n//     if (err instanceof ProcessTermError) {\n//       throw new MessageError(\n//         err.EXIT_SIGNAL\n//           ? reporter.lang('commandFailedWithSignal', err.EXIT_SIGNAL)\n//           : reporter.lang('commandFailedWithCode', err.EXIT_CODE),\n//       );\n//     } else {\n//       throw err;\n//     }\n//   }\n// }\n"
  },
  {
    "path": "checkpoint/dist-src/util/fix-cmd-win-slashes.js",
    "content": "export function fixCmdWinSlashes(cmd) {\n    function findQuotes(quoteSymbol) {\n        const quotes = [];\n        const addQuote = (_, index) => {\n            quotes.push({ from: index, to: index + _.length });\n            return _;\n        };\n        const regEx = new RegExp(quoteSymbol + '.*' + quoteSymbol);\n        cmd.replace(regEx, addQuote);\n        return quotes;\n    }\n    const quotes = findQuotes('\"').concat(findQuotes(\"'\"));\n    function isInsideQuotes(index) {\n        return quotes.reduce((result, quote) => {\n            return result || (quote.from <= index && index <= quote.to);\n        }, false);\n    }\n    const cmdPrePattern = '((?:^|&&|&|\\\\|\\\\||\\\\|)\\\\s*)';\n    const cmdPattern = '(\".*?\"|\\'.*?\\'|\\\\S*)';\n    const regExp = new RegExp(`${cmdPrePattern}${cmdPattern}`, 'g');\n    return cmd.replace(regExp, (whole, pre, cmd, index) => {\n        if ((pre[0] === '&' || pre[0] === '|') && isInsideQuotes(index)) {\n            return whole;\n        }\n        return pre + cmd.replace(/\\//g, '\\\\');\n    });\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/fs-normalized.js",
    "content": "//\n// // This module serves as a wrapper for file operations that are inconsistant across node and OS versions.\n// import fs from 'fs';\n// import {promisify} from './promise.js';\n// import {constants} from './fs.js';\n// export type CopyFileAction = {\n//   src: string,\n//   dest: string,\n//   atime: Date,\n//   mtime: Date,\n//   mode: number,\n// };\n// let disableTimestampCorrection: boolean; // OS dependent. will be detected on first file copy.\n// const readFileBuffer = promisify(fs.readFile);\n// const close: (fd: number) => Promise<void> = promisify(fs.close);\n// const lstat: (path: string) => Promise<fs.Stats> = promisify(fs.lstat);\n// const open: (path: string, flags: string | number, mode: number) => Promise<number> = promisify(fs.open);\n// const futimes: (fd: number, atime: number, mtime: number) => Promise<void> = promisify(fs.futimes);\n// const write: (\n//   fd: number,\n//   buffer: Buffer,\n//   offset?: number,\n//   length?: number,\n//   position?: number,\n// ) => Promise<void> = promisify(fs.write);\n// /**\n//  * Unlinks the destination to force a recreation. This is needed on case-insensitive file systems\n//  * to force the correct naming when the filename has changed only in character-casing. (Jest -> jest).\n//  */\n// export const copyFile = async function(data: CopyFileAction, cleanup: () => any): Promise<void> {\n//   // $FlowFixMe: Flow doesn't currently support COPYFILE_FICLONE\n//   const ficloneFlag = (constants as any).COPYFILE_FICLONE || 0;\n//   try {\n//     await unlink(data.dest);\n//     await copyFilePoly(data.src, data.dest, ficloneFlag, data);\n//   } finally {\n//     if (cleanup) {\n//       cleanup();\n//     }\n//   }\n// };\n// // Node 8.5.0 introduced `fs.copyFile` which is much faster, so use that when available.\n// // Otherwise we fall back to reading and writing files as buffers.\n// const copyFilePoly: (src: string, dest: string, flags: number, data: CopyFileAction) => Promise<void> = (\n//   src,\n//   dest,\n//   flags,\n//   data,\n// ) => {\n//   if (fs.copyFile) {\n//     return new Promise((resolve, reject) =>\n//       fs.copyFile(src, dest, flags, err => {\n//         if (err) {\n//           reject(err);\n//         } else {\n//           fixTimes(undefined, dest, data).then(() => resolve()).catch(ex => reject(ex));\n//         }\n//       }),\n//     );\n//   } else {\n//     return copyWithBuffer(src, dest, flags, data);\n//   }\n// };\n// const copyWithBuffer: (src: string, dest: string, flags: number, data: CopyFileAction) => Promise<void> = async (\n//   src,\n//   dest,\n//   flags,\n//   data,\n// ) => {\n//   // Use open -> write -> futimes -> close sequence to avoid opening the file twice:\n//   // one with writeFile and one with utimes\n//   const fd = await open(dest, 'w', data.mode);\n//   try {\n//     const buffer = await readFileBuffer(src);\n//     await write(fd, buffer, 0, buffer.length);\n//     await fixTimes(fd, dest, data);\n//   } finally {\n//     await close(fd);\n//   }\n// };\n// // We want to preserve file timestamps when copying a file, since pika uses them to decide if a file has\n// // changed compared to the cache.\n// // There are some OS specific cases here:\n// // * On linux, fs.copyFile does not preserve timestamps, but does on OSX and Win.\n// // * On windows, you must open a file with write permissions to call `fs.futimes`.\n// // * On OSX you can open with read permissions and still call `fs.futimes`.\n// async function fixTimes(fd: number | undefined, dest: string, data: CopyFileAction): Promise<void> {\n//   const doOpen = fd === undefined;\n//   let openfd: number = fd ? fd : -1;\n//   if (disableTimestampCorrection === undefined) {\n//     // if timestamps match already, no correction is needed.\n//     // the need to correct timestamps varies based on OS and node versions.\n//     const destStat = await lstat(dest);\n//     disableTimestampCorrection = fileDatesEqual(destStat.mtime, data.mtime);\n//   }\n//   if (disableTimestampCorrection) {\n//     return;\n//   }\n//   if (doOpen) {\n//     try {\n//       openfd = await open(dest, 'a', data.mode);\n//     } catch (er) {\n//       // file is likely read-only\n//       try {\n//         openfd = await open(dest, 'r', data.mode);\n//       } catch (err) {\n//         // We can't even open this file for reading.\n//         return;\n//       }\n//     }\n//   }\n//   try {\n//     if (openfd) {\n//       await futimes(openfd, data.atime, data.mtime);\n//     }\n//   } catch (er) {\n//     // If `futimes` throws an exception, we probably have a case of a read-only file on Windows.\n//     // In this case we can just return. The incorrect timestamp will just cause that file to be recopied\n//     // on subsequent installs, which will effect pika performance but not break anything.\n//   } finally {\n//     if (doOpen && openfd) {\n//       await close(openfd);\n//     }\n//   }\n// }\n// // Compare file timestamps.\n// // Some versions of Node on windows zero the milliseconds when utime is used.\n// export const fileDatesEqual = (a: Date, b: Date) => {\n//   const aTime = a.getTime();\n//   const bTime = b.getTime();\n//   if (process.platform !== 'win32') {\n//     return aTime === bTime;\n//   }\n//   // See https://github.com/nodejs/node/pull/12607\n//   // Submillisecond times from stat and utimes are truncated on Windows,\n//   // causing a file with mtime 8.0079998 and 8.0081144 to become 8.007 and 8.008\n//   // and making it impossible to update these files to their correct timestamps.\n//   if (Math.abs(aTime - bTime) <= 1) {\n//     return true;\n//   }\n//   const aTimeSec = Math.floor(aTime / 1000);\n//   const bTimeSec = Math.floor(bTime / 1000);\n//   // See https://github.com/nodejs/node/issues/2069\n//   // Some versions of Node on windows zero the milliseconds when utime is used\n//   // So if any of the time has a milliseconds part of zero we suspect that the\n//   // bug is present and compare only seconds.\n//   if (aTime - aTimeSec * 1000 === 0 || bTime - bTimeSec * 1000 === 0) {\n//     return aTimeSec === bTimeSec;\n//   }\n//   return aTime === bTime;\n// };\n"
  },
  {
    "path": "checkpoint/dist-src/util/fs.js",
    "content": "import { promisify } from 'util';\nimport _rimraf from 'rimraf';\nimport _mkdirp from 'mkdirp';\nimport _glob from 'glob';\nexport const unlink = promisify(_rimraf);\nexport const glob = promisify(_glob);\nexport const mkdirp = promisify(_mkdirp);\n//\n// import {ReadStream} from 'fs';\n// import Reporter from '../reporters/base-reporter.js';\n// import {CopyFileAction} from './fs-normalized.js';\nimport * as os from 'os';\nimport * as path from 'path';\n// import BlockingQueue from './blocking-queue.js';\n// import * as promise from './promise.js';\nimport map from './map.js';\n// import {copyFile, fileDatesEqual, unlink} from './fs-normalized.js';\n// export const constants =\n//   typeof fs.constants !== 'undefined'\n//     ? fs.constants\n//     : {\n//         R_OK: fs.R_OK,\n//         W_OK: fs.W_OK,\n//         X_OK: fs.X_OK,\n//       };\n// export const lockQueue = new BlockingQueue('fs lock');\nimport * as fs from 'fs';\nimport * as util from 'util';\nexport const open = util.promisify(fs.open);\nexport const writeFile = util.promisify(fs.writeFile);\nexport const readlink = util.promisify(fs.readlink);\nexport const realpath = util.promisify(fs.realpath);\nexport const readdir = util.promisify(fs.readdir);\nexport const rename = util.promisify(fs.rename);\nexport const access = util.promisify(fs.access);\nexport const stat = util.promisify(fs.stat);\nexport const exists = util.promisify(fs.exists);\nexport const lstat = util.promisify(fs.lstat);\nexport const chmod = util.promisify(fs.chmod);\nexport const link = util.promisify(fs.link);\nexport const copyFile = util.promisify(fs.copyFile);\nconst readFileBuffer = util.promisify(fs.readFile);\nexport const readFile = (path) => {\n    return util.promisify(fs.readFile)(path, { encoding: 'utf-8' });\n};\n// export {unlink};\n// // fs.copyFile uses the native file copying instructions on the system, performing much better\n// // than any JS-based solution and consumes fewer resources. Repeated testing to fine tune the\n// // concurrency level revealed 128 as the sweet spot on a quad-core, 16 CPU Intel system with SSD.\n// const CONCURRENT_QUEUE_ITEMS = fs.copyFile ? 128 : 4;\n// const fsSymlink: (target: string, path: string, type?: 'dir' | 'file' | 'junction') => Promise<void> = promisify(\n//   fs.symlink,\n// );\n// import invariant from 'invariant';\nimport stripBOM from 'strip-bom';\n// const noop = () => {};\n// export type CopyQueueItem = {\n//   src: string,\n//   dest: string,\n//   type?: string,\n//   onFresh?: () => void,\n//   onDone?: () => void,\n// };\n// type CopyQueue = Array<CopyQueueItem>;\n// type LinkFileAction = {\n//   src: string,\n//   dest: string,\n//   removeDest: boolean,\n// };\n// type CopySymlinkAction = {\n//   dest: string,\n//   linkname: string,\n// };\n// type CopyActions = {\n//   file: Array<CopyFileAction>,\n//   symlink: Array<CopySymlinkAction>,\n//   link: Array<LinkFileAction>,\n// };\n// type CopyOptions = {\n//   onProgress: (dest: string) => void,\n//   onStart: (num: number) => void,\n//   possibleExtraneous: Set<string>,\n//   ignoreBasenames: Array<string>,\n//   artifactFiles: Array<string>,\n// };\n// type FailedFolderQuery = {\n//   error: Error,\n//   folder: string,\n// };\n// type FolderQueryResult = {\n//   skipped: Array<FailedFolderQuery>,\n//   folder?: string,\n// };\n// async function buildActionsForCopy(\n//   queue: CopyQueue,\n//   events: CopyOptions,\n//   possibleExtraneous: Set<string>,\n//   reporter: Reporter,\n// ): Promise<CopyActions> {\n//   const artifactFiles: Set<string> = new Set(events.artifactFiles || []);\n//   const files: Set<string> = new Set();\n//   // initialise events\n//   for (const item of queue) {\n//     const onDone = item.onDone;\n//     item.onDone = () => {\n//       events.onProgress(item.dest);\n//       if (onDone) {\n//         onDone();\n//       }\n//     };\n//   }\n//   events.onStart(queue.length);\n//   // start building actions\n//   const actions: CopyActions = {\n//     file: [],\n//     symlink: [],\n//     link: [],\n//   };\n//   // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items\n//   // at a time due to the requirement to push items onto the queue\n//   while (queue.length) {\n//     const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);\n//     await Promise.all(items.map(build));\n//   }\n//   // simulate the existence of some files to prevent considering them extraneous\n//   for (const file of artifactFiles) {\n//     if (possibleExtraneous.has(file)) {\n//       reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));\n//       possibleExtraneous.delete(file);\n//     }\n//   }\n//   for (const loc of possibleExtraneous) {\n//     if (files.has(loc.toLowerCase())) {\n//       possibleExtraneous.delete(loc);\n//     }\n//   }\n//   return actions;\n//   //\n//   async function build(data: CopyQueueItem): Promise<void> {\n//     const {src, dest, type} = data;\n//     const onFresh = data.onFresh || noop;\n//     const onDone = data.onDone || noop;\n//     // TODO https://github.com/yarnpkg/yarn/issues/3751\n//     // related to bundled dependencies handling\n//     if (files.has(dest.toLowerCase())) {\n//       reporter.verbose(`The case-insensitive file ${dest} shouldn't be copied twice in one bulk copy`);\n//     } else {\n//       files.add(dest.toLowerCase());\n//     }\n//     if (type === 'symlink') {\n//       await mkdirp(path.dirname(dest));\n//       onFresh();\n//       actions.symlink.push({\n//         dest,\n//         linkname: src,\n//       });\n//       onDone();\n//       return;\n//     }\n//     if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {\n//       // ignored file\n//       return;\n//     }\n//     const srcStat = await lstat(src);\n//     let srcFiles;\n//     if (srcStat.isDirectory()) {\n//       srcFiles = await readdir(src);\n//     }\n//     let destStat;\n//     try {\n//       // try accessing the destination\n//       destStat = await lstat(dest);\n//     } catch (e) {\n//       // proceed if destination doesn't exist, otherwise error\n//       if (e.code !== 'ENOENT') {\n//         throw e;\n//       }\n//     }\n//     // if destination exists\n//     if (destStat) {\n//       const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();\n//       const bothFolders = srcStat.isDirectory() && destStat.isDirectory();\n//       const bothFiles = srcStat.isFile() && destStat.isFile();\n//       // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving\n//       // us modes that aren't valid. investigate this, it's generally safe to proceed.\n//       /* if (srcStat.mode !== destStat.mode) {\n//         try {\n//           await access(dest, srcStat.mode);\n//         } catch (err) {}\n//       } */\n//       if (bothFiles && artifactFiles.has(dest)) {\n//         // this file gets changed during build, likely by a custom install script. Don't bother checking it.\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkipArtifact', src));\n//         return;\n//       }\n//       if (bothFiles && srcStat.size === destStat.size && fileDatesEqual(srcStat.mtime, destStat.mtime)) {\n//         // we can safely assume this is the same file\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime));\n//         return;\n//       }\n//       if (bothSymlinks) {\n//         const srcReallink = await readlink(src);\n//         if (srcReallink === (await readlink(dest))) {\n//           // if both symlinks are the same then we can continue on\n//           onDone();\n//           reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));\n//           return;\n//         }\n//       }\n//       if (bothFolders) {\n//         // mark files that aren't in this folder as possibly extraneous\n//         const destFiles = await readdir(dest);\n//         invariant(srcFiles, 'src files not initialised');\n//         for (const file of destFiles) {\n//           if (srcFiles.indexOf(file) < 0) {\n//             const loc = path.join(dest, file);\n//             possibleExtraneous.add(loc);\n//             if ((await lstat(loc)).isDirectory()) {\n//               for (const file of await readdir(loc)) {\n//                 possibleExtraneous.add(path.join(loc, file));\n//               }\n//             }\n//           }\n//         }\n//       }\n//     }\n//     if (destStat && destStat.isSymbolicLink()) {\n//       await unlink(dest);\n//       destStat = null;\n//     }\n//     if (srcStat.isSymbolicLink()) {\n//       onFresh();\n//       const linkname = await readlink(src);\n//       actions.symlink.push({\n//         dest,\n//         linkname,\n//       });\n//       onDone();\n//     } else if (srcStat.isDirectory()) {\n//       if (!destStat) {\n//         reporter.verbose(reporter.lang('verboseFileFolder', dest));\n//         await mkdirp(dest);\n//       }\n//       const destParts = dest.split(path.sep);\n//       while (destParts.length) {\n//         files.add(destParts.join(path.sep).toLowerCase());\n//         destParts.pop();\n//       }\n//       // push all files to queue\n//       invariant(srcFiles, 'src files not initialised');\n//       let remaining = srcFiles.length;\n//       if (!remaining) {\n//         onDone();\n//       }\n//       for (const file of srcFiles) {\n//         queue.push({\n//           dest: path.join(dest, file),\n//           onFresh,\n//           onDone: () => {\n//             if (--remaining === 0) {\n//               onDone();\n//             }\n//           },\n//           src: path.join(src, file),\n//         });\n//       }\n//     } else if (srcStat.isFile()) {\n//       onFresh();\n//       actions.file.push({\n//         src,\n//         dest,\n//         atime: srcStat.atime,\n//         mtime: srcStat.mtime,\n//         mode: srcStat.mode,\n//       });\n//       onDone();\n//     } else {\n//       throw new Error(`unsure how to copy this: ${src}`);\n//     }\n//   }\n// }\n// async function buildActionsForHardlink(\n//   queue: CopyQueue,\n//   events: CopyOptions,\n//   possibleExtraneous: Set<string>,\n//   reporter: Reporter,\n// ): Promise<CopyActions> {\n//   const artifactFiles: Set<string> = new Set(events.artifactFiles || []);\n//   const files: Set<string> = new Set();\n//   // initialise events\n//   for (const item of queue) {\n//     const onDone = item.onDone || noop;\n//     item.onDone = () => {\n//       events.onProgress(item.dest);\n//       onDone();\n//     };\n//   }\n//   events.onStart(queue.length);\n//   // start building actions\n//   const actions: CopyActions = {\n//     file: [],\n//     symlink: [],\n//     link: [],\n//   };\n//   // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items\n//   // at a time due to the requirement to push items onto the queue\n//   while (queue.length) {\n//     const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);\n//     await Promise.all(items.map(build));\n//   }\n//   // simulate the existence of some files to prevent considering them extraneous\n//   for (const file of artifactFiles) {\n//     if (possibleExtraneous.has(file)) {\n//       reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));\n//       possibleExtraneous.delete(file);\n//     }\n//   }\n//   for (const loc of possibleExtraneous) {\n//     if (files.has(loc.toLowerCase())) {\n//       possibleExtraneous.delete(loc);\n//     }\n//   }\n//   return actions;\n//   //\n//   async function build(data: CopyQueueItem): Promise<void> {\n//     const {src, dest} = data;\n//     const onFresh = data.onFresh || noop;\n//     const onDone = data.onDone || noop;\n//     if (files.has(dest.toLowerCase())) {\n//       // Fixes issue https://github.com/yarnpkg/yarn/issues/2734\n//       // When bulk hardlinking we have A -> B structure that we want to hardlink to A1 -> B1,\n//       // package-linker passes that modules A1 and B1 need to be hardlinked,\n//       // the recursive linking algorithm of A1 ends up scheduling files in B1 to be linked twice which will case\n//       // an exception.\n//       onDone();\n//       return;\n//     }\n//     files.add(dest.toLowerCase());\n//     if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {\n//       // ignored file\n//       return;\n//     }\n//     const srcStat = await lstat(src);\n//     let srcFiles;\n//     if (srcStat.isDirectory()) {\n//       srcFiles = await readdir(src);\n//     }\n//     const destExists = await exists(dest);\n//     if (destExists) {\n//       const destStat = await lstat(dest);\n//       const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();\n//       const bothFolders = srcStat.isDirectory() && destStat.isDirectory();\n//       const bothFiles = srcStat.isFile() && destStat.isFile();\n//       if (srcStat.mode !== destStat.mode) {\n//         try {\n//           await access(dest, srcStat.mode);\n//         } catch (err) {\n//           // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving\n//           // us modes that aren't valid. investigate this, it's generally safe to proceed.\n//           reporter.verbose(err);\n//         }\n//       }\n//       if (bothFiles && artifactFiles.has(dest)) {\n//         // this file gets changed during build, likely by a custom install script. Don't bother checking it.\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkipArtifact', src));\n//         return;\n//       }\n//       // correct hardlink\n//       if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) {\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino));\n//         return;\n//       }\n//       if (bothSymlinks) {\n//         const srcReallink = await readlink(src);\n//         if (srcReallink === (await readlink(dest))) {\n//           // if both symlinks are the same then we can continue on\n//           onDone();\n//           reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));\n//           return;\n//         }\n//       }\n//       if (bothFolders) {\n//         // mark files that aren't in this folder as possibly extraneous\n//         const destFiles = await readdir(dest);\n//         invariant(srcFiles, 'src files not initialised');\n//         for (const file of destFiles) {\n//           if (srcFiles.indexOf(file) < 0) {\n//             const loc = path.join(dest, file);\n//             possibleExtraneous.add(loc);\n//             if ((await lstat(loc)).isDirectory()) {\n//               for (const file of await readdir(loc)) {\n//                 possibleExtraneous.add(path.join(loc, file));\n//               }\n//             }\n//           }\n//         }\n//       }\n//     }\n//     if (srcStat.isSymbolicLink()) {\n//       onFresh();\n//       const linkname = await readlink(src);\n//       actions.symlink.push({\n//         dest,\n//         linkname,\n//       });\n//       onDone();\n//     } else if (srcStat.isDirectory()) {\n//       reporter.verbose(reporter.lang('verboseFileFolder', dest));\n//       await mkdirp(dest);\n//       const destParts = dest.split(path.sep);\n//       while (destParts.length) {\n//         files.add(destParts.join(path.sep).toLowerCase());\n//         destParts.pop();\n//       }\n//       // push all files to queue\n//       invariant(srcFiles, 'src files not initialised');\n//       let remaining = srcFiles.length;\n//       if (!remaining) {\n//         onDone();\n//       }\n//       for (const file of srcFiles) {\n//         queue.push({\n//           onFresh,\n//           src: path.join(src, file),\n//           dest: path.join(dest, file),\n//           onDone: () => {\n//             if (--remaining === 0) {\n//               onDone();\n//             }\n//           },\n//         });\n//       }\n//     } else if (srcStat.isFile()) {\n//       onFresh();\n//       actions.link.push({\n//         src,\n//         dest,\n//         removeDest: destExists,\n//       });\n//       onDone();\n//     } else {\n//       throw new Error(`unsure how to copy this: ${src}`);\n//     }\n//   }\n// }\n// export function copy(src: string, dest: string, reporter: Reporter): Promise<void> {\n//   return copyBulk([{src, dest}], reporter);\n// }\n// export async function copyBulk(\n//   queue: CopyQueue,\n//   reporter: Reporter,\n//   _events?: {\n//     onProgress?: (dest: string) => void,\n//     onStart?: (num: number) => void,\n//     possibleExtraneous: Set<string>,\n//     ignoreBasenames?: Array<string>,\n//     artifactFiles?: Array<string>,\n//   },\n// ): Promise<void> {\n//   const events: CopyOptions = {\n//     onStart: (_events && _events.onStart) || noop,\n//     onProgress: (_events && _events.onProgress) || noop,\n//     possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),\n//     ignoreBasenames: (_events && _events.ignoreBasenames) || [],\n//     artifactFiles: (_events && _events.artifactFiles) || [],\n//   };\n//   const actions: CopyActions = await buildActionsForCopy(queue, events, events.possibleExtraneous, reporter);\n//   events.onStart(actions.file.length + actions.symlink.length + actions.link.length);\n//   const fileActions: Array<CopyFileAction> = actions.file;\n//   const currentlyWriting: Map<string, Promise<void>> = new Map();\n//   await promise.queue(\n//     fileActions,\n//     async (data: CopyFileAction): Promise<void> => {\n//       let writePromise;\n//       while ((writePromise = currentlyWriting.get(data.dest))) {\n//         await writePromise;\n//       }\n//       reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest));\n//       const copier = copyFile(data, () => currentlyWriting.delete(data.dest));\n//       currentlyWriting.set(data.dest, copier);\n//       events.onProgress(data.dest);\n//       return copier;\n//     },\n//     CONCURRENT_QUEUE_ITEMS,\n//   );\n//   // we need to copy symlinks last as they could reference files we were copying\n//   const symlinkActions: Array<CopySymlinkAction> = actions.symlink;\n//   await promise.queue(symlinkActions, (data): Promise<void> => {\n//     const linkname = path.resolve(path.dirname(data.dest), data.linkname);\n//     reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));\n//     return symlink(linkname, data.dest);\n//   });\n// }\n// export async function hardlinkBulk(\n//   queue: CopyQueue,\n//   reporter: Reporter,\n//   _events?: {\n//     onProgress?: (dest: string) => void,\n//     onStart?: (num: number) => void,\n//     possibleExtraneous: Set<string>,\n//     artifactFiles?: Array<string>,\n//   },\n// ): Promise<void> {\n//   const events: CopyOptions = {\n//     onStart: (_events && _events.onStart) || noop,\n//     onProgress: (_events && _events.onProgress) || noop,\n//     possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),\n//     artifactFiles: (_events && _events.artifactFiles) || [],\n//     ignoreBasenames: [],\n//   };\n//   const actions: CopyActions = await buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter);\n//   events.onStart(actions.file.length + actions.symlink.length + actions.link.length);\n//   const fileActions: Array<LinkFileAction> = actions.link;\n//   await promise.queue(\n//     fileActions,\n//     async (data): Promise<void> => {\n//       reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest));\n//       if (data.removeDest) {\n//         await unlink(data.dest);\n//       }\n//       await link(data.src, data.dest);\n//     },\n//     CONCURRENT_QUEUE_ITEMS,\n//   );\n//   // we need to copy symlinks last as they could reference files we were copying\n//   const symlinkActions: Array<CopySymlinkAction> = actions.symlink;\n//   await promise.queue(symlinkActions, (data): Promise<void> => {\n//     const linkname = path.resolve(path.dirname(data.dest), data.linkname);\n//     reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));\n//     return symlink(linkname, data.dest);\n//   });\n// }\n// function _readFile(loc: string, encoding: string): Promise<any> {\n//   return new Promise((resolve, reject) => {\n//     fs.readFile(loc, encoding, function(err, content) {\n//       if (err) {\n//         reject(err);\n//       } else {\n//         resolve(content);\n//       }\n//     });\n//   });\n// }\n// export function readFile(loc: string): Promise<string> {\n//   return _readFile(loc, 'utf8').then(normalizeOS);\n// }\n// export function readFileRaw(loc: string): Promise<Buffer> {\n//   return _readFile(loc, 'binary');\n// }\n// export async function readFileAny(files: Array<string>): Promise<string | null> {\n//   for (const file of files) {\n//     if (await exists(file)) {\n//       return readFile(file);\n//     }\n//   }\n//   return null;\n// }\nexport async function readJson(loc) {\n    return (await readJsonAndFile(loc)).object;\n}\nexport async function readJsonAndFile(loc) {\n    const file = await readFile(loc);\n    try {\n        return {\n            object: map(JSON.parse(stripBOM(file))),\n            content: file,\n        };\n    }\n    catch (err) {\n        err.message = `${loc}: ${err.message}`;\n        throw err;\n    }\n}\nexport async function walk(dir, relativeDir, ignoreBasenames = new Set()) {\n    let files = [];\n    let filenames = await readdir(dir);\n    if (ignoreBasenames.size) {\n        filenames = filenames.filter(name => !ignoreBasenames.has(name));\n    }\n    for (const name of filenames) {\n        const relative = relativeDir ? path.join(relativeDir, name) : name;\n        const loc = path.join(dir, name);\n        const stat = await lstat(loc);\n        files.push({\n            relative,\n            basename: name,\n            absolute: loc,\n            mtime: +stat.mtime,\n        });\n        if (stat.isDirectory()) {\n            files = files.concat(await walk(loc, relative, ignoreBasenames));\n        }\n    }\n    return files;\n}\n// export async function getFileSizeOnDisk(loc: string): Promise<number> {\n//   const stat = await lstat(loc);\n//   const {size, blksize: blockSize} = stat;\n//   return Math.ceil(size / blockSize) * blockSize;\n// }\n// export function normalizeOS(body: string): string {\n//   return body.replace(/\\r\\n/g, '\\n');\n// }\nconst cr = '\\r'.charCodeAt(0);\nconst lf = '\\n'.charCodeAt(0);\nasync function getEolFromFile(path) {\n    if (!(await exists(path))) {\n        return undefined;\n    }\n    const buffer = await readFileBuffer(path);\n    for (let i = 0; i < buffer.length; ++i) {\n        if (buffer[i] === cr) {\n            return '\\r\\n';\n        }\n        if (buffer[i] === lf) {\n            return '\\n';\n        }\n    }\n    return undefined;\n}\nexport async function writeFilePreservingEol(path, data) {\n    const eol = (await getEolFromFile(path)) || os.EOL;\n    if (eol !== '\\n') {\n        data = data.replace(/\\n/g, eol);\n    }\n    await writeFile(path, data);\n}\n// export async function hardlinksWork(dir: string): Promise<boolean> {\n//   const filename = 'test-file' + Math.random();\n//   const file = path.join(dir, filename);\n//   const fileLink = path.join(dir, filename + '-link');\n//   try {\n//     await writeFile(file, 'test');\n//     await link(file, fileLink);\n//   } catch (err) {\n//     return false;\n//   } finally {\n//     await unlink(file);\n//     await unlink(fileLink);\n//   }\n//   return true;\n// }\n// // not a strict polyfill for Node's fs.mkdtemp\n// export async function makeTempDir(prefix?: string): Promise<string> {\n//   const dir = path.join(os.tmpdir(), `pika-${prefix || ''}-${Date.now()}-${Math.random()}`);\n//   await unlink(dir);\n//   await mkdirp(dir);\n//   return dir;\n// }\n// export async function readFirstAvailableStream(paths: Iterable<string>): Promise<?ReadStream> {\n//   for (const path of paths) {\n//     try {\n//       const fd = await open(path, 'r');\n//       return fs.createReadStream(path, {fd});\n//     } catch (err) {\n//       // Try the next one\n//     }\n//   }\n//   return null;\n// }\n// export async function getFirstSuitableFolder(\n//   paths: Iterable<string>,\n//   mode: number = constants.W_OK | constants.X_OK, // eslint-disable-line no-bitwise\n// ): Promise<FolderQueryResult> {\n//   const result: FolderQueryResult = {\n//     skipped: [],\n//     folder: null,\n//   };\n//   for (const folder of paths) {\n//     try {\n//       await mkdirp(folder);\n//       await access(folder, mode);\n//       result.folder = folder;\n//       return result;\n//     } catch (error) {\n//       result.skipped.push({\n//         error,\n//         folder,\n//       });\n//     }\n//   }\n//   return result;\n// }\n"
  },
  {
    "path": "checkpoint/dist-src/util/map.js",
    "content": "export default function nullify(obj) {\n    if (Array.isArray(obj)) {\n        for (const item of obj) {\n            nullify(item);\n        }\n    }\n    else if ((obj !== null && typeof obj === 'object') || typeof obj === 'function') {\n        Object.setPrototypeOf(obj, null);\n        // for..in can only be applied to 'object', not 'function'\n        if (typeof obj === 'object') {\n            for (const key in obj) {\n                nullify(obj[key]);\n            }\n        }\n    }\n    return obj;\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/misc.js",
    "content": "/* @flow */\nimport _camelCase from 'camelcase';\nexport function sortAlpha(a, b) {\n    // sort alphabetically in a deterministic way\n    const shortLen = Math.min(a.length, b.length);\n    for (let i = 0; i < shortLen; i++) {\n        const aChar = a.charCodeAt(i);\n        const bChar = b.charCodeAt(i);\n        if (aChar !== bChar) {\n            return aChar - bChar;\n        }\n    }\n    return a.length - b.length;\n}\nexport function sortOptionsByFlags(a, b) {\n    const aOpt = a.flags.replace(/-/g, '');\n    const bOpt = b.flags.replace(/-/g, '');\n    return sortAlpha(aOpt, bOpt);\n}\nexport function entries(obj) {\n    const entries = [];\n    if (obj) {\n        for (const key in obj) {\n            entries.push([key, obj[key]]);\n        }\n    }\n    return entries;\n}\nexport function removePrefix(pattern, prefix) {\n    if (pattern.startsWith(prefix)) {\n        pattern = pattern.slice(prefix.length);\n    }\n    return pattern;\n}\nexport function removeSuffix(pattern, suffix) {\n    if (pattern.endsWith(suffix)) {\n        return pattern.slice(0, -suffix.length);\n    }\n    return pattern;\n}\nexport function addSuffix(pattern, suffix) {\n    if (!pattern.endsWith(suffix)) {\n        return pattern + suffix;\n    }\n    return pattern;\n}\nexport function hyphenate(str) {\n    return str.replace(/[A-Z]/g, match => {\n        return '-' + match.charAt(0).toLowerCase();\n    });\n}\nexport function camelCase(str) {\n    if (/[A-Z]/.test(str)) {\n        return null;\n    }\n    else {\n        return _camelCase(str);\n    }\n}\nexport function compareSortedArrays(array1, array2) {\n    if (array1.length !== array2.length) {\n        return false;\n    }\n    for (let i = 0, len = array1.length; i < len; i++) {\n        if (array1[i] !== array2[i]) {\n            return false;\n        }\n    }\n    return true;\n}\nexport function sleep(ms) {\n    return new Promise(resolve => {\n        setTimeout(resolve, ms);\n    });\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/normalize-manifest/fix.js",
    "content": "import { MANIFEST_FIELDS } from '../../constants.js';\nimport { isValidLicense } from './util.js';\nimport { normalizePerson, extractDescription } from './util.js';\nimport inferLicense from './infer-license.js';\nimport * as fs from '../fs.js';\nimport semver from 'semver';\nimport * as path from 'path';\nimport * as nodeUrl from 'url';\nconst LICENSE_RENAMES = {\n    'MIT/X11': 'MIT',\n    X11: 'MIT',\n};\nexport default (async function (info, moduleLoc, reporter, warn) {\n    const files = await fs.readdir(moduleLoc);\n    // clean info.version\n    if (typeof info.version === 'string') {\n        info.version = semver.clean(info.version) || info.version;\n    }\n    // if name or version aren't set then set them to empty strings\n    info.name = info.name || '';\n    info.version = info.version || '';\n    // if the man field is a string then coerce it to an array\n    if (typeof info.man === 'string') {\n        info.man = [info.man];\n    }\n    // if the keywords field is a string then split it on any whitespace\n    if (typeof info.keywords === 'string') {\n        info.keywords = info.keywords.split(/\\s+/g);\n    }\n    // if there's no contributors field but an authors field then expand it\n    if (!info.contributors && files.indexOf('AUTHORS') >= 0) {\n        const authorsFilepath = path.join(moduleLoc, 'AUTHORS');\n        const authorsFilestats = await fs.stat(authorsFilepath);\n        if (authorsFilestats.isFile()) {\n            let authors = await fs.readFile(authorsFilepath);\n            info.contributors = authors\n                .split(/\\r?\\n/g) // split on lines\n                .map((line) => line.replace(/^\\s*#.*$/, '').trim()) // remove comments\n                .filter((line) => !!line); // remove empty lines;\n        }\n    }\n    // expand people fields to objects\n    if (typeof info.author === 'string' || typeof info.author === 'object') {\n        info.author = normalizePerson(info.author);\n    }\n    if (Array.isArray(info.contributors)) {\n        info.contributors = info.contributors.map(normalizePerson);\n    }\n    if (Array.isArray(info.maintainers)) {\n        info.maintainers = info.maintainers.map(normalizePerson);\n    }\n    // if there's no readme field then load the README file from the cwd\n    if (!info.readme) {\n        const readmeCandidates = files\n            .filter((filename) => {\n            const lower = filename.toLowerCase();\n            return lower === 'readme' || lower.indexOf('readme.') === 0;\n        })\n            .sort((filename1, filename2) => {\n            // favor files with extensions\n            return filename2.indexOf('.') - filename1.indexOf('.');\n        });\n        for (const readmeFilename of readmeCandidates) {\n            const readmeFilepath = path.join(moduleLoc, readmeFilename);\n            const readmeFileStats = await fs.stat(readmeFilepath);\n            if (readmeFileStats.isFile()) {\n                info.readmeFilename = readmeFilename;\n                info.readme = await fs.readFile(readmeFilepath);\n                break;\n            }\n        }\n    }\n    // if there's no description then take the first paragraph from the readme\n    if (!info.description && info.readme) {\n        const desc = extractDescription(info.readme);\n        if (desc) {\n            info.description = desc;\n        }\n    }\n    // support array of engine keys\n    if (Array.isArray(info.engines)) {\n        const engines = {};\n        for (const str of info.engines) {\n            if (typeof str === 'string') {\n                const [name, ...patternParts] = str.trim().split(/ +/g);\n                engines[name] = patternParts.join(' ');\n            }\n        }\n        info.engines = engines;\n    }\n    // allow bugs to be specified as a string, expand it to an object with a single url prop\n    if (typeof info.bugs === 'string') {\n        info.bugs = { url: info.bugs };\n    }\n    // normalize homepage url to http\n    if (typeof info.homepage === 'string') {\n        const parts = nodeUrl.parse(info.homepage);\n        parts.protocol = parts.protocol || 'http:';\n        if (parts.pathname && !parts.hostname) {\n            parts.hostname = parts.pathname;\n            parts.pathname = '';\n        }\n        info.homepage = nodeUrl.format(parts);\n    }\n    // if the `bin` field is as string then expand it to an object with a single property\n    // based on the original `bin` field and `name field`\n    // { name: \"foo\", bin: \"cli.js\" } -> { name: \"foo\", bin: { foo: \"cli.js\" } }\n    if (typeof info.name === 'string' && typeof info.bin === 'string' && info.bin.length > 0) {\n        // Remove scoped package name for consistency with NPM's bin field fixing behaviour\n        const name = info.name.replace(/^@[^\\/]+\\//, '');\n        info.bin = { [name]: info.bin };\n    }\n    // bundleDependencies is an alias for bundledDependencies\n    if (info.bundledDependencies) {\n        info.bundleDependencies = info.bundledDependencies;\n        delete info.bundledDependencies;\n    }\n    let scripts;\n    // dummy script object to shove file inferred scripts onto\n    if (info.scripts && typeof info.scripts === 'object') {\n        scripts = info.scripts;\n    }\n    else {\n        scripts = {};\n    }\n    // if there's a server.js file and no start script then set it to `node server.js`\n    if (!scripts.start && files.indexOf('server.js') >= 0) {\n        scripts.start = 'node server';\n    }\n    // if there's a binding.gyp file and no install script then set it to `node-gyp rebuild`\n    if (!scripts.install && files.indexOf('binding.gyp') >= 0) {\n        scripts.install = 'node-gyp rebuild';\n    }\n    // set scripts if we've polluted the empty object\n    if (Object.keys(scripts).length) {\n        info.scripts = scripts;\n    }\n    const dirs = info.directories;\n    if (dirs && typeof dirs === 'object') {\n        const binDir = dirs.bin;\n        if (!info.bin && binDir && typeof binDir === 'string') {\n            const bin = (info.bin = {});\n            const fullBinDir = path.join(moduleLoc, binDir);\n            if (await fs.exists(fullBinDir)) {\n                for (const scriptName of await fs.readdir(fullBinDir)) {\n                    if (scriptName[0] === '.') {\n                        continue;\n                    }\n                    bin[scriptName] = path.join('.', binDir, scriptName);\n                }\n            }\n            else {\n                warn(reporter.lang('manifestDirectoryNotFound', binDir, info.name));\n            }\n        }\n        const manDir = dirs.man;\n        if (!info.man && typeof manDir === 'string') {\n            const man = (info.man = []);\n            const fullManDir = path.join(moduleLoc, manDir);\n            if (await fs.exists(fullManDir)) {\n                for (const filename of await fs.readdir(fullManDir)) {\n                    if (/^(.*?)\\.[0-9]$/.test(filename)) {\n                        man.push(path.join('.', manDir, filename));\n                    }\n                }\n            }\n            else {\n                warn(reporter.lang('manifestDirectoryNotFound', manDir, info.name));\n            }\n        }\n    }\n    delete info.directories;\n    // normalize licenses field\n    const licenses = info.licenses;\n    if (Array.isArray(licenses) && !info.license) {\n        let licenseTypes = [];\n        for (let license of licenses) {\n            if (license && typeof license === 'object') {\n                license = license.type;\n            }\n            if (typeof license === 'string') {\n                licenseTypes.push(license);\n            }\n        }\n        licenseTypes = licenseTypes.filter(isValidLicense);\n        if (licenseTypes.length === 1) {\n            info.license = licenseTypes[0];\n        }\n        else if (licenseTypes.length) {\n            info.license = `(${licenseTypes.join(' OR ')})`;\n        }\n    }\n    const license = info.license;\n    // normalize license\n    if (license && typeof license === 'object') {\n        info.license = license.type;\n    }\n    // get license file\n    const licenseFile = files.find((filename) => {\n        const lower = filename.toLowerCase();\n        return (lower === 'license' || lower.startsWith('license.') || lower === 'unlicense' || lower.startsWith('unlicense.'));\n    });\n    if (licenseFile) {\n        const licenseFilepath = path.join(moduleLoc, licenseFile);\n        const licenseFileStats = await fs.stat(licenseFilepath);\n        if (licenseFileStats.isFile()) {\n            const licenseContent = await fs.readFile(licenseFilepath);\n            const inferredLicense = inferLicense(licenseContent);\n            info.licenseText = licenseContent;\n            const license = info.license;\n            if (typeof license === 'string') {\n                if (inferredLicense && isValidLicense(inferredLicense) && !isValidLicense(license)) {\n                    // some packages don't specify their license version but we can infer it based on their license file\n                    const basicLicense = license.toLowerCase().replace(/(-like|\\*)$/g, '');\n                    const expandedLicense = inferredLicense.toLowerCase();\n                    if (expandedLicense.startsWith(basicLicense)) {\n                        // TODO consider doing something to notify the user\n                        info.license = inferredLicense;\n                    }\n                }\n            }\n            else if (inferredLicense) {\n                // if there's no license then infer it based on the license file\n                info.license = inferredLicense;\n            }\n            else {\n                // valid expression to refer to a license in a file\n                info.license = `SEE LICENSE IN ${licenseFile}`;\n            }\n        }\n    }\n    if (typeof info.license === 'string') {\n        // sometimes licenses are known by different names, reduce them\n        info.license = LICENSE_RENAMES[info.license] || info.license;\n    }\n    else if (typeof info.readme === 'string') {\n        // the license might be at the bottom of the README\n        const inferredLicense = inferLicense(info.readme);\n        if (inferredLicense) {\n            info.license = inferredLicense;\n        }\n    }\n    // get notice file\n    const noticeFile = files.find((filename) => {\n        const lower = filename.toLowerCase();\n        return lower === 'notice' || lower.startsWith('notice.');\n    });\n    if (noticeFile) {\n        const noticeFilepath = path.join(moduleLoc, noticeFile);\n        const noticeFileStats = await fs.stat(noticeFilepath);\n        if (noticeFileStats.isFile()) {\n            info.noticeText = await fs.readFile(noticeFilepath);\n        }\n    }\n    for (const dependencyType of MANIFEST_FIELDS) {\n        const dependencyList = info[dependencyType];\n        if (dependencyList && typeof dependencyList === 'object') {\n            delete dependencyList['//'];\n            for (const name in dependencyList) {\n                dependencyList[name] = dependencyList[name] || '';\n            }\n        }\n    }\n});\n"
  },
  {
    "path": "checkpoint/dist-src/util/normalize-manifest/for-publish.js",
    "content": "export async function generatePublishManifest(manifest, config, _dists) {\n    const { name, version, description, keywords, homepage, bugs, bin, license, authors, contributors, man, sideEffects, repository, dependencies, peerDependencies, devDependencies, bundledDependencies, optionalDependencies, engines, enginesStrict, private: priv, publishConfig, } = manifest;\n    const newManifest = {\n        name,\n        description,\n        version,\n        license,\n        bin,\n        files: ['dist-*/', 'bin/'],\n        pika: true,\n        sideEffects: sideEffects || false,\n        keywords,\n        homepage,\n        bugs,\n        authors,\n        contributors,\n        man,\n        repository,\n        dependencies: dependencies || {},\n        peerDependencies,\n        devDependencies,\n        bundledDependencies,\n        optionalDependencies,\n        engines,\n        enginesStrict,\n        private: priv,\n        publishConfig,\n    };\n    const dists = _dists || (await config.getDistributions());\n    for (const [runner, options] of dists) {\n        if (runner.manifest) {\n            await runner.manifest(newManifest, {\n                cwd: config.cwd,\n                isFull: true,\n                manifest,\n                options,\n            });\n        }\n    }\n    newManifest.pika = true;\n    return newManifest;\n}\nexport function generatePrettyManifest(manifest) {\n    return JSON.stringify({\n        ...manifest,\n        dependencies: Object.keys(manifest.dependencies).length === 0 ? {} : '{ ... }',\n    }, null, 2);\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/normalize-manifest/index.js",
    "content": "import validate from './validate.js';\nimport fix from './fix.js';\nimport * as path from 'path';\nexport default (async function (info, moduleLoc, config, isRoot) {\n    // Append dependencies\n    // if (depInfo) {\n    //   info.dependencies = depInfo.main;\n    //   info.devDependencies = depInfo.dev;\n    // }\n    // create human readable name\n    const { name, version } = info;\n    let human;\n    if (typeof name === 'string') {\n        human = name;\n    }\n    if (human && typeof version === 'string' && version) {\n        human += `@${version}`;\n    }\n    if (isRoot && info._loc) {\n        human = path.relative(config.cwd, info._loc);\n    }\n    function warn(msg) {\n        if (human) {\n            msg = `${human}: ${msg}`;\n        }\n        config.reporter.warn(msg);\n    }\n    await fix(info, moduleLoc, config.reporter, warn);\n    try {\n        validate(info, isRoot, config.reporter, warn);\n    }\n    catch (err) {\n        if (human) {\n            err.message = `${human}: ${err.message}`;\n        }\n        throw err;\n    }\n    return info;\n});\n"
  },
  {
    "path": "checkpoint/dist-src/util/normalize-manifest/infer-license.js",
    "content": "import LICENSES from './licenses.js';\nfunction clean(str) {\n    return str.replace(/[^A-Za-z\\s]/g, ' ').replace(/[\\s]+/g, ' ').trim().toLowerCase();\n}\nconst REGEXES = {\n    Apache: [/Apache License\\b/],\n    BSD: [/BSD\\b/],\n    ISC: [/The ISC License/, /ISC\\b/],\n    MIT: [/MIT\\b/],\n    Unlicense: [/http:\\/\\/unlicense.org\\//],\n    WTFPL: [/DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE/, /WTFPL\\b/],\n};\nexport default function inferLicense(license) {\n    // check if we have any explicit licenses\n    const cleanLicense = clean(license);\n    for (const licenseName in LICENSES) {\n        const testLicense = LICENSES[licenseName];\n        if (cleanLicense.search(testLicense) >= 0) {\n            return licenseName;\n        }\n    }\n    // infer based on some keywords\n    for (const licenseName in REGEXES) {\n        for (const regex of REGEXES[licenseName]) {\n            if (license.search(regex) >= 0) {\n                return `${licenseName}*`;\n            }\n        }\n    }\n    return null;\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/normalize-manifest/licenses.js",
    "content": "export default ({\n    'Apache-2.0': new RegExp('(licensed under the apache license version the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license$|apache license version january http www apache org licenses terms and conditions for use reproduction and distribution definitions license shall mean the terms and conditions for use reproduction and distribution as defined by sections through of this document licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the license legal entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity for the purposes of this definition control means i the power direct or indirect to cause the direction or management of such entity whether by contract or otherwise or ii ownership of fifty percent or more of the outstanding shares or iii beneficial ownership of such entity you or your shall mean an individual or legal entity exercising permissions granted by this license source form shall mean the preferred form for making modifications including but not limited to software source code documentation source and configuration files object form shall mean any form resulting from mechanical transformation or translation of a source form including but not limited to compiled object code generated documentation and conversions to other media types work shall mean the work of authorship whether in source or object form made available under the license as indicated by a copyright notice that is included in or attached to the work an example is provided in the appendix below derivative works shall mean any work whether in source or object form that is based on or derived from the work and for which the editorial revisions annotations elaborations or other modifications represent as a whole an original work of authorship for the purposes of this license derivative works shall not include works that remain separable from or merely link or bind by name to the interfaces of the work and derivative works thereof contribution shall mean any work of authorship including the original version of the work and any modifications or additions to that work or derivative works thereof that is intentionally submitted to licensor for inclusion in the work by the copyright owner or by an individual or legal entity authorized to submit on behalf of the copyright owner for the purposes of this definition submitted means any form of electronic verbal or written communication sent to the licensor or its representatives including but not limited to communication on electronic mailing lists source code control systems and issue tracking systems that are managed by or on behalf of the licensor for the purpose of discussing and improving the work but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as not a contribution contributor shall mean licensor and any individual or legal entity on behalf of whom a contribution has been received by licensor and subsequently incorporated within the work grant of copyright license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable copyright license to reproduce prepare derivative works of publicly display publicly perform sublicense and distribute the work and such derivative works in source or object form grant of patent license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable except as stated in this section patent license to make have made use offer to sell sell import and otherwise transfer the work where such license applies only to those patent claims licensable by such contributor that are necessarily infringed by their contribution s alone or by combination of their contribution s with the work to which such contribution s was submitted if you institute patent litigation against any entity including a cross claim or counterclaim in a lawsuit alleging that the work or a contribution incorporated within the work constitutes direct or contributory patent infringement then any patent licenses granted to you under this license for that work shall terminate as of the date such litigation is filed redistribution you may reproduce and distribute copies of the work or derivative works thereof in any medium with or without modifications and in source or object form provided that you meet the following conditions a you must give any other recipients of the work or derivative works a copy of this license and b you must cause any modified files to carry prominent notices stating that you changed the files and c you must retain in the source form of any derivative works that you distribute all copyright patent trademark and attribution notices from the source form of the work excluding those notices that do not pertain to any part of the derivative works and d if the work includes a notice text file as part of its distribution then any derivative works that you distribute must include a readable copy of the attribution notices contained within such notice file excluding those notices that do not pertain to any part of the derivative works in at least one of the following places within a notice text file distributed as part of the derivative works within the source form or documentation if provided along with the derivative works or within a display generated by the derivative works if and wherever such third party notices normally appear the contents of the notice file are for informational purposes only and do not modify the license you may add your own attribution notices within derivative works that you distribute alongside or as an addendum to the notice text from the work provided that such additional attribution notices cannot be construed as modifying the license you may add your own copyright statement to your modifications and may provide additional or different license terms and conditions for use reproduction or distribution of your modifications or for any such derivative works as a whole provided your use reproduction and distribution of the work otherwise complies with the conditions stated in this license submission of contributions unless you explicitly state otherwise any contribution intentionally submitted for inclusion in the work by you to the licensor shall be under the terms and conditions of this license without any additional terms or conditions notwithstanding the above nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with licensor regarding such contributions trademarks this license does not grant permission to use the trade names trademarks service marks or product names of the licensor except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the notice file disclaimer of warranty unless required by applicable law or agreed to in writing licensor provides the work and each contributor provides its contributions on an as is basis without warranties or conditions of any kind either express or implied including without limitation any warranties or conditions of title non infringement merchantability or fitness for a particular purpose you are solely responsible for determining the appropriateness of using or redistributing the work and assume any risks associated with your exercise of permissions under this license limitation of liability in no event and under no legal theory whether in tort including negligence contract or otherwise unless required by applicable law such as deliberate and grossly negligent acts or agreed to in writing shall any contributor be liable to you for damages including any direct indirect special incidental or consequential damages of any character arising as a result of this license or out of the use or inability to use the work including but not limited to damages for loss of goodwill work stoppage computer failure or malfunction or any and all other commercial damages or losses even if such contributor has been advised of the possibility of such damages accepting warranty or additional liability while redistributing the work or derivative works thereof you may choose to offer and charge a fee for acceptance of support warranty indemnity or other liability obligations and or rights consistent with this license however in accepting such obligations you may act only on your own behalf and on your sole responsibility not on behalf of any other contributor and only if you agree to indemnify defend and hold each contributor harmless for any liability incurred by or claims asserted against such contributor by reason of your accepting any such warranty or additional liability end of terms and conditions$)', 'g'),\n    'BSD-2-Clause': new RegExp('(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this(.*?| )is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this(.*?| )even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$)', 'g'),\n    'BSD-3-Clause': new RegExp('(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name of(.*?| )nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution the names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall the copyright holders and contributors be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name(.*?| )nor the names of(.*?| )contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by(.*?| )as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$))', 'g'),\n    MIT: new RegExp('permission is hereby granted free of charge to any person obtaining a copy of this software and associated documentation files the software to deal in the software without restriction including without limitation the rights to use copy modify merge publish distribute sublicense and or sell copies of the software and to permit persons to whom the software is furnished to do so subject to the following conditions the above copyright notice and this permission notice shall be included in all copies or substantial portions of the software the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors or copyright holders be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software$', 'g'),\n    Unlicense: new RegExp('this is free and unencumbered software released into the public domain anyone is free to copy modify publish use compile sell or distribute this software either in source code form or as a compiled binary for any purpose commercial or non commercial and by any means in jurisdictions that recognize copyright laws the author or authors of this software dedicate any and all copyright interest in the software to the public domain we make this dedication for the benefit of the public at large and to the detriment of our heirs and successors we intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software for more information please refer to wildcard$', 'g'),\n});\n"
  },
  {
    "path": "checkpoint/dist-src/util/normalize-manifest/typos.js",
    "content": "export default {\n    autohr: 'author',\n    autor: 'author',\n    contributers: 'contributors',\n    depdenencies: 'dependencies',\n    dependancies: 'dependencies',\n    dependecies: 'dependencies',\n    depends: 'dependencies',\n    'dev-dependencies': 'devDependencies',\n    devDependences: 'devDependencies',\n    devDepenencies: 'devDependencies',\n    devEependencies: 'devDependencies',\n    devdependencies: 'devDependencies',\n    hampage: 'homepage',\n    hompage: 'homepage',\n    prefereGlobal: 'preferGlobal',\n    publicationConfig: 'publishConfig',\n    repo: 'repository',\n    repostitory: 'repository',\n    script: 'scripts',\n};\n"
  },
  {
    "path": "checkpoint/dist-src/util/normalize-manifest/util.js",
    "content": "import validateLicense from 'validate-npm-package-license';\nexport function isValidLicense(license) {\n    return !!license && validateLicense(license).validForNewPackages;\n}\nexport function stringifyPerson(person) {\n    if (!person || typeof person !== 'object') {\n        return person;\n    }\n    const parts = [];\n    if (person.name) {\n        parts.push(person.name);\n    }\n    const email = person.email || person.mail;\n    if (typeof email === 'string') {\n        parts.push(`<${email}>`);\n    }\n    const url = person.url || person.web;\n    if (typeof url === 'string') {\n        parts.push(`(${url})`);\n    }\n    return parts.join(' ');\n}\nexport function parsePerson(person) {\n    if (typeof person !== 'string') {\n        return person;\n    }\n    // format: name (url) <email>\n    const obj = {};\n    let name = person.match(/^([^\\(<]+)/);\n    if (name && name[0].trim()) {\n        obj.name = name[0].trim();\n    }\n    const email = person.match(/<([^>]+)>/);\n    if (email) {\n        obj.email = email[1];\n    }\n    const url = person.match(/\\(([^\\)]+)\\)/);\n    if (url) {\n        obj.url = url[1];\n    }\n    return obj;\n}\nexport function normalizePerson(person) {\n    return parsePerson(stringifyPerson(person));\n}\nexport function extractDescription(readme) {\n    if (typeof readme !== 'string' || readme === '') {\n        return undefined;\n    }\n    // split into lines\n    const lines = readme.trim().split('\\n').map((line) => line.trim());\n    // find the start of the first paragraph, ignore headings\n    let start = 0;\n    for (; start < lines.length; start++) {\n        const line = lines[start];\n        if (line && line.match(/^(#|$)/)) {\n            // line isn't empty and isn't a heading so this is the start of a paragraph\n            start++;\n            break;\n        }\n    }\n    // skip newlines from the header to the first line\n    while (start < lines.length && !lines[start]) {\n        start++;\n    }\n    // continue to the first non empty line\n    let end = start;\n    while (end < lines.length && lines[end]) {\n        end++;\n    }\n    return lines.slice(start, end).join(' ');\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/normalize-manifest/validate.js",
    "content": "import { MessageError } from '@pika/types';\nimport typos from './typos.js';\nimport isBuiltinModule from 'is-builtin-module';\nconst strings = ['name', 'version'];\nconst dependencyKeys = [\n    // npm registry will include optionalDependencies in dependencies and we'll want to dedupe them from the\n    // other fields first\n    'optionalDependencies',\n    // it's seemingly common to include a dependency in dependencies and devDependencies of the same name but\n    // different ranges, this can cause a lot of issues with our determinism and the behaviour of npm is\n    // currently unspecified.\n    'dependencies',\n    'devDependencies',\n];\nfunction isValidName(name) {\n    return !name.match(/[\\/@\\s\\+%:]/) && encodeURIComponent(name) === name;\n}\nfunction isValidScopedName(name) {\n    if (name[0] !== '@') {\n        return false;\n    }\n    const parts = name.slice(1).split('/');\n    return parts.length === 2 && isValidName(parts[0]) && isValidName(parts[1]);\n}\nexport function isValidPackageName(name) {\n    return isValidName(name) || isValidScopedName(name);\n}\nexport default function (info, isRoot, reporter, warn) {\n    if (isRoot) {\n        for (const key in typos) {\n            if (key in info) {\n                warn(reporter.lang('manifestPotentialTypo', key, typos[key]));\n            }\n        }\n    }\n    // validate name\n    const { name } = info;\n    if (typeof name === 'string') {\n        if (isRoot && isBuiltinModule(name)) {\n            warn(reporter.lang('manifestBuiltinModule', name));\n        }\n        // cannot start with a dot\n        if (name[0] === '.') {\n            throw new MessageError(reporter.lang('manifestNameDot'));\n        }\n        // cannot contain the following characters\n        if (!isValidPackageName(name)) {\n            throw new MessageError(reporter.lang('manifestNameIllegalChars'));\n        }\n        // cannot equal node_modules or favicon.ico\n        const lower = name.toLowerCase();\n        if (lower === 'node_modules' || lower === 'favicon.ico') {\n            throw new MessageError(reporter.lang('manifestNameBlacklisted'));\n        }\n    }\n    // Only care if you are trying to publish to npm.\n    // // validate license\n    // if (isRoot && !info.private) {\n    //   if (typeof info.license === 'string') {\n    //     const license = info.license.replace(/\\*$/g, '');\n    //     if (!isValidLicense(license)) {\n    //       warn(reporter.lang('manifestLicenseInvalid'));\n    //     }\n    //   } else {\n    //     warn(reporter.lang('manifestLicenseNone'));\n    //   }\n    // }\n    // validate strings\n    for (const key of strings) {\n        const val = info[key];\n        if (val && typeof val !== 'string') {\n            throw new MessageError(reporter.lang('manifestStringExpected', key));\n        }\n    }\n    cleanDependencies(info, isRoot, reporter, warn);\n}\nexport function cleanDependencies(info, isRoot, reporter, warn) {\n    // get dependency objects\n    const depTypes = [];\n    for (const type of dependencyKeys) {\n        const deps = info[type];\n        if (!deps || typeof deps !== 'object') {\n            continue;\n        }\n        depTypes.push([type, deps]);\n    }\n    // aggregate all non-trivial deps (not '' or '*')\n    const nonTrivialDeps = new Map();\n    for (const [type, deps] of depTypes) {\n        for (const name of Object.keys(deps)) {\n            const version = deps[name];\n            if (!nonTrivialDeps.has(name) && version && version !== '*') {\n                nonTrivialDeps.set(name, { type, version });\n            }\n        }\n    }\n    // overwrite first dep of package with non-trivial version, remove the rest\n    const setDeps = new Set();\n    for (const [type, deps] of depTypes) {\n        for (const name of Object.keys(deps)) {\n            let version = deps[name];\n            const dep = nonTrivialDeps.get(name);\n            if (dep) {\n                if (version && version !== '*' && version !== dep.version && isRoot) {\n                    // only throw a warning when at the root\n                    warn(reporter.lang('manifestDependencyCollision', dep.type, name, dep.version, type, version));\n                }\n                version = dep.version;\n            }\n            if (setDeps.has(name)) {\n                delete deps[name];\n            }\n            else {\n                deps[name] = version;\n                setDeps.add(name);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/promise.js",
    "content": "export function wait(delay) {\n    return new Promise(resolve => {\n        setTimeout(resolve, delay);\n    });\n}\nexport function promisify(fn, firstData) {\n    return function (...args) {\n        return new Promise(function (resolve, reject) {\n            args.push(function (err, ...result) {\n                let res = result;\n                if (result.length <= 1) {\n                    res = result[0];\n                }\n                if (firstData) {\n                    res = err;\n                    err = null;\n                }\n                if (err) {\n                    reject(err);\n                }\n                else {\n                    resolve(res);\n                }\n            });\n            fn.apply(null, args);\n        });\n    };\n}\nexport function queue(arr, promiseProducer, concurrency = Infinity) {\n    concurrency = Math.min(concurrency, arr.length);\n    // clone\n    arr = arr.slice();\n    const results = [];\n    let total = arr.length;\n    if (!total) {\n        return Promise.resolve(results);\n    }\n    return new Promise((resolve, reject) => {\n        for (let i = 0; i < concurrency; i++) {\n            next();\n        }\n        function next() {\n            const item = arr.shift();\n            const promise = promiseProducer(item);\n            promise.then(function (result) {\n                results.push(result);\n                total--;\n                if (total === 0) {\n                    resolve(results);\n                }\n                else {\n                    if (arr.length) {\n                        next();\n                    }\n                }\n            }, reject);\n        }\n    });\n}\n"
  },
  {
    "path": "checkpoint/dist-src/util/signal-handler.js",
    "content": "import { forwardSignalToSpawnedProcesses } from './child.js';\nfunction forwardSignalAndExit(signal) {\n    forwardSignalToSpawnedProcesses(signal);\n    // We want to exit immediately here since `SIGTERM` means that\n    // If we lose stdout messages due to abrupt exit, shoot the messenger?\n    process.exit(1); // eslint-disable-line no-process-exit\n}\nexport default function handleSignals() {\n    process.on('SIGTERM', () => {\n        forwardSignalAndExit('SIGTERM');\n    });\n}\n"
  },
  {
    "path": "checkpoint/dist-types/commands/build.d.ts",
    "content": "import Config, { BuildFlags } from '../config.js';\nimport { Reporter } from '../reporters/index.js';\nexport declare function hasWrapper(): boolean;\nexport declare const examples: any;\nexport declare class Build {\n    constructor(flags: BuildFlags, config: Config, reporter: Reporter);\n    out: string;\n    flags: BuildFlags;\n    config: Config;\n    reporter: Reporter;\n    totalNum: number;\n    cleanup(): Promise<void>;\n    init(isFull?: boolean): Promise<void>;\n}\nexport declare function run(config: Config, reporter: Reporter, flags: BuildFlags, args: Array<string>): Promise<void>;\n"
  },
  {
    "path": "checkpoint/dist-types/config.d.ts",
    "content": "import { Manifest } from './types.js';\nimport BaseReporter from './reporters/base-reporter.js';\nexport interface BuildFlags {\n    publish?: boolean;\n    out?: string;\n    silent?: boolean;\n    force?: boolean;\n}\nexport interface GlobalFlags extends BuildFlags {\n    cwd?: string;\n    pipeline?: string;\n    verbose?: boolean;\n    json?: boolean;\n}\nexport default class Config {\n    cwd: string;\n    reporter: BaseReporter;\n    _manifest: any;\n    manifest: Manifest;\n    flags: GlobalFlags;\n    constructor(reporter: BaseReporter, cwd: string, flags: GlobalFlags);\n    loadPackageManifest(): Promise<Manifest>;\n    readJson(loc: string, factory?: (filename: string) => Promise<any>): Promise<any>;\n    getDistributions(): Promise<[any, any][]>;\n}\n"
  },
  {
    "path": "checkpoint/dist-types/constants.d.ts",
    "content": "/// <reference types=\"node\" />\nexport declare const DEPENDENCY_TYPES: string[];\nexport declare const RESOLUTIONS = \"resolutions\";\nexport declare const MANIFEST_FIELDS: string[];\nexport declare const SUPPORTED_NODE_VERSIONS = \">=8.5.0\";\nexport declare const CHILD_CONCURRENCY = 5;\nexport declare const NODE_MODULES_FOLDER = \"node_modules\";\nexport declare const NODE_PACKAGE_JSON = \"package.json\";\nexport declare const DEFAULT_INDENT = \"  \";\nexport declare const ENV_PATH_KEY: string;\nexport declare function getPathKey(platform: string, env: NodeJS.ProcessEnv): string;\n"
  },
  {
    "path": "checkpoint/dist-types/errors.d.ts",
    "content": "import { MessageError } from '@pika/types';\nexport declare class ProcessSpawnError extends MessageError {\n    constructor(msg: string, code?: string, process?: string);\n    code?: string;\n    process?: string;\n}\nexport declare class SecurityError extends MessageError {\n}\nexport declare class ProcessTermError extends MessageError {\n    EXIT_CODE?: number;\n    EXIT_SIGNAL?: string;\n}\nexport declare class ResponseError extends Error {\n    constructor(msg: string, responseCode: number);\n    responseCode: number;\n}\nexport declare class OneTimePasswordError extends Error {\n}\n"
  },
  {
    "path": "checkpoint/dist-types/index.d.ts",
    "content": "export declare function cli(args: string[]): Promise<void>;\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/base-reporter.d.ts",
    "content": "/// <reference types=\"node\" />\nimport { ReporterSpinnerSet, Trees, Stdout, Stdin, Package, ReporterSpinner } from './types';\nimport { LanguageKeys } from './lang/en.js';\nimport { Formatter } from './format.js';\nimport * as languages from './lang/index.js';\ndeclare type Language = keyof typeof languages;\nexport declare type ReporterOptions = {\n    verbose?: boolean;\n    language?: Language;\n    stdout?: Stdout;\n    stderr?: Stdout;\n    stdin?: Stdin;\n    emoji?: boolean;\n    noProgress?: boolean;\n    silent?: boolean;\n    isSilent?: boolean;\n    nonInteractive?: boolean;\n};\nexport declare function stringifyLangArgs(args: Array<any>): Array<string>;\nexport default class BaseReporter {\n    constructor(opts?: ReporterOptions);\n    formatter: Formatter;\n    language: Language;\n    stdout: Stdout;\n    stderr: Stdout;\n    stdin: Stdin;\n    isTTY: boolean;\n    emoji: boolean;\n    noProgress: boolean;\n    isVerbose: boolean;\n    isSilent: boolean;\n    nonInteractive: boolean;\n    format: Formatter;\n    peakMemoryInterval?: NodeJS.Timer;\n    peakMemory: number;\n    startTime: number;\n    lang(key: LanguageKeys, ...args: Array<any>): string;\n    /**\n     * `stringifyLangArgs` run `JSON.stringify` on strings too causing\n     * them to appear quoted. This marks them as \"raw\" and prevents\n     * the quoting and escaping\n     */\n    rawText(str: string): {\n        inspect(): string;\n    };\n    verbose(msg: string): void;\n    verboseInspect(val: any): void;\n    _verbose(msg: string): void;\n    _verboseInspect(val: any): void;\n    _getStandardInput(): Stdin;\n    initPeakMemoryCounter(): void;\n    checkPeakMemory(): void;\n    close(): void;\n    getTotalTime(): number;\n    list(key: string, items: Array<string>, hints?: Object): void;\n    tree(key: string, obj: Trees, { force }?: {\n        force?: boolean;\n    }): void;\n    step(current: number, total: number, message: string, emoji?: string): void;\n    error(message: string): void;\n    info(message: string): void;\n    warn(message: string): void;\n    success(message: string): void;\n    log(message: string, { force }?: {\n        force?: boolean;\n    }): void;\n    command(command: string): void;\n    inspect(value: any): void;\n    header(pkg: Package): void;\n    footer(showPeakMemory: boolean): void;\n    table(head: Array<string>, body: Array<Array<string>>): void;\n    activity(): ReporterSpinner;\n    activitySet(total: number, workers: number): ReporterSpinnerSet;\n    progress(total: number): () => void;\n    disableProgress(): void;\n}\nexport {};\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/console/console-reporter.d.ts",
    "content": "import BaseReporter, { ReporterOptions } from '../base-reporter.js';\nimport { FormatKeys } from '../format.js';\nimport { Package, ReporterSpinner, ReporterSpinnerSet, Trees } from '../types.js';\nimport Progress from './progress-bar.js';\nimport Spinner from './spinner-progress.js';\ndeclare type Row = Array<string>;\nexport default class ConsoleReporter extends BaseReporter {\n    _lastCategorySize: number;\n    _progressBar?: Progress;\n    _spinners: Set<Spinner>;\n    constructor(opts: ReporterOptions);\n    _prependEmoji(msg: string, emoji?: string): string;\n    _logCategory(category: string, color: FormatKeys, msg: string): void;\n    _verbose(msg: string): void;\n    _verboseInspect(obj: any): void;\n    close(): void;\n    table(head: Array<string>, body: Array<Row>): void;\n    step(current: number, total: number, msg: string, emoji?: string): void;\n    inspect(value: any): void;\n    list(key: string, items: Array<string>, hints?: Object): void;\n    header(pkg: Package): void;\n    footer(showPeakMemory?: boolean): void;\n    log(msg: string, { force }?: {\n        force?: boolean;\n    }): void;\n    _log(msg: string, { force }?: {\n        force?: boolean;\n    }): void;\n    success(msg: string): void;\n    error(msg: string): void;\n    info(msg: string): void;\n    command(command: string): void;\n    warn(msg: string): void;\n    tree(key: string, trees: Trees, { force }?: {\n        force?: boolean;\n    }): void;\n    activitySet(total: number, workers: number): ReporterSpinnerSet;\n    activity(): ReporterSpinner;\n    progress(count: number): () => void;\n    stopProgress(): void;\n}\nexport {};\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/console/helpers/tree-helper.d.ts",
    "content": "import { Trees } from '../../types.js';\nexport declare type FormattedOutput = {\n    prefix: string;\n    hint: any;\n    color: string;\n    name: string;\n    formatter: any;\n};\nexport declare function sortTrees(trees: Trees): Trees;\nexport declare function recurseTree(tree: Trees, prefix: string, recurseFunc: Function): void;\nexport declare function getFormattedOutput(fmt: FormattedOutput): string;\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/console/progress-bar.d.ts",
    "content": "/// <reference types=\"node\" />\nimport { Stdout } from '../types.js';\nexport default class ProgressBar {\n    constructor(total: number, stdout?: Stdout, callback?: (progressBar: ProgressBar) => void);\n    stdout: Stdout;\n    curr: number;\n    total: number;\n    width: number;\n    chars: [string, string];\n    delay: number;\n    id?: NodeJS.Timeout;\n    _callback?: (progressBar: ProgressBar) => void;\n    static bars: [string, string][];\n    tick(): void;\n    cancelTick(): void;\n    stop(): void;\n    render(): void;\n}\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/console/spinner-progress.d.ts",
    "content": "/// <reference types=\"node\" />\nimport { Stdout } from '../types.js';\nexport default class Spinner {\n    constructor(stdout?: Stdout, lineNumber?: number);\n    stdout: Stdout;\n    prefix: string;\n    current: number;\n    lineNumber: number;\n    delay: number;\n    chars: Array<string>;\n    text: string;\n    id?: NodeJS.Timeout;\n    static spinners: Array<string>;\n    setPrefix(prefix: string): void;\n    setText(text: string): void;\n    start(): void;\n    render(): void;\n    stop(): void;\n}\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/console/util.d.ts",
    "content": "import { Stdout } from '../types.js';\nexport declare function clearLine(stdout: Stdout): void;\nexport declare function toStartOfLine(stdout: Stdout): void;\nexport declare function writeOnNthLine(stdout: Stdout, n: number, msg: string): void;\nexport declare function clearNthLine(stdout: Stdout, n: number): void;\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/format.d.ts",
    "content": "declare function formatFunction(...strs: Array<string>): string;\nexport declare const defaultFormatter: {\n    bold: typeof formatFunction;\n    dim: typeof formatFunction;\n    italic: typeof formatFunction;\n    underline: typeof formatFunction;\n    inverse: typeof formatFunction;\n    strikethrough: typeof formatFunction;\n    black: typeof formatFunction;\n    red: typeof formatFunction;\n    green: typeof formatFunction;\n    yellow: typeof formatFunction;\n    blue: typeof formatFunction;\n    magenta: typeof formatFunction;\n    cyan: typeof formatFunction;\n    white: typeof formatFunction;\n    gray: typeof formatFunction;\n    grey: typeof formatFunction;\n    stripColor: typeof formatFunction;\n};\ndeclare type FormatFunction = (...strs: Array<string>) => string;\nexport declare type FormatKeys = keyof typeof defaultFormatter;\nexport declare type Formatter = {\n    bold: FormatFunction;\n    dim: FormatFunction;\n    italic: FormatFunction;\n    underline: FormatFunction;\n    inverse: FormatFunction;\n    strikethrough: FormatFunction;\n    black: FormatFunction;\n    red: FormatFunction;\n    green: FormatFunction;\n    yellow: FormatFunction;\n    blue: FormatFunction;\n    magenta: FormatFunction;\n    cyan: FormatFunction;\n    white: FormatFunction;\n    gray: FormatFunction;\n    grey: FormatFunction;\n    stripColor: FormatFunction;\n};\nexport {};\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/index.d.ts",
    "content": "export { default as ConsoleReporter } from './console/console-reporter';\nexport { default as JSONReporter } from './json-reporter';\nexport { default as NoopReporter } from './noop-reporter';\nexport { default as Reporter } from './base-reporter';\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/json-reporter.d.ts",
    "content": "import { ReporterSpinnerSet, Trees, ReporterSpinner } from './types.js';\nimport BaseReporter from './base-reporter.js';\nexport default class JSONReporter extends BaseReporter {\n    constructor(opts?: Object);\n    _activityId: number;\n    _progressId: number;\n    _dump(type: string, data: any, error?: boolean): void;\n    _verbose(msg: string): void;\n    list(type: string, items: Array<string>, hints?: Object): void;\n    tree(type: string, trees: Trees): void;\n    step(current: number, total: number, message: string): void;\n    inspect(value: any): void;\n    footer(showPeakMemory: boolean): void;\n    log(msg: string): void;\n    command(msg: string): void;\n    table(head: Array<string>, body: Array<Array<string>>): void;\n    success(msg: string): void;\n    error(msg: string): void;\n    warn(msg: string): void;\n    info(msg: string): void;\n    activitySet(total: number, workers: number): ReporterSpinnerSet;\n    activity(): ReporterSpinner;\n    _activity(data: Object): ReporterSpinner;\n    progress(total: number): () => void;\n}\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/lang/en.d.ts",
    "content": "declare const messages: {\n    upToDate: string;\n    folderInSync: string;\n    nothingToInstall: string;\n    resolvingPackages: string;\n    checkingManifest: string;\n    fetchingPackages: string;\n    linkingDependencies: string;\n    rebuildingPackages: string;\n    buildingFreshPackages: string;\n    cleaningModules: string;\n    bumpingVersion: string;\n    savingHar: string;\n    answer: string;\n    usage: string;\n    installCommandRenamed: string;\n    globalFlagRemoved: string;\n    waitingInstance: string;\n    waitingNamedInstance: string;\n    offlineRetrying: string;\n    internalServerErrorRetrying: string;\n    clearedCache: string;\n    couldntClearPackageFromCache: string;\n    clearedPackageFromCache: string;\n    packWroteTarball: string;\n    helpExamples: string;\n    helpCommands: string;\n    helpCommandsMore: string;\n    helpLearnMore: string;\n    manifestPotentialTypo: string;\n    manifestBuiltinModule: string;\n    manifestNameDot: string;\n    manifestNameIllegalChars: string;\n    manifestNameBlacklisted: string;\n    manifestLicenseInvalid: string;\n    manifestLicenseNone: string;\n    manifestStringExpected: string;\n    manifestDependencyCollision: string;\n    manifestDirectoryNotFound: string;\n    verboseFileCopy: string;\n    verboseFileLink: string;\n    verboseFileSymlink: string;\n    verboseFileSkip: string;\n    verboseFileSkipSymlink: string;\n    verboseFileSkipHardlink: string;\n    verboseFileRemoveExtraneous: string;\n    verboseFilePhantomExtraneous: string;\n    verboseFileSkipArtifact: string;\n    verboseFileFolder: string;\n    verboseRequestStart: string;\n    verboseRequestFinish: string;\n    configSet: string;\n    configDelete: string;\n    configNpm: string;\n    configPika: string;\n    couldntFindPackagejson: string;\n    couldntFindMatch: string;\n    couldntFindPackageInCache: string;\n    couldntFindVersionThatMatchesRange: string;\n    chooseVersionFromList: string;\n    moduleNotInManifest: string;\n    moduleAlreadyInManifest: string;\n    unknownFolderOrTarball: string;\n    unknownPackage: string;\n    unknownPackageName: string;\n    unknownUser: string;\n    unknownRegistryResolver: string;\n    userNotAnOwner: string;\n    invalidVersionArgument: string;\n    invalidVersion: string;\n    requiredVersionInRange: string;\n    packageNotFoundRegistry: string;\n    requiredPackageNotFoundRegistry: string;\n    doesntExist: string;\n    missingRequiredPackageKey: string;\n    invalidAccess: string;\n    invalidCommand: string;\n    invalidGistFragment: string;\n    invalidHostedGitFragment: string;\n    invalidFragment: string;\n    invalidPackageName: string;\n    invalidPackageVersion: string;\n    couldntFindManifestIn: string;\n    shrinkwrapWarning: string;\n    npmLockfileWarning: string;\n    lockfileOutdated: string;\n    lockfileMerged: string;\n    lockfileConflict: string;\n    ignoredScripts: string;\n    missingAddDependencies: string;\n    yesWarning: string;\n    networkWarning: string;\n    flatGlobalError: string;\n    noName: string;\n    noVersion: string;\n    answerRequired: string;\n    missingWhyDependency: string;\n    bugReport: string;\n    unexpectedError: string;\n    jsonError: string;\n    noPermission: string;\n    noGlobalFolder: string;\n    allDependenciesUpToDate: string;\n    legendColorsForVersionUpdates: string;\n    frozenLockfileError: string;\n    fileWriteError: string;\n    fileDeleteError: string;\n    multiplePackagesCantUnpackInSameDestination: string;\n    incorrectLockfileEntry: string;\n    invalidResolutionName: string;\n    invalidResolutionVersion: string;\n    incompatibleResolutionVersion: string;\n    pikaOutdated: string;\n    pikaOutdatedInstaller: string;\n    pikaOutdatedCommand: string;\n    tooManyArguments: string;\n    tooFewArguments: string;\n    noArguments: string;\n    ownerRemoving: string;\n    ownerRemoved: string;\n    ownerRemoveError: string;\n    ownerGetting: string;\n    ownerGettingFailed: string;\n    ownerAlready: string;\n    ownerAdded: string;\n    ownerAdding: string;\n    ownerAddingFailed: string;\n    ownerNone: string;\n    teamCreating: string;\n    teamRemoving: string;\n    teamAddingUser: string;\n    teamRemovingUser: string;\n    teamListing: string;\n    distFailed: string;\n    distExiting: string;\n    distContinuing: string;\n    cleaning: string;\n    cleanCreatingFile: string;\n    cleanCreatedFile: string;\n    cleanAlreadyExists: string;\n    cleanRequiresForce: string;\n    cleanDoesNotExist: string;\n    binLinkCollision: string;\n    linkCollision: string;\n    linkMissing: string;\n    linkRegistered: string;\n    linkRegisteredMessage: string;\n    linkUnregistered: string;\n    linkUnregisteredMessage: string;\n    linkUsing: string;\n    linkDisusing: string;\n    linkDisusingMessage: string;\n    linkTargetMissing: string;\n    createInvalidBin: string;\n    createMissingPackage: string;\n    workspacesAddRootCheck: string;\n    workspacesRemoveRootCheck: string;\n    workspacesFocusRootCheck: string;\n    workspacesRequirePrivateProjects: string;\n    workspacesSettingMustBeArray: string;\n    workspacesDisabled: string;\n    workspacesNohoistRequirePrivatePackages: string;\n    workspacesNohoistDisabled: string;\n    workspaceRootNotFound: string;\n    workspaceMissingWorkspace: string;\n    workspaceMissingCommand: string;\n    workspaceUnknownWorkspace: string;\n    workspaceVersionMandatory: string;\n    workspaceNameMandatory: string;\n    workspaceNameDuplicate: string;\n    cacheFolderSkipped: string;\n    cacheFolderMissing: string;\n    cacheFolderSelected: string;\n    execMissingCommand: string;\n    noScriptsAvailable: string;\n    noBinAvailable: string;\n    dashDashDeprecation: string;\n    commandNotSpecified: string;\n    binCommands: string;\n    possibleCommands: string;\n    commandQuestion: string;\n    commandFailedWithCode: string;\n    commandFailedWithSignal: string;\n    packageRequiresNodeGyp: string;\n    nodeGypAutoInstallFailed: string;\n    foundIncompatible: string;\n    incompatibleEngine: string;\n    incompatibleCPU: string;\n    incompatibleOS: string;\n    invalidEngine: string;\n    optionalCompatibilityExcluded: string;\n    optionalModuleFail: string;\n    optionalModuleScriptFail: string;\n    optionalModuleCleanupFail: string;\n    unmetPeer: string;\n    incorrectPeer: string;\n    selectedPeer: string;\n    missingBundledDependency: string;\n    savedNewDependency: string;\n    savedNewDependencies: string;\n    directDependencies: string;\n    allDependencies: string;\n    foundWarnings: string;\n    foundErrors: string;\n    savedLockfile: string;\n    noRequiredLockfile: string;\n    noLockfileFound: string;\n    invalidSemver: string;\n    newVersion: string;\n    currentVersion: string;\n    noVersionOnPublish: string;\n    manualVersionResolution: string;\n    manualVersionResolutionOption: string;\n    createdTag: string;\n    createdTagFail: string;\n    deletedTag: string;\n    deletedTagFail: string;\n    gettingTags: string;\n    deletingTags: string;\n    creatingTag: string;\n    whyStart: string;\n    whyFinding: string;\n    whyCalculating: string;\n    whyUnknownMatch: string;\n    whyInitGraph: string;\n    whyWhoKnows: string;\n    whyDiskSizeWithout: string;\n    whyDiskSizeUnique: string;\n    whyDiskSizeTransitive: string;\n    whySharedDependencies: string;\n    whyHoistedTo: string;\n    whyHoistedFromSimple: string;\n    whyNotHoistedSimple: string;\n    whyDependedOnSimple: string;\n    whySpecifiedSimple: string;\n    whyReasons: string;\n    whyHoistedFrom: string;\n    whyNotHoisted: string;\n    whyDependedOn: string;\n    whySpecified: string;\n    whyMatch: string;\n    uninstalledPackages: string;\n    uninstallRegenerate: string;\n    cleanRemovedFiles: string;\n    cleanSavedSize: string;\n    configFileFound: string;\n    configPossibleFile: string;\n    npmUsername: string;\n    npmPassword: string;\n    npmEmail: string;\n    npmOneTimePassword: string;\n    loggingIn: string;\n    loggedIn: string;\n    notRevokingEnvToken: string;\n    notRevokingConfigToken: string;\n    noTokenToRevoke: string;\n    revokingToken: string;\n    revokedToken: string;\n    loginAsPublic: string;\n    incorrectCredentials: string;\n    incorrectOneTimePassword: string;\n    twoFactorAuthenticationEnabled: string;\n    clearedCredentials: string;\n    publishFail: string;\n    publishPrivate: string;\n    published: string;\n    publishing: string;\n    nonInteractiveNoVersionSpecified: string;\n    nonInteractiveNoToken: string;\n    infoFail: string;\n    malformedRegistryResponse: string;\n    registryNoVersions: string;\n    cantRequestOffline: string;\n    requestManagerNotSetupHAR: string;\n    requestError: string;\n    requestFailed: string;\n    tarballNotInNetworkOrCache: string;\n    fetchBadHashWithPath: string;\n    fetchBadIntegrityAlgorithm: string;\n    fetchErrorCorrupt: string;\n    errorExtractingTarball: string;\n    updateInstalling: string;\n    hostedGitResolveError: string;\n    unknownFetcherFor: string;\n    downloadGitWithoutCommit: string;\n    downloadHTTPWithoutCommit: string;\n    unplugDisabled: string;\n    plugnplayWindowsSupport: string;\n    packageInstalledWithBinaries: string;\n    packageHasBinaries: string;\n    packageHasNoBinaries: string;\n    packageBinaryNotFound: string;\n    couldBeDeduped: string;\n    lockfileNotContainPattern: string;\n    integrityCheckFailed: string;\n    noIntegrityFile: string;\n    integrityFailedExpectedIsNotAJSON: string;\n    integrityCheckLinkedModulesDontMatch: string;\n    integrityFlagsDontMatch: string;\n    integrityLockfilesDontMatch: string;\n    integrityFailedFilesMissing: string;\n    integrityPatternsDontMatch: string;\n    integrityModulesFoldersMissing: string;\n    integritySystemParamsDontMatch: string;\n    packageNotInstalled: string;\n    optionalDepNotInstalled: string;\n    packageWrongVersion: string;\n    packageDontSatisfy: string;\n    lockfileExists: string;\n    pikaManifestExists: string;\n    noManifestExists: string;\n    skippingImport: string;\n    importFailed: string;\n    importResolveFailed: string;\n    importResolvedRangeMatch: string;\n    importSourceFilesCorrupted: string;\n    importPackageLock: string;\n    importYarnLock: string;\n    importNodeModules: string;\n    packageContainsPikaAsGlobal: string;\n    watchStarting: string;\n    watchRunning: string;\n    watchRebuild: string;\n    watchError: string;\n    noValidationErrors: string;\n    validationErrors: string;\n    scopeNotValid: string;\n    deprecatedCommand: string;\n    deprecatedListArgs: string;\n    implicitFileDeprecated: string;\n    unsupportedNodeVersion: string;\n    verboseUpgradeBecauseRequested: string;\n    verboseUpgradeBecauseOutdated: string;\n    verboseUpgradeNotUnlocking: string;\n    verboseUpgradeUnlocking: string;\n    folderMissing: string;\n    mutexPortBusy: string;\n    auditRunning: string;\n    auditSummary: string;\n    auditSummarySeverity: string;\n    auditCritical: string;\n    auditHigh: string;\n    auditModerate: string;\n    auditLow: string;\n    auditInfo: string;\n    auditResolveCommand: string;\n    auditSemverMajorChange: string;\n    auditManualReview: string;\n    auditRunAuditForDetails: string;\n    auditOffline: string;\n};\nexport declare type LanguageKeys = keyof typeof messages;\nexport default messages;\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/lang/index.d.ts",
    "content": "import en from './en.js';\nexport { en };\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/noop-reporter.d.ts",
    "content": "import BaseReporter from './base-reporter.js';\nimport { LanguageKeys } from './lang/en.js';\nimport { Package, ReporterSpinner, ReporterSpinnerSet, Trees } from './types.js';\nexport default class NoopReporter extends BaseReporter {\n    lang(key: LanguageKeys, ...args: Array<any>): string;\n    verbose(msg: string): void;\n    verboseInspect(val: any): void;\n    initPeakMemoryCounter(): void;\n    checkPeakMemory(): void;\n    close(): void;\n    getTotalTime(): number;\n    list(key: string, items: Array<string>, hints?: Object): void;\n    tree(key: string, obj: Trees): void;\n    step(current: number, total: number, message: string, emoji?: string): void;\n    error(message: string): void;\n    info(message: string): void;\n    warn(message: string): void;\n    success(message: string): void;\n    log(message: string): void;\n    command(command: string): void;\n    inspect(value: any): void;\n    header(pkg: Package): void;\n    footer(showPeakMemory: boolean): void;\n    table(head: Array<string>, body: Array<Array<string>>): void;\n    activity(): ReporterSpinner;\n    activitySet(total: number, workers: number): ReporterSpinnerSet;\n    progress(total: number): () => void;\n    disableProgress(): void;\n}\n"
  },
  {
    "path": "checkpoint/dist-types/reporters/types.d.ts",
    "content": "/// <reference types=\"node\" />\nimport { Writable, Readable } from 'stream';\nimport { WriteStream, ReadStream } from 'fs';\nexport declare type Stdout = Writable | WriteStream;\nexport declare type Stdin = Readable | ReadStream;\nexport declare type Package = {\n    name: string;\n    version: string;\n};\nexport declare type Tree = {\n    name: string;\n    children?: Trees;\n    hint?: string;\n    hidden?: boolean;\n    color?: string;\n};\nexport declare type Trees = Array<Tree>;\nexport declare type ReporterSpinner = {\n    tick: (name: string) => void;\n    end: () => void;\n};\nexport declare type ReporterSpinnerSet = {\n    spinners: Array<ReporterSetSpinner>;\n    end: () => void;\n};\nexport declare type ReporterSetSpinner = {\n    clear: () => void;\n    setPrefix: (current: number, prefix: string) => void;\n    tick: (msg: string) => void;\n    end: () => void;\n};\n"
  },
  {
    "path": "checkpoint/dist-types/types.d.ts",
    "content": "import { Reporter } from './reporters/index.js';\nimport Config from './config.js';\nexport declare type CLIFunction = (config: Config, reporter: Reporter, flags: Object, args: Array<string>) => CLIFunctionReturn;\ndeclare type _CLIFunctionReturn = boolean;\nexport declare type CLIFunctionReturn = _CLIFunctionReturn | Promise<_CLIFunctionReturn>;\nexport declare type PersonObject = {\n    email?: string;\n    name?: string;\n    url?: string;\n};\ndeclare type Dependencies = {\n    [key: string]: string;\n};\nexport declare type Manifest = {\n    name: string;\n    version: string;\n    description?: string;\n    keywords?: string[];\n    sideEffects?: boolean;\n    private?: boolean;\n    distributions?: any;\n    author?: {\n        name?: string;\n        email?: string;\n        url?: string;\n    };\n    homepage?: string;\n    flat?: boolean;\n    license?: string;\n    licenseText?: string;\n    noticeText?: string;\n    readme?: string;\n    readmeFilename?: string;\n    repository?: {\n        type: 'git';\n        url: string;\n    };\n    bugs?: {\n        url: string;\n    };\n    dist?: {\n        tarball: string;\n        shasum: string;\n    };\n    directories?: {\n        man: string;\n        bin: string;\n    };\n    man?: Array<string>;\n    bin?: {\n        [name: string]: string;\n    };\n    scripts?: {\n        [name: string]: string;\n    };\n    engines?: {\n        [engineName: string]: string;\n    };\n    os?: Array<string>;\n    cpu?: Array<string>;\n    dependencies?: Dependencies;\n    devDependencies?: Dependencies;\n    peerDependencies?: Dependencies;\n    optionalDependencies?: Dependencies;\n    bundleDependencies?: Array<string>;\n    bundledDependencies?: Array<string>;\n    installConfig?: {\n        pnp?: boolean;\n    };\n    deprecated?: string;\n    files?: Array<string>;\n    main?: string;\n    fresh?: boolean;\n    prebuiltVariants?: {\n        [filename: string]: string;\n    };\n};\nexport declare type Dependency = {\n    name: string;\n    current: string;\n    wanted: string;\n    latest: string;\n    url: string;\n    hint?: string;\n    range: string;\n    upgradeTo: string;\n    workspaceName: string;\n    workspaceLoc: string;\n};\nexport {};\n"
  },
  {
    "path": "checkpoint/dist-types/util/babel-plugin-import-rewrite.d.ts",
    "content": "export default function transform({ template, types: t }: {\n    template: any;\n    types: any;\n}): any;\n"
  },
  {
    "path": "checkpoint/dist-types/util/babel-validate-specifier.d.ts",
    "content": "export declare function validateDynamicImportArguments(path: any): Set<string>;\n"
  },
  {
    "path": "checkpoint/dist-types/util/blocking-queue.d.ts",
    "content": "/// <reference types=\"node\" />\nexport default class BlockingQueue {\n    constructor(alias: string, maxConcurrency?: number);\n    concurrencyQueue: Array<() => void>;\n    warnedStuck: boolean;\n    maxConcurrency: number;\n    runningCount: number;\n    stuckTimer?: NodeJS.Timeout;\n    alias: string;\n    first: boolean;\n    queue: {\n        [key: string]: Array<{\n            factory: () => Promise<any>;\n            resolve: (val: any) => void;\n            reject: Function;\n        }>;\n    };\n    running: {\n        [key: string]: boolean;\n    };\n    stillActive(): void;\n    stuckTick(): void;\n    push<T>(key: string, factory: () => Promise<T>): Promise<T>;\n    shift(key: string): void;\n    maybePushConcurrencyQueue(run: () => void): void;\n    shiftConcurrencyQueue(): void;\n}\n"
  },
  {
    "path": "checkpoint/dist-types/util/child.d.ts",
    "content": "/// <reference types=\"node\" />\nimport BlockingQueue from './blocking-queue.js';\nimport { ChildProcess, SpawnOptions } from 'child_process';\nexport declare const queue: BlockingQueue;\nexport declare const exec: (...args: any[]) => Promise<any>;\nexport declare function forwardSignalToSpawnedProcesses(signal: string): void;\ndeclare type ProcessFn = (proc: ChildProcess, update: (chunk: string) => void, reject: (err: any) => void, done: () => void) => void;\nexport declare function spawn(program: string, args: Array<string>, opts?: SpawnOptions & {\n    detached?: boolean;\n    process?: ProcessFn;\n}, onData?: (chunk: Buffer | string) => void): Promise<string>;\nexport {};\n"
  },
  {
    "path": "checkpoint/dist-types/util/conversion.d.ts",
    "content": "export declare function boolify(val: string | number | boolean): boolean;\nexport declare function boolifyWithDefault(val: string | number | boolean, defaultResult: boolean): boolean;\n"
  },
  {
    "path": "checkpoint/dist-types/util/execute-lifecycle-script.d.ts",
    "content": "/// <reference types=\"node\" />\nexport declare type LifecycleReturn = Promise<{\n    cwd: string;\n    command: string;\n    stdout: string;\n}>;\nexport declare function makeEnv(): Promise<{\n    [key: string]: string;\n}>;\nexport declare function executeLifecycleScript({ cwd, cmd, args, isInteractive, onProgress, customShell, }: {\n    cwd: string;\n    args: string[];\n    cmd: string;\n    isInteractive?: boolean;\n    onProgress?: (chunk: Buffer | string) => void;\n    customShell?: string;\n}): LifecycleReturn;\nexport default executeLifecycleScript;\n"
  },
  {
    "path": "checkpoint/dist-types/util/fix-cmd-win-slashes.d.ts",
    "content": "export declare function fixCmdWinSlashes(cmd: string): string;\n"
  },
  {
    "path": "checkpoint/dist-types/util/fs-normalized.d.ts",
    "content": ""
  },
  {
    "path": "checkpoint/dist-types/util/fs.d.ts",
    "content": "/// <reference types=\"node\" />\nexport declare const unlink: (path: string) => Promise<void>;\nexport declare const glob: (path: string, options?: Object) => Promise<Array<string>>;\nexport declare const mkdirp: (path: string) => Promise<void>;\nimport * as fs from 'fs';\nexport declare const open: typeof fs.open.__promisify__;\nexport declare const writeFile: typeof fs.writeFile.__promisify__;\nexport declare const readlink: typeof fs.readlink.__promisify__;\nexport declare const realpath: typeof fs.realpath.__promisify__;\nexport declare const readdir: typeof fs.readdir.__promisify__;\nexport declare const rename: typeof fs.rename.__promisify__;\nexport declare const access: typeof fs.access.__promisify__;\nexport declare const stat: typeof fs.stat.__promisify__;\nexport declare const exists: typeof fs.exists.__promisify__;\nexport declare const lstat: typeof fs.lstat.__promisify__;\nexport declare const chmod: typeof fs.chmod.__promisify__;\nexport declare const link: (arg1: fs.PathLike, arg2: fs.PathLike) => Promise<void>;\nexport declare const copyFile: typeof fs.copyFile.__promisify__;\nexport declare const readFile: (path: string) => Promise<string>;\nexport declare function readJson(loc: string): Promise<Object>;\nexport declare function readJsonAndFile(loc: string): Promise<{\n    object: Object;\n    content: string;\n}>;\nexport declare type WalkFiles = Array<{\n    relative: string;\n    absolute: string;\n    basename: string;\n    mtime: number;\n}>;\nexport declare function walk(dir: string, relativeDir?: string, ignoreBasenames?: Set<string>): Promise<WalkFiles>;\nexport declare function writeFilePreservingEol(path: string, data: string): Promise<void>;\n"
  },
  {
    "path": "checkpoint/dist-types/util/map.d.ts",
    "content": "export default function nullify<T>(obj?: T): T;\n"
  },
  {
    "path": "checkpoint/dist-types/util/misc.d.ts",
    "content": "export declare function sortAlpha(a: string, b: string): number;\nexport declare function sortOptionsByFlags(a: any, b: any): number;\nexport declare function entries<T>(obj: {\n    [key: string]: T;\n}): Array<[string, T]>;\nexport declare function removePrefix(pattern: string, prefix: string): string;\nexport declare function removeSuffix(pattern: string, suffix: string): string;\nexport declare function addSuffix(pattern: string, suffix: string): string;\nexport declare function hyphenate(str: string): string;\nexport declare function camelCase(str: string): string | null;\nexport declare function compareSortedArrays<T>(array1: Array<T>, array2: Array<T>): boolean;\nexport declare function sleep(ms: number): Promise<void>;\n"
  },
  {
    "path": "checkpoint/dist-types/util/normalize-manifest/fix.d.ts",
    "content": "import { Reporter } from '../../reporters/index.js';\ndeclare type Dict<T> = {\n    [key: string]: T;\n};\ndeclare type WarnFunction = (msg: string) => void;\ndeclare const _default: (info: Dict<any>, moduleLoc: string, reporter: Reporter, warn: WarnFunction) => Promise<void>;\nexport default _default;\n"
  },
  {
    "path": "checkpoint/dist-types/util/normalize-manifest/for-publish.d.ts",
    "content": "import Config from '../../config';\nexport declare function generatePublishManifest(manifest: any, config: Config, _dists?: Array<[Function, any]>): Promise<object>;\nexport declare function generatePrettyManifest(manifest: any): string;\n"
  },
  {
    "path": "checkpoint/dist-types/util/normalize-manifest/index.d.ts",
    "content": "import { Manifest } from '../../types.js';\nimport Config from '../../config.js';\ndeclare const _default: (info: any, moduleLoc: string, config: Config, isRoot: boolean) => Promise<Manifest>;\nexport default _default;\n"
  },
  {
    "path": "checkpoint/dist-types/util/normalize-manifest/infer-license.d.ts",
    "content": "export default function inferLicense(license: string): string | null;\n"
  },
  {
    "path": "checkpoint/dist-types/util/normalize-manifest/licenses.d.ts",
    "content": "declare const _default: {\n    'Apache-2.0': RegExp;\n    'BSD-2-Clause': RegExp;\n    'BSD-3-Clause': RegExp;\n    MIT: RegExp;\n    Unlicense: RegExp;\n};\nexport default _default;\n"
  },
  {
    "path": "checkpoint/dist-types/util/normalize-manifest/typos.d.ts",
    "content": "declare const _default: {\n    autohr: string;\n    autor: string;\n    contributers: string;\n    depdenencies: string;\n    dependancies: string;\n    dependecies: string;\n    depends: string;\n    'dev-dependencies': string;\n    devDependences: string;\n    devDepenencies: string;\n    devEependencies: string;\n    devdependencies: string;\n    hampage: string;\n    hompage: string;\n    prefereGlobal: string;\n    publicationConfig: string;\n    repo: string;\n    repostitory: string;\n    script: string;\n};\nexport default _default;\n"
  },
  {
    "path": "checkpoint/dist-types/util/normalize-manifest/util.d.ts",
    "content": "import { PersonObject } from '../../types.js';\nexport declare function isValidLicense(license: string): boolean;\nexport declare function stringifyPerson(person: any): any;\nexport declare function parsePerson(person: any): PersonObject;\nexport declare function normalizePerson(person: any): any | PersonObject;\nexport declare function extractDescription(readme: any): string;\n"
  },
  {
    "path": "checkpoint/dist-types/util/normalize-manifest/validate.d.ts",
    "content": "import { Reporter } from '../../reporters/index.js';\nexport declare function isValidPackageName(name: string): boolean;\ndeclare type WarnFunction = (msg: string) => void;\nexport default function (info: any, isRoot: boolean, reporter: Reporter, warn: WarnFunction): void;\nexport declare function cleanDependencies(info: Object, isRoot: boolean, reporter: Reporter, warn: WarnFunction): void;\nexport {};\n"
  },
  {
    "path": "checkpoint/dist-types/util/promise.d.ts",
    "content": "export declare function wait(delay: number): Promise<void>;\nexport declare function promisify(fn: Function, firstData?: boolean): (...args: Array<any>) => Promise<any>;\nexport declare function queue<T, U>(arr: Array<U>, promiseProducer: (result: U) => Promise<T>, concurrency?: number): Promise<Array<T>>;\n"
  },
  {
    "path": "checkpoint/dist-types/util/signal-handler.d.ts",
    "content": "export default function handleSignals(): void;\n"
  },
  {
    "path": "checkpoint/package.json",
    "content": "{\n  \"name\": \"@pika/pack\",\n  \"description\": \"package building, reimagined.\",\n  \"version\": \"0.4.0\",\n  \"license\": \"MIT\",\n  \"bin\": {\n    \"pika-pack\": \"dist-node/index.bin.js\"\n  },\n  \"files\": [\n    \"dist-*/\",\n    \"bin/\"\n  ],\n  \"pika\": true,\n  \"sideEffects\": false,\n  \"homepage\": \"https://www.pikapkg.com/blog/introducing-pika-pack/\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/pikapkg/pack.git\"\n  },\n  \"dependencies\": {\n    \"@pika/cli\": \"latest\",\n    \"@pika/types\": \"^0.6.0\",\n    \"camelcase\": \"^4.0.0\",\n    \"chalk\": \"^2.1.0\",\n    \"commander\": \"^2.9.0\",\n    \"file-uri-to-path\": \"^1.0.0\",\n    \"glob\": \"^7.1.1\",\n    \"import-from\": \"^3.0.0\",\n    \"invariant\": \"^2.2.0\",\n    \"is-builtin-module\": \"^2.0.0\",\n    \"is-ci\": \"^1.0.10\",\n    \"loud-rejection\": \"^1.2.0\",\n    \"mkdirp\": \"^0.5.1\",\n    \"np\": \"^5.0.2\",\n    \"rimraf\": \"^2.5.0\",\n    \"strip-ansi\": \"^4.0.0\",\n    \"strip-bom\": \"^3.0.0\",\n    \"validate-npm-package-license\": \"^3.0.4\",\n    \"yargs-parser\": \"^13.1.1\"\n  },\n  \"devDependencies\": {\n    \"@pika/plugin-build-node\": \"^0.6.0\",\n    \"@pika/plugin-simple-bin\": \"^0.6.0\",\n    \"@pika/plugin-ts-standard-pkg\": \"^0.6.0\",\n    \"prettier\": \"^1.15.3\",\n    \"typescript\": \"^3.2.2\"\n  },\n  \"engines\": {\n    \"node\": \">=8\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"source\": \"dist-src/index.js\",\n  \"types\": \"dist-types/index.d.ts\",\n  \"main\": \"dist-node/index.js\"\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"@pika/pack\",\n  \"description\": \"package building, reimagined.\",\n  \"version\": \"0.6.0\",\n  \"license\": \"MIT\",\n  \"homepage\": \"https://www.pikapkg.com/blog/introducing-pika-pack/\",\n  \"engines\": {\n    \"node\": \">=8\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/pikapkg/pack.git\"\n  },\n  \"scripts\": {\n    \"format\": \"prettier --write src/**/*.ts\",\n    \"build\": \"node checkpoint/dist-node/index.bin.js\",\n    \"publish\": \"pika publish\",\n    \"test\": \"node pkg/dist-node/index.bin.js\",\n    \"version\": \"node  pkg/dist-node/index.bin.js\",\n    \"update-checkpoint\": \"rm -rf checkpoint/ && cp -r pkg/ checkpoint/\"\n  },\n  \"@pika/pack\": {\n    \"pipeline\": [\n      [\n        \"@pika/plugin-ts-standard-pkg\"\n      ],\n      [\n        \"@pika/plugin-build-node\"\n      ],\n      [\n        \"@pika/plugin-simple-bin\",\n        {\n          \"bin\": \"pika-pack\",\n          \"minNodeVersion\": 8\n        }\n      ]\n    ]\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"dependencies\": {\n    \"commander\": \"^6.2.1\",\n    \"file-uri-to-path\": \"^2.0.0\",\n    \"glob\": \"^7.1.6\",\n    \"import-from\": \"^3.0.0\",\n    \"invariant\": \"^2.2.4\",\n    \"is-builtin-module\": \"^3.0.0\",\n    \"is-ci\": \"^2.0.0\",\n    \"kleur\": \"^4.1.3\",\n    \"loud-rejection\": \"^2.2.0\",\n    \"mkdirp\": \"^1.0.4\",\n    \"np\": \"^7.1.0\",\n    \"rimraf\": \"^3.0.2\",\n    \"strip-ansi\": \"^6.0.0\",\n    \"strip-bom\": \"^4.0.0\",\n    \"validate-npm-package-license\": \"^3.0.4\",\n    \"yargs-parser\": \"^20.2.4\"\n  },\n  \"devDependencies\": {\n    \"@pika/plugin-build-node\": \"^0.9.2\",\n    \"@pika/plugin-simple-bin\": \"^0.9.2\",\n    \"@pika/plugin-ts-standard-pkg\": \"^0.9.2\",\n    \"@types/yargs-parser\": \"^20.2.0\",\n    \"prettier\": \"^2.2.1\",\n    \"typescript\": \"^4.1.3\"\n  }\n}\n"
  },
  {
    "path": "src/commands/build.ts",
    "content": "import {BuilderOptions} from '@pika/types';\nimport chalk from 'chalk';\nimport * as path from 'path';\nimport Config, {BuildFlags} from '../config.js';\nimport {DEFAULT_INDENT} from '../constants.js';\nimport {Reporter} from '../reporters/index.js';\nimport * as fs from '../util/fs.js';\nimport {generatePrettyManifest, generatePublishManifest} from '../util/normalize-manifest/for-publish.js';\n\nexport function hasWrapper(): boolean {\n  return true;\n}\n\nexport const examples = null;\n\nexport class Build {\n  constructor(flags: BuildFlags, config: Config, reporter: Reporter) {\n    this.flags = flags;\n    this.config = config;\n    this.reporter = reporter;\n    this.totalNum = 0;\n    this.out = path.resolve(config.cwd, flags.out || 'pkg/');\n    if (this.out === this.config.cwd) {\n      throw new Error('On publish, you cannot write to cwd because a package.json is created');\n    }\n  }\n\n  out: string;\n  flags: BuildFlags;\n  config: Config;\n  reporter: Reporter;\n  totalNum: number;\n\n  async cleanup(): Promise<void> {\n    const {out} = this;\n    await fs.unlink(path.join(out, '*'));\n  }\n\n  async init(isFull?: boolean): Promise<void> {\n    const {config, out, reporter, flags} = this;\n    const {cwd} = config;\n    const outPretty = path.relative(cwd, out) + path.sep;\n\n    const manifest = await config.manifest;\n    const {sourcemap} = manifest['@pika/pack'] || {sourcemap: true};\n    const distRunners = await config.getDistributions();\n    const builderConfig: Partial<BuilderOptions> = {\n      out,\n      cwd,\n      reporter: {\n        info: (msg) => reporter.log(chalk.dim(`      » ${msg}`)),\n        warning: (msg) => reporter.log(chalk.yellow(`      » ${msg}`)),\n        success: (msg) => reporter.log(chalk.green(`      » ${msg}`)),\n        created: (filename: string, entrypoint?: string) =>\n          reporter.log(\n            `      📝  ${chalk.green(path.relative(cwd, filename))} ${entrypoint ? chalk.dim(`[${entrypoint}]`) : ''}`,\n          ),\n      },\n      isFull,\n      manifest,\n      src: {\n        loc: path.join(out, 'dist-src'),\n        entrypoint: path.join(out, 'dist-src', 'index.js'),\n        // TODO: Deprecated, remove\n        options: {},\n        // TODO: Deprecated, remove\n        files: await (async (): Promise<Array<string>> => {\n          const ignoreSet = new Set<string>([]);\n          ignoreSet.add('**/*/README.md');\n          const files = await fs.glob(`src/**/*`, {\n            cwd,\n            nodir: true,\n            absolute: true,\n            ignore: Array.from(ignoreSet).map((g) => path.join('src', g)),\n          });\n          return files.filter((fileAbs) => !fileAbs.endsWith('.d.ts'));\n        })(),\n      },\n    };\n    const steps: Array<(curr: number, total: number) => Promise<{bailout: boolean} | void>> = [];\n    steps.push(async (curr: number, total: number) => {\n      this.reporter.step(curr, total, 'Validating source');\n      for (const [runner, options] of distRunners) {\n        if (runner.validate) {\n          const result = await runner.validate({\n            ...builderConfig,\n            options: {sourcemap, ...options},\n          });\n          if (result instanceof Error) {\n            throw result;\n          }\n        }\n      }\n    });\n\n    steps.push(async (curr: number, total: number) => {\n      this.reporter.step(curr, total, `Preparing pipeline`);\n      await this.cleanup();\n      reporter.log(`      ❇️  ${chalk.green(outPretty)}`);\n      for (const [runner, options] of distRunners) {\n        await (runner.beforeBuild &&\n          runner.beforeBuild({\n            ...builderConfig,\n            options: {sourcemap, ...options},\n          }));\n      }\n    });\n\n    if (distRunners.length === 0) {\n      steps.push(async (curr: number, total: number) => {\n        this.reporter.step(\n          curr,\n          total,\n          `Pipeline is empty! See ${chalk.underline('https://github.com/pikapkg/pack')} for help getting started`,\n        );\n      });\n    }\n\n    for (const [runner, options] of distRunners) {\n      steps.push(async (curr: number, total: number) => {\n        this.reporter.step(curr, total, `Running ${chalk.bold(runner.name)}`);\n        // return Promise.resolve(\n        try {\n          await (runner.beforeJob &&\n            runner.beforeJob({\n              ...builderConfig,\n              options: {sourcemap, ...options},\n            }));\n          await (runner.build &&\n            runner.build({\n              ...builderConfig,\n              options: {sourcemap, ...options},\n            }));\n          await (runner.afterJob &&\n            runner.afterJob({\n              ...builderConfig,\n              options: {sourcemap, ...options},\n            }));\n        } catch (err) {\n          if (flags.force) {\n            console.error('      ❗️  ', chalk.red(err.message), chalk.dim('--force, continuing...'));\n          } else {\n            console.error('      ❗️  ', chalk.red(err.message));\n            if (err.all) {\n              console.error('      ❗️  ', chalk.bold('ERROR OUTPUT:'));\n              console.error(err.all);\n            }\n            throw err;\n          }\n        }\n        // ).catch(err => {\n        // log(chalk.red(err.message));\n        // reporter.log(\n        //   reporter.lang(\"distFailed\", runner.name, err.code, err.message),\n        //   { force: true }\n        // );\n        // if (err.forceExit === true) {\n        // reporter.log(reporter.lang(\"distExiting\"));\n        // throw err;\n        // return;\n        // }\n        // reporter.log(reporter.lang(\"distContinuing\"));\n        // });\n      });\n    }\n    steps.push(async (curr: number, total: number) => {\n      this.reporter.step(curr, total, `Finalizing package`);\n      for (const [runner, options] of distRunners) {\n        await (runner.afterBuild &&\n          runner.afterBuild({\n            ...builderConfig,\n            options: {sourcemap, ...options},\n          }));\n      }\n\n      if (await fs.exists(path.join(cwd, 'CHANGELOG'))) {\n        fs.copyFile(path.join(cwd, 'CHANGELOG'), path.join(out, 'CHANGELOG'));\n        reporter.log(chalk.dim(`      » copying CHANGELOG...`));\n      } else if (await fs.exists(path.join(cwd, 'CHANGELOG.md'))) {\n        fs.copyFile(path.join(cwd, 'CHANGELOG.md'), path.join(out, 'CHANGELOG.md'));\n        reporter.log(chalk.dim(`      » copying CHANGELOG.md...`));\n      }\n\n      if (await fs.exists(path.join(cwd, 'LICENSE'))) {\n        fs.copyFile(path.join(cwd, 'LICENSE'), path.join(out, 'LICENSE'));\n        reporter.log(chalk.dim(`      » copying LICENSE...`));\n      } else if (await fs.exists(path.join(cwd, 'LICENSE.md'))) {\n        fs.copyFile(path.join(cwd, 'LICENSE.md'), path.join(out, 'LICENSE.md'));\n        reporter.log(chalk.dim(`      » copying LICENSE.md...`));\n      }\n\n      if (await fs.exists(path.join(cwd, 'README'))) {\n        fs.copyFile(path.join(cwd, 'README'), path.join(out, 'README'));\n        reporter.log(chalk.dim(`      » copying README...`));\n      } else if (await fs.exists(path.join(cwd, 'README.md'))) {\n        fs.copyFile(path.join(cwd, 'README.md'), path.join(out, 'README.md'));\n        reporter.log(chalk.dim(`      » copying README.md...`));\n      }\n\n      const publishManifest = await generatePublishManifest(config._manifest, config, distRunners);\n      if (out === cwd) {\n        reporter.log(`NEW MANIFEST:\\n\\n`);\n        reporter.log(generatePrettyManifest(publishManifest));\n        reporter.log(`\\n\\n`);\n      } else {\n        await fs.writeFilePreservingEol(\n          path.join(out, 'package.json'),\n          JSON.stringify(publishManifest, null, DEFAULT_INDENT) + '\\n',\n        );\n        reporter.log(`      📝  ` + chalk.green(outPretty + 'package.json'));\n      }\n\n      reporter.log(`      📦  ` + chalk.green(outPretty));\n    });\n    let currentStep = 0;\n    for (const step of steps) {\n      await step(++currentStep, steps.length);\n    }\n  }\n}\n\nexport async function run(config: Config, reporter: Reporter, flags: BuildFlags, args: Array<string>): Promise<void> {\n  const isProduction = flags.publish;\n  const builder = new Build(flags, config, reporter);\n  await builder.init(isProduction);\n}\n"
  },
  {
    "path": "src/config.ts",
    "content": "declare function __non_webpack_require__(m: string): any;\n\nimport * as path from 'path';\nimport * as constants from './constants.js';\nimport {MessageError} from '@pika/types';\nimport {Manifest} from './types.js';\nimport * as fs from './util/fs.js';\nimport normalizeManifest from './util/normalize-manifest/index.js';\nimport BaseReporter from './reporters/base-reporter.js';\nimport executeLifecycleScript from './util/execute-lifecycle-script.js';\nimport importFrom from 'import-from';\n\nexport interface BuildFlags {\n  publish?: boolean;\n  out?: string;\n  silent?: boolean;\n  force?: boolean;\n}\n\nexport interface GlobalFlags extends BuildFlags {\n  cwd?: string;\n  pipeline?: string;\n  verbose?: boolean;\n  json?: boolean;\n}\n\nexport default class Config {\n  cwd: string;\n  reporter: BaseReporter;\n  _manifest: any;\n  manifest: Manifest;\n  flags: GlobalFlags;\n\n  constructor(reporter: BaseReporter, cwd: string, flags: GlobalFlags) {\n    this.reporter = reporter;\n    // Ensure the cwd is always an absolute path.\n    this.cwd = path.resolve(cwd || process.cwd());\n    this.flags = flags;\n  }\n\n  async loadPackageManifest() {\n    const loc = path.join(this.cwd, constants.NODE_PACKAGE_JSON);\n    if (await fs.exists(loc)) {\n      const info = await this.readJson(loc, fs.readJsonAndFile);\n      this._manifest = {...info.object};\n      this.manifest = await normalizeManifest(info.object, this.cwd, this, true);\n      return this.manifest;\n    } else {\n      return null;\n    }\n  }\n\n  readJson(loc: string, factory: (filename: string) => Promise<any> = fs.readJson): Promise<any> {\n    try {\n      return factory(loc);\n    } catch (err) {\n      if (err instanceof SyntaxError) {\n        throw new MessageError(this.reporter.lang('jsonError', loc, err.message));\n      } else {\n        throw err;\n      }\n    }\n  }\n\n  async getDistributions(): Promise<[any, any][]> {\n    const raw = this.manifest[`@pika/pack`] || {};\n    const override = this.flags.pipeline && JSON.parse(this.flags.pipeline);\n    const cwd = this.cwd;\n    function cleanRawDistObject(rawVal): false | [any, any] {\n      if (Array.isArray(rawVal)) {\n        let importStr =\n          rawVal[0].startsWith('./') || rawVal[0].startsWith('../') ? path.join(cwd, rawVal[0]) : rawVal[0];\n        const importResult = importFrom(cwd, importStr) as any;\n        return [{...importResult, name: rawVal[0]}, rawVal[1] || {}];\n      }\n      if (typeof rawVal === 'string') {\n        return [\n          {\n            build: ({cwd}) => {\n              return executeLifecycleScript({\n                // config: this,\n                args: [],\n                cwd,\n                cmd: rawVal,\n                isInteractive: false,\n              });\n            },\n          },\n          {},\n        ];\n      }\n      if (!rawVal) {\n        throw new Error('Cannot be false');\n      }\n      return false;\n    }\n    const pipeline: any[] = override || raw.pipeline || [];\n    return pipeline.map(cleanRawDistObject).filter(Boolean) as [any, any][];\n  }\n}\n"
  },
  {
    "path": "src/constants.ts",
    "content": "// import os from 'os';\n// import * as path from 'path';\n// import userHome from './util/user-home-dir.js';\n// import {getCacheDir, getConfigDir, getDataDir} from './util/user-dirs.js';\n\nexport const DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDependencies'];\n// export const OWNED_DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDependencies'];\n\nexport const RESOLUTIONS = 'resolutions';\nexport const MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES];\n\nexport const SUPPORTED_NODE_VERSIONS = '>=8.5.0';\n\n// export const PIKA_REGISTRY = 'https://registry.npmjs.org';\n// export const NPM_REGISTRY_RE = /https?:\\/\\/registry\\.npmjs\\.org/g;\n\n// export const PIKA_DOCS = 'https://yarnpkg.com/en/docs/cli/';\n// export const PIKA_INSTALLER_SH = 'https://yarnpkg.com/install.sh';\n// export const PIKA_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi';\n\n// export const SELF_UPDATE_VERSION_URL = 'https://www.pikapkg.com/downloads/latest-version';\n\n// // cache version, bump whenever we make backwards incompatible changes\n// export const CACHE_VERSION = 3;\n\n// // lockfile version, bump whenever we make backwards incompatible changes\n// export const LOCKFILE_VERSION = 1;\n\n// // max amount of network requests to perform concurrently\n// export const NETWORK_CONCURRENCY = 8;\n\n// // HTTP timeout used when downloading packages\n// export const NETWORK_TIMEOUT = 30 * 1000; // in milliseconds\n\n// // max amount of child processes to execute concurrently\nexport const CHILD_CONCURRENCY = 5;\n\n// export const REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid'];\n\n// function getPreferredCacheDirectories(): Array<string> {\n//   const preferredCacheDirectories = [getCacheDir()];\n\n//   if (process.getuid) {\n//     // $FlowFixMe: process.getuid exists, dammit\n//     preferredCacheDirectories.push(path.join(os.tmpdir(), `.pika-cache-${process.getuid()}`));\n//   }\n\n//   preferredCacheDirectories.push(path.join(os.tmpdir(), `.pika-cache`));\n\n//   return preferredCacheDirectories;\n// }\n\n// export const PREFERRED_MODULE_CACHE_DIRECTORIES = getPreferredCacheDirectories();\n// export const CONFIG_DIRECTORY = getConfigDir();\n// export const DATA_DIRECTORY = getDataDir();\n// export const LINK_REGISTRY_DIRECTORY = path.join(DATA_DIRECTORY, 'link');\n// export const GLOBAL_MODULE_DIRECTORY = path.join(DATA_DIRECTORY, 'global');\n\n// export const NODE_BIN_PATH = process.execPath;\n\nexport const NODE_MODULES_FOLDER = 'node_modules';\nexport const NODE_PACKAGE_JSON = 'package.json';\n\n// export const PNP_FILENAME = '.pnp';\n\n// export const POSIX_GLOBAL_PREFIX = `${process.env.DESTDIR || ''}/usr/local`;\n// export const FALLBACK_GLOBAL_PREFIX = path.join(userHome, '.pika');\n\n// export const META_FOLDER = '.pika-meta';\n// export const INTEGRITY_FILENAME = '.pika-integrity';\n// export const LOCKFILE_FILENAME = 'pika.lock';\n// export const LEGACY_LOCKFILE_FILENAME = 'yarn.lock';\n// export const METADATA_FILENAME = '.pika-metadata.json';\n// export const TARBALL_FILENAME = '.pika-tarball.tgz';\n// export const CLEAN_FILENAME = '.pikaclean';\n\n// export const NPM_LOCK_FILENAME = 'package-lock.json';\n// export const NPM_SHRINKWRAP_FILENAME = 'npm-shrinkwrap.json';\n\nexport const DEFAULT_INDENT = '  ';\n// export const SINGLE_INSTANCE_PORT = 31997;\n// export const SINGLE_INSTANCE_FILENAME = '.pika-single-instance';\n\nexport const ENV_PATH_KEY = getPathKey(process.platform, process.env);\n\nexport function getPathKey(platform: string, env: NodeJS.ProcessEnv): string {\n  let pathKey = 'PATH';\n\n  // windows calls its path \"Path\" usually, but this is not guaranteed.\n  if (platform === 'win32') {\n    pathKey = 'Path';\n\n    for (const key in env) {\n      if (key.toLowerCase() === 'path') {\n        pathKey = key;\n      }\n    }\n  }\n\n  return pathKey;\n}\n\n// export const VERSION_COLOR_SCHEME: {[key: string]: VersionColor} = {\n//   major: 'red',\n//   premajor: 'red',\n//   minor: 'yellow',\n//   preminor: 'yellow',\n//   patch: 'green',\n//   prepatch: 'green',\n//   prerelease: 'red',\n//   unchanged: 'white',\n//   unknown: 'red',\n// };\n\n// export type VersionColor = 'red' | 'yellow' | 'green' | 'white';\n\n// export type RequestHint = 'dev' | 'optional' | 'resolution' | 'workspaces';\n"
  },
  {
    "path": "src/errors.ts",
    "content": "import {MessageError} from '@pika/types';\n\nexport class ProcessSpawnError extends MessageError {\n  constructor(msg: string, code?: string, process?: string) {\n    super(msg);\n    this.code = code;\n    this.process = process;\n  }\n\n  code?: string;\n  process?: string;\n}\n\nexport class SecurityError extends MessageError {}\n\nexport class ProcessTermError extends MessageError {\n  EXIT_CODE?: number;\n  EXIT_SIGNAL?: string;\n}\n\nexport class ResponseError extends Error {\n  constructor(msg: string, responseCode: number) {\n    super(msg);\n    this.responseCode = responseCode;\n  }\n\n  responseCode: number;\n}\n\nexport class OneTimePasswordError extends Error {}\n"
  },
  {
    "path": "src/index.ts",
    "content": "import * as path from 'path';\nimport * as kleur from 'kleur';\nimport * as fs from 'fs';\nimport invariant from 'invariant';\nimport loudRejection from 'loud-rejection';\n\nimport {ConsoleReporter, JSONReporter} from './reporters/index.js';\nimport * as buildCommand from './commands/build.js';\nimport {MessageError} from '@pika/types';\nimport Config, {GlobalFlags} from './config.js';\nimport handleSignals from './util/signal-handler.js';\nimport {boolifyWithDefault} from './util/conversion.js';\nimport map from './util/map.js';\nimport stripBOM from 'strip-bom';\nimport uri2path from 'file-uri-to-path';\nimport yargs from 'yargs-parser';\n\n// @ts-ignore\nconst currentFilename = uri2path(import.meta.url);\nfunction getVersion() {\n  const packageJsonContent = fs.readFileSync(path.resolve(currentFilename, '../../package.json'), {encoding: 'utf-8'});\n  const {version} = map(JSON.parse(stripBOM(packageJsonContent)));\n  return version;\n}\n\nfunction printHelp() {\n  console.log(\n    `\n${kleur.bold(`@pika/pack`)} - Build npm packages without the mess.\n${kleur.bold('Options:')}\n    --cwd               Set the current working directory.\n    --out               Set the output directory. Defaults to \"pkg/\".\n    --pipeline          Set a build pipeline via JSON string.\n    --force             Continue with the build when a build plugin fails or throws an exception.\n    --json              Log output as JSON.\n    --verbose           Log additional debugging information.\n    --silent            Log almost nothing.\n    --help              Print help.\n    --version, -v       Print version.\n    `.trim(),\n  );\n}\n\nexport async function cli(args: string[]) {\n  const version = getVersion();\n  loudRejection();\n  handleSignals();\n\n  // Handle special flags\n  if (args.find((arg) => arg === '--version' || arg === '-v')) {\n    console.log(version.trim());\n    process.exitCode = 0;\n    return;\n  }\n  if (args.find((arg) => arg === '--help')) {\n    printHelp();\n    process.exitCode = 0;\n    return;\n  }\n\n  // Handle the legacy CLI interface\n  if (args[2] === 'publish') {\n    console.log(`The publish flow has moved to the @pika/cli package (included with this package).\nUpdate your publish script to: ${kleur.bold('pika publish [flags]')}\n`);\n    process.exitCode = 1;\n    return;\n  }\n  if (args[2] === 'build') {\n    console.log(\n      kleur.yellow(\n        `Note: This CLI was recently deprecated. Update your build script to: ${kleur.bold('pika build [flags]')}`,\n      ),\n    );\n    args.splice(2, 1);\n  }\n\n  const flags = yargs(args) as GlobalFlags;\n  const cwd = flags.cwd || process.cwd();\n  const Reporter = flags.json ? JSONReporter : ConsoleReporter;\n  const reporter = new Reporter({\n    emoji: true,\n    verbose: flags.verbose,\n    isSilent: boolifyWithDefault(process.env.PIKA_SILENT, false) || flags.silent,\n  });\n\n  const exit = (exitCode: any = 0) => {\n    process.exitCode = exitCode;\n    reporter.close();\n  };\n\n  const command = buildCommand;\n  reporter.initPeakMemoryCounter();\n  const outputWrapperEnabled = boolifyWithDefault(process.env.PIKA_WRAP_OUTPUT, true);\n  const shouldWrapOutput = outputWrapperEnabled && !flags.json && command.hasWrapper();\n  if (shouldWrapOutput) {\n    reporter.header({name: '@pika/pack', version});\n  }\n\n  const run = (): Promise<void> => {\n    invariant(command, 'missing command');\n\n    return command.run(config, reporter, flags, args).then((exitCode) => {\n      if (shouldWrapOutput) {\n        reporter.footer(false);\n      }\n      return exitCode;\n    });\n  };\n\n  function onUnexpectedError(err: Error) {\n    function indent(str: string): string {\n      return '\\n  ' + str.trim().split('\\n').join('\\n  ');\n    }\n\n    const log = [];\n    log.push(`Arguments: ${indent(process.argv.join(' '))}`);\n    log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`);\n    log.push(`Pika version: ${indent(version)}`);\n    log.push(`Node version: ${indent(process.versions.node)}`);\n    log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`);\n\n    log.push(`Trace: ${indent(err.stack)}`);\n    reporter.error(reporter.lang('unexpectedError', err.message));\n  }\n\n  const config = new Config(reporter, cwd, flags);\n  await config.loadPackageManifest();\n\n  try {\n    // option \"no-progress\" stored in pika config\n    const noProgressConfig = false; //config.registries.pika.getOption('no-progress');\n\n    if (noProgressConfig) {\n      reporter.disableProgress();\n    }\n\n    // verbose logs outputs process.uptime() with this line we can sync uptime to absolute time on the computer\n    reporter.verbose(`current time: ${new Date().toISOString()}`);\n    return run().then(exit);\n  } catch (err) {\n    reporter.verbose(err.stack);\n\n    if (err instanceof MessageError) {\n      reporter.error(err.message);\n    } else {\n      onUnexpectedError(err);\n    }\n\n    return exit(1);\n  }\n}\n"
  },
  {
    "path": "src/reporters/base-reporter.ts",
    "content": "import {ReporterSpinnerSet, Trees, Stdout, Stdin, Package, ReporterSpinner} from './types';\nimport {LanguageKeys} from './lang/en.js';\nimport {Formatter} from './format.js';\n\nimport {defaultFormatter} from './format.js';\nimport * as languages from './lang/index.js';\nimport * as isCI from 'is-ci';\nimport * as os from 'os';\n\nimport * as util from 'util';\nimport {EventEmitter} from 'events';\n\ntype Language = keyof typeof languages;\n\nexport type ReporterOptions = {\n  verbose?: boolean;\n  language?: Language;\n  stdout?: Stdout;\n  stderr?: Stdout;\n  stdin?: Stdin;\n  emoji?: boolean;\n  noProgress?: boolean;\n  silent?: boolean;\n  isSilent?: boolean;\n  nonInteractive?: boolean;\n};\n\nexport function stringifyLangArgs(args: Array<any>): Array<string> {\n  return args.map(function (val): string {\n    if (val != null && val.inspect) {\n      return val.inspect();\n    } else {\n      try {\n        const str = JSON.stringify(val) || val + '';\n        // should match all literal line breaks and\n        // \"u001b\" that follow an odd number of backslashes and convert them to ESC\n        // we do this because the JSON.stringify process has escaped these characters\n        return str\n          .replace(/((?:^|[^\\\\])(?:\\\\{2})*)\\\\u001[bB]/g, '$1\\u001b')\n          .replace(/[\\\\]r[\\\\]n|([\\\\])?[\\\\]n/g, (match, precededBacklash) => {\n            // precededBacklash not null when \"\\n\" is preceded by a backlash (\"\\\\n\")\n            // match will be \"\\\\n\" and we don't replace it with os.EOL\n            return precededBacklash ? match : os.EOL;\n          });\n      } catch (e) {\n        return util.inspect(val);\n      }\n    }\n  });\n}\n\nexport default class BaseReporter {\n  constructor(opts: ReporterOptions = {}) {\n    const lang = 'en';\n    this.language = lang;\n    this.stdout = opts.stdout || process.stdout;\n    this.stderr = opts.stderr || process.stderr;\n    this.stdin = opts.stdin || this._getStandardInput();\n    this.emoji = !!opts.emoji;\n    this.nonInteractive = !!opts.nonInteractive;\n    this.noProgress = !!opts.noProgress || isCI;\n    this.isVerbose = !!opts.verbose;\n\n    // @ts-ignore\n    this.isTTY = this.stdout.isTTY;\n\n    this.peakMemory = 0;\n    this.startTime = Date.now();\n    this.format = defaultFormatter;\n  }\n\n  formatter: Formatter;\n  language: Language;\n  stdout: Stdout;\n  stderr: Stdout;\n  stdin: Stdin;\n  isTTY: boolean;\n  emoji: boolean;\n  noProgress: boolean;\n  isVerbose: boolean;\n  isSilent: boolean;\n  nonInteractive: boolean;\n  format: Formatter;\n\n  peakMemoryInterval?: NodeJS.Timer;\n  peakMemory: number;\n  startTime: number;\n\n  lang(key: LanguageKeys, ...args: Array<any>): string {\n    const msg = languages[this.language][key] || languages.en[key];\n    if (!msg) {\n      throw new ReferenceError(`No message defined for language key ${key}`);\n    }\n\n    // stringify args\n    const stringifiedArgs = stringifyLangArgs(args);\n\n    // replace $0 placeholders with args\n    return msg.replace(/\\$(\\d+)/g, (str, i: number) => {\n      return stringifiedArgs[i];\n    });\n  }\n\n  /**\n   * `stringifyLangArgs` run `JSON.stringify` on strings too causing\n   * them to appear quoted. This marks them as \"raw\" and prevents\n   * the quoting and escaping\n   */\n  rawText(str: string): {inspect(): string} {\n    return {\n      inspect(): string {\n        return str;\n      },\n    };\n  }\n\n  verbose(msg: string) {\n    if (this.isVerbose) {\n      this._verbose(msg);\n    }\n  }\n\n  verboseInspect(val: any) {\n    if (this.isVerbose) {\n      this._verboseInspect(val);\n    }\n  }\n\n  _verbose(msg: string) {}\n  _verboseInspect(val: any) {}\n\n  _getStandardInput(): Stdin {\n    let standardInput;\n\n    // Accessing stdin in a win32 headless process (e.g., Visual Studio) may throw an exception.\n    try {\n      standardInput = process.stdin;\n    } catch (e) {\n      console.warn(e.message);\n      delete process.stdin;\n      // @ts-ignore\n      process.stdin = new EventEmitter();\n      standardInput = process.stdin;\n    }\n\n    return standardInput;\n  }\n\n  initPeakMemoryCounter() {\n    this.checkPeakMemory();\n    this.peakMemoryInterval = setInterval(() => {\n      this.checkPeakMemory();\n    }, 1000);\n    // $FlowFixMe: Node's setInterval returns a Timeout, not a Number\n    this.peakMemoryInterval.unref();\n  }\n\n  checkPeakMemory() {\n    const {heapTotal} = process.memoryUsage();\n    if (heapTotal > this.peakMemory) {\n      this.peakMemory = heapTotal;\n    }\n  }\n\n  close() {\n    if (this.peakMemoryInterval) {\n      clearInterval(this.peakMemoryInterval);\n      this.peakMemoryInterval = null;\n    }\n  }\n\n  getTotalTime(): number {\n    return Date.now() - this.startTime;\n  }\n\n  // TODO\n  list(key: string, items: Array<string>, hints?: Object) {}\n\n  // Outputs basic tree structure to console\n  tree(key: string, obj: Trees, {force = false}: {force?: boolean} = {}) {}\n\n  // called whenever we begin a step in the CLI.\n  step(current: number, total: number, message: string, emoji?: string) {}\n\n  // a error message has been triggered. this however does not always meant an abrupt\n  // program end.\n  error(message: string) {}\n\n  // an info message has been triggered. this provides things like stats and diagnostics.\n  info(message: string) {}\n\n  // a warning message has been triggered.\n  warn(message: string) {}\n\n  // a success message has been triggered.\n  success(message: string) {}\n\n  // a simple log message\n  // TODO: rethink the {force} parameter. In the meantime, please don't use it (cf comments in #4143).\n  log(message: string, {force = false}: {force?: boolean} = {}) {}\n\n  // a shell command has been executed\n  command(command: string) {}\n\n  // inspect and pretty-print any value\n  inspect(value: any) {}\n\n  // the screen shown at the very start of the CLI\n  header(pkg: Package) {}\n\n  // the screen shown at the very end of the CLI\n  footer(showPeakMemory: boolean) {}\n\n  // a table structure\n  table(head: Array<string>, body: Array<Array<string>>) {}\n\n  // render an activity spinner and return a function that will trigger an update\n  activity(): ReporterSpinner {\n    return {\n      tick(name: string) {},\n      end() {},\n    };\n  }\n\n  //\n  activitySet(total: number, workers: number): ReporterSpinnerSet {\n    return {\n      spinners: Array(workers).fill({\n        clear() {},\n        setPrefix() {},\n        tick() {},\n        end() {},\n      }),\n      end() {},\n    };\n  }\n\n  // render a progress bar and return a function which when called will trigger an update\n  progress(total: number): () => void {\n    return function () {};\n  }\n\n  // utility function to disable progress bar\n  disableProgress() {\n    this.noProgress = true;\n  }\n}\n"
  },
  {
    "path": "src/reporters/console/console-reporter.ts",
    "content": "import chalk from 'chalk';\nimport * as readline from 'readline';\nimport stripAnsi from 'strip-ansi';\nimport {inspect} from 'util';\nimport {removeSuffix} from '../../util/misc.js';\nimport BaseReporter, {ReporterOptions} from '../base-reporter.js';\nimport {FormatKeys, Formatter} from '../format.js';\nimport {Package, ReporterSetSpinner, ReporterSpinner, ReporterSpinnerSet, Trees} from '../types.js';\nimport {getFormattedOutput, recurseTree, sortTrees} from './helpers/tree-helper.js';\nimport Progress from './progress-bar.js';\nimport Spinner from './spinner-progress.js';\nimport {clearLine} from './util.js';\n\nconst AUDIT_COL_WIDTHS = [15, 62];\n\nconst auditSeverityColors = {\n  info: chalk.bold,\n  low: chalk.bold,\n  moderate: chalk.yellow,\n  high: chalk.red,\n  critical: chalk.bgRed,\n};\n\ntype Row = Array<string>;\n\n// fixes bold on windows\nif (process.platform === 'win32' && !(process.env.TERM && /^xterm/i.test(process.env.TERM))) {\n  // @ts-ignore\n  chalk.bold._styles[0].close += '\\u001b[m';\n}\n\nexport default class ConsoleReporter extends BaseReporter {\n  _lastCategorySize: number;\n  _progressBar?: Progress;\n  _spinners: Set<Spinner>;\n\n  constructor(opts: ReporterOptions) {\n    super(opts);\n\n    this._lastCategorySize = 0;\n    this._spinners = new Set();\n    this.format = (chalk as any) as Formatter;\n    this.format.stripColor = stripAnsi;\n    this.isSilent = !!opts.isSilent;\n  }\n\n  _prependEmoji(msg: string, emoji?: string): string {\n    if (this.emoji && emoji && this.isTTY) {\n      msg = `${emoji}  ${msg}`;\n    }\n    return msg;\n  }\n\n  _logCategory(category: string, color: FormatKeys, msg: string) {\n    this._lastCategorySize = category.length;\n    this._log(`${this.format[color](category)} ${msg}`);\n  }\n\n  _verbose(msg: string) {\n    this._logCategory('verbose', 'grey', `${process.uptime()} ${msg}`);\n  }\n\n  _verboseInspect(obj: any) {\n    this.inspect(obj);\n  }\n\n  close() {\n    for (const spinner of this._spinners) {\n      spinner.stop();\n    }\n    this._spinners.clear();\n    this.stopProgress();\n    super.close();\n  }\n\n  table(head: Array<string>, body: Array<Row>) {\n    //\n    head = head.map((field: string): string => this.format.underline(field));\n\n    //\n    const rows = [head].concat(body);\n\n    // get column widths\n    const cols: Array<number> = [];\n    for (let i = 0; i < head.length; i++) {\n      const widths = rows.map((row: Row): number => this.format.stripColor(row[i]).length);\n      cols[i] = Math.max(...widths);\n    }\n\n    //\n    const builtRows = rows.map((row: Row): string => {\n      for (let i = 0; i < row.length; i++) {\n        const field = row[i];\n        const padding = cols[i] - this.format.stripColor(field).length;\n\n        row[i] = field + ' '.repeat(padding);\n      }\n      return row.join(' ');\n    });\n\n    this.log(builtRows.join('\\n'));\n  }\n\n  step(current: number, total: number, msg: string, emoji?: string) {\n    msg = this._prependEmoji(msg, emoji);\n\n    if (msg.endsWith('?')) {\n      msg = `${removeSuffix(msg, '?')}...?`;\n    } else {\n      msg += '...';\n    }\n    this.log(`${this.format.dim(`[${current}/${total}]`)} ${msg}`);\n  }\n\n  inspect(value: any) {\n    if (typeof value !== 'number' && typeof value !== 'string') {\n      value = inspect(value, {\n        breakLength: 0,\n        colors: this.isTTY,\n        depth: null,\n        maxArrayLength: null,\n      });\n    }\n\n    this.log(String(value), {force: true});\n  }\n\n  list(key: string, items: Array<string>, hints?: Object) {\n    const gutterWidth = (this._lastCategorySize || 2) - 1;\n\n    if (hints) {\n      for (const item of items) {\n        this._log(`${' '.repeat(gutterWidth)}- ${this.format.bold(item)}`);\n        this._log(`  ${' '.repeat(gutterWidth)} ${hints[item]}`);\n      }\n    } else {\n      for (const item of items) {\n        this._log(`${' '.repeat(gutterWidth)}- ${item}`);\n      }\n    }\n  }\n\n  header(pkg: Package) {\n    this.log(this.format.bold(`${pkg.name} v${pkg.version}`));\n  }\n\n  footer(showPeakMemory?: boolean) {\n    this.stopProgress();\n\n    const totalTime = (this.getTotalTime() / 1000).toFixed(2);\n    let msg = `Done in ${totalTime}s.`;\n    if (showPeakMemory) {\n      const peakMemory = (this.peakMemory / 1024 / 1024).toFixed(2);\n      msg += ` Peak memory usage ${peakMemory}MB.`;\n    }\n    this.log(this._prependEmoji(msg, '✨'));\n  }\n\n  log(msg: string, {force = false}: {force?: boolean} = {}) {\n    this._lastCategorySize = 0;\n    this._log(msg, {force});\n  }\n\n  _log(msg: string, {force = false}: {force?: boolean} = {}) {\n    if (this.isSilent && !force) {\n      return;\n    }\n    clearLine(this.stdout);\n    this.stdout.write(`${msg}\\n`);\n  }\n\n  success(msg: string) {\n    this._logCategory('success', 'green', msg);\n  }\n\n  error(msg: string) {\n    clearLine(this.stderr);\n    this.stderr.write(`${this.format.red('error')} ${msg}\\n`);\n  }\n\n  info(msg: string) {\n    this._logCategory('info', 'blue', msg);\n  }\n\n  command(command: string) {\n    this.log(this.format.dim(`$ ${command}`));\n  }\n\n  warn(msg: string) {\n    clearLine(this.stderr);\n    this.stderr.write(`${this.format.yellow('warning')} ${msg}\\n`);\n  }\n\n  // handles basic tree output to console\n  tree(key: string, trees: Trees, {force = false}: {force?: boolean} = {}) {\n    this.stopProgress();\n    //\n    if (this.isSilent && !force) {\n      return;\n    }\n    const output = ({name, children, hint, color}, titlePrefix, childrenPrefix) => {\n      const formatter = this.format;\n      const out = getFormattedOutput({\n        prefix: titlePrefix,\n        hint,\n        color,\n        name,\n        formatter,\n      });\n      this.stdout.write(out);\n\n      if (children && children.length) {\n        recurseTree(sortTrees(children), childrenPrefix, output);\n      }\n    };\n    recurseTree(sortTrees(trees), '', output);\n  }\n\n  activitySet(total: number, workers: number): ReporterSpinnerSet {\n    if (!this.isTTY || this.noProgress) {\n      return super.activitySet(total, workers);\n    }\n\n    const spinners: Array<ReporterSetSpinner> = [];\n    const reporterSpinners = this._spinners;\n\n    for (let i = 1; i < workers; i++) {\n      this.log('');\n    }\n\n    for (let i = 0; i < workers; i++) {\n      const spinner = new Spinner(this.stderr, i);\n      reporterSpinners.add(spinner);\n      spinner.start();\n\n      let prefix: string | null = null;\n      let current = 0;\n      const updatePrefix = () => {\n        spinner.setPrefix(`${this.format.dim(`[${current === 0 ? '-' : current}/${total}]`)} `);\n      };\n      const clear = () => {\n        prefix = null;\n        current = 0;\n        updatePrefix();\n        spinner.setText('waiting...');\n      };\n      clear();\n\n      spinners.unshift({\n        clear,\n\n        setPrefix(_current: number, _prefix: string) {\n          current = _current;\n          prefix = _prefix;\n          spinner.setText(prefix);\n          updatePrefix();\n        },\n\n        tick(msg: string) {\n          if (prefix) {\n            msg = `${prefix}: ${msg}`;\n          }\n          spinner.setText(msg);\n        },\n\n        end() {\n          spinner.stop();\n          reporterSpinners.delete(spinner);\n        },\n      });\n    }\n\n    return {\n      spinners,\n      end: () => {\n        for (const spinner of spinners) {\n          spinner.end();\n        }\n        readline.moveCursor(this.stdout, 0, -workers + 1);\n      },\n    };\n  }\n\n  activity(): ReporterSpinner {\n    if (!this.isTTY) {\n      return {\n        tick() {},\n        end() {},\n      };\n    }\n    const reporterSpinners = this._spinners;\n\n    const spinner = new Spinner(this.stderr);\n    spinner.start();\n\n    reporterSpinners.add(spinner);\n\n    return {\n      tick(name: string) {\n        spinner.setText(name);\n      },\n\n      end() {\n        spinner.stop();\n        reporterSpinners.delete(spinner);\n      },\n    };\n  }\n\n  progress(count: number): () => void {\n    if (this.noProgress || count <= 0) {\n      return function () {\n        // noop\n      };\n    }\n\n    if (!this.isTTY) {\n      return function () {\n        // TODO what should the behaviour here be? we could buffer progress messages maybe\n      };\n    }\n\n    // Clear any potentially old progress bars\n    this.stopProgress();\n\n    const bar = (this._progressBar = new Progress(count, this.stderr, (progress: Progress) => {\n      if (progress === this._progressBar) {\n        this._progressBar = null;\n      }\n    }));\n\n    bar.render();\n\n    return function () {\n      bar.tick();\n    };\n  }\n\n  stopProgress() {\n    if (this._progressBar) {\n      this._progressBar.stop();\n    }\n  }\n}\n"
  },
  {
    "path": "src/reporters/console/helpers/tree-helper.ts",
    "content": "// types\nimport {Trees} from '../../types.js';\n\nexport type FormattedOutput = {\n  prefix: string;\n  hint: any;\n  color: string;\n  name: string;\n  formatter: any;\n};\n\n// public\nexport function sortTrees(trees: Trees): Trees {\n  return trees.sort(function (tree1, tree2): number {\n    return tree1.name.localeCompare(tree2.name);\n  });\n}\n\nexport function recurseTree(tree: Trees, prefix: string, recurseFunc: Function) {\n  const treeLen = tree.length;\n  const treeEnd = treeLen - 1;\n  for (let i = 0; i < treeLen; i++) {\n    const atEnd = i === treeEnd;\n    recurseFunc(tree[i], prefix + getLastIndentChar(atEnd), prefix + getNextIndentChar(atEnd));\n  }\n}\n\nexport function getFormattedOutput(fmt: FormattedOutput): string {\n  const item = formatColor(fmt.color, fmt.name, fmt.formatter);\n  const suffix = getSuffix(fmt.hint, fmt.formatter);\n  return `${fmt.prefix}─ ${item}${suffix}\\n`;\n}\n\nfunction getNextIndentChar(end: boolean): string {\n  return end ? '   ' : '│  ';\n}\n\nfunction getLastIndentChar(end: boolean): string {\n  return end ? '└' : '├';\n}\n\nfunction getSuffix(hint: any, formatter: any): string {\n  return hint ? ` (${formatter.grey(hint)})` : '';\n}\n\nfunction formatColor(color: string, strToFormat: string, formatter: any): string {\n  return color ? formatter[color](strToFormat) : strToFormat;\n}\n"
  },
  {
    "path": "src/reporters/console/progress-bar.ts",
    "content": "import {Stdout} from '../types.js';\nimport {clearLine, toStartOfLine} from './util.js';\n\nexport default class ProgressBar {\n  constructor(total: number, stdout: Stdout = process.stderr, callback?: (progressBar: ProgressBar) => void) {\n    this.stdout = stdout;\n    this.total = total;\n    this.chars = ProgressBar.bars[0];\n    this.delay = 60;\n    this.curr = 0;\n    this._callback = callback;\n    clearLine(stdout);\n  }\n\n  stdout: Stdout;\n  curr: number;\n  total: number;\n  width: number;\n  chars: [string, string];\n  delay: number;\n  id?: NodeJS.Timeout;\n  _callback?: (progressBar: ProgressBar) => void;\n\n  static bars: [string, string][] = [['#', '-']];\n\n  tick() {\n    if (this.curr >= this.total) {\n      return;\n    }\n\n    this.curr++;\n\n    // schedule render\n    if (!this.id) {\n      this.id = setTimeout((): void => this.render(), this.delay);\n    }\n  }\n\n  cancelTick() {\n    if (this.id) {\n      clearTimeout(this.id);\n      this.id = null;\n    }\n  }\n\n  stop() {\n    // \"stop\" by setting current to end so `tick` becomes noop\n    this.curr = this.total;\n\n    this.cancelTick();\n    clearLine(this.stdout);\n    if (this._callback) {\n      this._callback(this);\n    }\n  }\n\n  render() {\n    // clear throttle\n    this.cancelTick();\n\n    let ratio = this.curr / this.total;\n    ratio = Math.min(Math.max(ratio, 0), 1);\n\n    // progress without bar\n    let bar = ` ${this.curr}/${this.total}`;\n\n    // calculate size of actual bar\n    // $FlowFixMe: investigate process.stderr.columns flow error\n    // @ts-ignore\n    const availableSpace = Math.max(0, this.stdout.columns - bar.length - 3);\n    const width = Math.min(this.total, availableSpace);\n    const completeLength = Math.round(width * ratio);\n    const complete = this.chars[0].repeat(completeLength);\n    const incomplete = this.chars[1].repeat(width - completeLength);\n    bar = `[${complete}${incomplete}]${bar}`;\n\n    toStartOfLine(this.stdout);\n    this.stdout.write(bar);\n  }\n}\n"
  },
  {
    "path": "src/reporters/console/spinner-progress.ts",
    "content": "import {Stdout} from '../types.js';\nimport {writeOnNthLine, clearNthLine} from './util.js';\n\nexport default class Spinner {\n  constructor(stdout: Stdout = process.stderr, lineNumber: number = 0) {\n    this.current = 0;\n    this.prefix = '';\n    this.lineNumber = lineNumber;\n    this.stdout = stdout;\n    this.delay = 60;\n    this.chars = Spinner.spinners[28].split('');\n    this.text = '';\n    this.id = null;\n  }\n\n  stdout: Stdout;\n  prefix: string;\n  current: number;\n  lineNumber: number;\n  delay: number;\n  chars: Array<string>;\n  text: string;\n  id?: NodeJS.Timeout;\n\n  static spinners: Array<string> = [\n    '|/-\\\\',\n    '⠂-–—–-',\n    '◐◓◑◒',\n    '◴◷◶◵',\n    '◰◳◲◱',\n    '▖▘▝▗',\n    '■□▪▫',\n    '▌▀▐▄',\n    '▉▊▋▌▍▎▏▎▍▌▋▊▉',\n    '▁▃▄▅▆▇█▇▆▅▄▃',\n    '←↖↑↗→↘↓↙',\n    '┤┘┴└├┌┬┐',\n    '◢◣◤◥',\n    '.oO°Oo.',\n    '.oO@*',\n    '🌍🌎🌏',\n    '◡◡ ⊙⊙ ◠◠',\n    '☱☲☴',\n    '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏',\n    '⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓',\n    '⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆',\n    '⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋',\n    '⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁',\n    '⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈',\n    '⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈',\n    '⢄⢂⢁⡁⡈⡐⡠',\n    '⢹⢺⢼⣸⣇⡧⡗⡏',\n    '⣾⣽⣻⢿⡿⣟⣯⣷',\n    '⠁⠂⠄⡀⢀⠠⠐⠈',\n  ];\n  setPrefix(prefix: string) {\n    this.prefix = prefix;\n  }\n  setText(text: string) {\n    this.text = text;\n  }\n  start() {\n    this.current = 0;\n    this.render();\n  }\n  render() {\n    if (this.id) {\n      clearTimeout(this.id);\n    }\n    // build line ensuring we don't wrap to the next line\n    let msg = `${this.prefix}${this.chars[this.current]} ${this.text}`;\n    // @ts-ignore\n    const columns = typeof this.stdout.columns === 'number' ? this.stdout.columns : 100;\n    msg = msg.slice(0, columns);\n    writeOnNthLine(this.stdout, this.lineNumber, msg);\n    this.current = ++this.current % this.chars.length;\n    this.id = setTimeout((): void => this.render(), this.delay);\n  }\n  stop() {\n    if (this.id) {\n      clearTimeout(this.id);\n      this.id = null;\n    }\n    clearNthLine(this.stdout, this.lineNumber);\n  }\n}\n"
  },
  {
    "path": "src/reporters/console/util.ts",
    "content": "import * as tty from 'tty';\nimport {Stdout} from '../types.js';\n\nimport * as readline from 'readline';\nimport chalk from 'chalk';\n\nconst CLEAR_WHOLE_LINE = 0;\nconst CLEAR_RIGHT_OF_CURSOR = 1;\n\nexport function clearLine(stdout: Stdout) {\n  if (!chalk.supportsColor) {\n    if (stdout instanceof tty.WriteStream) {\n      if (stdout.columns > 0) {\n        stdout.write(`\\r${' '.repeat(stdout.columns - 1)}`);\n      }\n      stdout.write(`\\r`);\n    }\n    return;\n  }\n\n  readline.clearLine(stdout, CLEAR_WHOLE_LINE);\n  readline.cursorTo(stdout, 0);\n}\n\nexport function toStartOfLine(stdout: Stdout) {\n  if (!chalk.supportsColor) {\n    stdout.write('\\r');\n    return;\n  }\n\n  readline.cursorTo(stdout, 0);\n}\n\nexport function writeOnNthLine(stdout: Stdout, n: number, msg: string) {\n  if (!chalk.supportsColor) {\n    return;\n  }\n\n  if (n == 0) {\n    readline.cursorTo(stdout, 0);\n    stdout.write(msg);\n    readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);\n    return;\n  }\n  readline.cursorTo(stdout, 0);\n  readline.moveCursor(stdout, 0, -n);\n  stdout.write(msg);\n  readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);\n  readline.cursorTo(stdout, 0);\n  readline.moveCursor(stdout, 0, n);\n}\n\nexport function clearNthLine(stdout: Stdout, n: number) {\n  if (!chalk.supportsColor) {\n    return;\n  }\n\n  if (n == 0) {\n    clearLine(stdout);\n    return;\n  }\n  readline.cursorTo(stdout, 0);\n  readline.moveCursor(stdout, 0, -n);\n  readline.clearLine(stdout, CLEAR_WHOLE_LINE);\n  readline.moveCursor(stdout, 0, n);\n}\n"
  },
  {
    "path": "src/reporters/format.ts",
    "content": "function formatFunction(...strs: Array<string>): string {\n  return strs.join(' ');\n}\n\nexport const defaultFormatter = {\n  bold: formatFunction,\n  dim: formatFunction,\n  italic: formatFunction,\n  underline: formatFunction,\n  inverse: formatFunction,\n  strikethrough: formatFunction,\n  black: formatFunction,\n  red: formatFunction,\n  green: formatFunction,\n  yellow: formatFunction,\n  blue: formatFunction,\n  magenta: formatFunction,\n  cyan: formatFunction,\n  white: formatFunction,\n  gray: formatFunction,\n  grey: formatFunction,\n  stripColor: formatFunction,\n};\n\ntype FormatFunction = (...strs: Array<string>) => string;\n\nexport type FormatKeys = keyof typeof defaultFormatter;\n\nexport type Formatter = {\n  bold: FormatFunction;\n  dim: FormatFunction;\n  italic: FormatFunction;\n  underline: FormatFunction;\n  inverse: FormatFunction;\n  strikethrough: FormatFunction;\n  black: FormatFunction;\n  red: FormatFunction;\n  green: FormatFunction;\n  yellow: FormatFunction;\n  blue: FormatFunction;\n  magenta: FormatFunction;\n  cyan: FormatFunction;\n  white: FormatFunction;\n  gray: FormatFunction;\n  grey: FormatFunction;\n  stripColor: FormatFunction;\n};\n"
  },
  {
    "path": "src/reporters/index.ts",
    "content": "export {default as ConsoleReporter} from './console/console-reporter';\nexport {default as JSONReporter} from './json-reporter';\nexport {default as NoopReporter} from './noop-reporter';\nexport {default as Reporter} from './base-reporter';\n"
  },
  {
    "path": "src/reporters/json-reporter.ts",
    "content": "import {ReporterSpinnerSet, Trees, ReporterSpinner} from './types.js';\nimport BaseReporter from './base-reporter.js';\n\nexport default class JSONReporter extends BaseReporter {\n  constructor(opts?: Object) {\n    super(opts);\n\n    this._activityId = 0;\n    this._progressId = 0;\n  }\n\n  _activityId: number;\n  _progressId: number;\n\n  _dump(type: string, data: any, error?: boolean) {\n    let stdout = this.stdout;\n    if (error) {\n      stdout = this.stderr;\n    }\n    stdout.write(`${JSON.stringify({type, data})}\\n`);\n  }\n\n  _verbose(msg: string) {\n    this._dump('verbose', msg);\n  }\n\n  list(type: string, items: Array<string>, hints?: Object) {\n    this._dump('list', {type, items, hints});\n  }\n\n  tree(type: string, trees: Trees) {\n    this._dump('tree', {type, trees});\n  }\n\n  step(current: number, total: number, message: string) {\n    this._dump('step', {message, current, total});\n  }\n\n  inspect(value: any) {\n    this._dump('inspect', value);\n  }\n\n  footer(showPeakMemory: boolean) {\n    this._dump('finished', this.getTotalTime());\n  }\n\n  log(msg: string) {\n    this._dump('log', msg);\n  }\n\n  command(msg: string) {\n    this._dump('command', msg);\n  }\n\n  table(head: Array<string>, body: Array<Array<string>>) {\n    this._dump('table', {head, body});\n  }\n\n  success(msg: string) {\n    this._dump('success', msg);\n  }\n\n  error(msg: string) {\n    this._dump('error', msg, true);\n  }\n\n  warn(msg: string) {\n    this._dump('warning', msg, true);\n  }\n\n  info(msg: string) {\n    this._dump('info', msg);\n  }\n\n  activitySet(total: number, workers: number): ReporterSpinnerSet {\n    if (!this.isTTY || this.noProgress) {\n      return super.activitySet(total, workers);\n    }\n\n    const id = this._activityId++;\n    this._dump('activitySetStart', {id, total, workers});\n\n    const spinners = [];\n    for (let i = 0; i < workers; i++) {\n      let current = 0;\n      let header = '';\n\n      spinners.push({\n        clear() {},\n        setPrefix(_current: number, _header: string) {\n          current = _current;\n          header = _header;\n        },\n        tick: (msg) => {\n          this._dump('activitySetTick', {\n            id,\n            header,\n            current,\n            worker: i,\n            message: msg,\n          });\n        },\n        end() {},\n      });\n    }\n\n    return {\n      spinners,\n      end: () => {\n        this._dump('activitySetEnd', {id});\n      },\n    };\n  }\n\n  activity(): ReporterSpinner {\n    return this._activity({});\n  }\n\n  _activity(data: Object): ReporterSpinner {\n    if (!this.isTTY || this.noProgress) {\n      return {\n        tick() {},\n        end() {},\n      };\n    }\n\n    const id = this._activityId++;\n    this._dump('activityStart', {id, ...data});\n\n    return {\n      tick: (name: string) => {\n        this._dump('activityTick', {id, name});\n      },\n\n      end: () => {\n        this._dump('activityEnd', {id});\n      },\n    };\n  }\n\n  progress(total: number): () => void {\n    if (this.noProgress) {\n      return function () {\n        // noop\n      };\n    }\n\n    const id = this._progressId++;\n    let current = 0;\n    this._dump('progressStart', {id, total});\n\n    return () => {\n      current++;\n      this._dump('progressTick', {id, current});\n\n      if (current === total) {\n        this._dump('progressFinish', {id});\n      }\n    };\n  }\n}\n"
  },
  {
    "path": "src/reporters/lang/en.ts",
    "content": "const messages = {\n  upToDate: 'Already up-to-date.',\n  folderInSync: 'Folder in sync.',\n  nothingToInstall: 'Nothing to install.',\n  resolvingPackages: 'Resolving packages',\n  checkingManifest: 'Validating package.json',\n  fetchingPackages: 'Fetching packages',\n  linkingDependencies: 'Linking dependencies',\n  rebuildingPackages: 'Rebuilding all packages',\n  buildingFreshPackages: 'Building fresh packages',\n  cleaningModules: 'Cleaning modules',\n  bumpingVersion: 'Bumping version',\n  savingHar: 'Saving HAR file: $0',\n  answer: 'Answer?',\n  usage: 'Usage',\n  installCommandRenamed: '`install` has been replaced with `add` to add new dependencies. Run $0 instead.',\n  globalFlagRemoved: '`--global` has been deprecated. Please run $0 instead.',\n  waitingInstance: 'Waiting for the other pika instance to finish (pid $0, inside $1)',\n  waitingNamedInstance: 'Waiting for the other pika instance to finish ($0)',\n  offlineRetrying: 'There appears to be trouble with your network connection. Retrying...',\n  internalServerErrorRetrying: 'There appears to be trouble with the npm registry (returned $1). Retrying...',\n  clearedCache: 'Cleared cache.',\n  couldntClearPackageFromCache: \"Couldn't clear package $0 from cache\",\n  clearedPackageFromCache: 'Cleared package $0 from cache',\n  packWroteTarball: 'Wrote tarball to $0.',\n\n  helpExamples: '  Examples:\\n$0\\n',\n  helpCommands: '  Commands:\\n$0\\n',\n  helpCommandsMore: '  Run `$0` for more information on specific commands.',\n  helpLearnMore: '  Visit $0 to learn more about Pika.\\n',\n\n  manifestPotentialTypo: 'Potential typo $0, did you mean $1?',\n  manifestBuiltinModule: '$0 is also the name of a node core module',\n  manifestNameDot: \"Name can't start with a dot\",\n  manifestNameIllegalChars: 'Name contains illegal characters',\n  manifestNameBlacklisted: 'Name is blacklisted',\n  manifestLicenseInvalid: 'License should be a valid SPDX license expression',\n  manifestLicenseNone: 'No license field',\n  manifestStringExpected: '$0 is not a string',\n  manifestDependencyCollision:\n    '$0 has dependency $1 with range $2 that collides with a dependency in $3 of the same name with version $4',\n  manifestDirectoryNotFound: 'Unable to read $0 directory of module $1',\n\n  verboseFileCopy: 'Copying $0 to $1.',\n  verboseFileLink: 'Creating hardlink at $0 to $1.',\n  verboseFileSymlink: 'Creating symlink at $0 to $1.',\n  verboseFileSkip: 'Skipping copying of file $0 as the file at $1 is the same size ($2) and mtime ($3).',\n  verboseFileSkipSymlink: 'Skipping copying of $0 as the file at $1 is the same symlink ($2).',\n  verboseFileSkipHardlink: 'Skipping copying of $0 as the file at $1 is the same hardlink ($2).',\n  verboseFileRemoveExtraneous: 'Removing extraneous file $0.',\n  verboseFilePhantomExtraneous:\n    \"File $0 would be marked as extraneous but has been removed as it's listed as a phantom file.\",\n  verboseFileSkipArtifact: 'Skipping copying of $0 as the file is marked as a built artifact and subject to change.',\n  verboseFileFolder: 'Creating directory $0.',\n\n  verboseRequestStart: 'Performing $0 request to $1.',\n  verboseRequestFinish: 'Request $0 finished with status code $1.',\n\n  configSet: 'Set $0 to $1.',\n  configDelete: 'Deleted $0.',\n  configNpm: 'npm config',\n  configPika: 'pika config',\n\n  couldntFindPackagejson: \"Couldn't find a package.json file in $0\",\n  couldntFindMatch: \"Couldn't find match for $0 in $1 for $2.\",\n  couldntFindPackageInCache:\n    \"Couldn't find any versions for $0 that matches $1 in our cache (possible versions are $2). This is usually caused by a missing entry in the lockfile, running Pika without the --offline flag may help fix this issue.\",\n  couldntFindVersionThatMatchesRange: \"Couldn't find any versions for $0 that matches $1\",\n  chooseVersionFromList: 'Please choose a version of $0 from this list:',\n  moduleNotInManifest: \"This module isn't specified in a package.json file.\",\n  moduleAlreadyInManifest: '$0 is already in $1. Please remove existing entry first before adding it to $2.',\n  unknownFolderOrTarball: \"Passed folder/tarball doesn't exist,\",\n  unknownPackage: \"Couldn't find package $0.\",\n  unknownPackageName: \"Couldn't find package name.\",\n  unknownUser: \"Couldn't find user $0.\",\n  unknownRegistryResolver: 'Unknown registry resolver $0',\n  userNotAnOwner: \"User $0 isn't an owner of this package.\",\n  invalidVersionArgument: 'Use the $0 flag to create a new version.',\n  invalidVersion: 'Invalid version supplied.',\n  requiredVersionInRange: 'Required version in range.',\n  packageNotFoundRegistry: \"Couldn't find package $0 on the $1 registry.\",\n  requiredPackageNotFoundRegistry: \"Couldn't find package $0 required by $1 on the $2 registry.\",\n  doesntExist: \"Package $1 refers to a non-existing file '$0'.\",\n  missingRequiredPackageKey: `Package $0 doesn't have a $1.`,\n  invalidAccess: 'Invalid argument for access, expected public or restricted.',\n  invalidCommand: 'Invalid subcommand. Try $0',\n  invalidGistFragment: 'Invalid gist fragment $0.',\n  invalidHostedGitFragment: 'Invalid hosted git fragment $0.',\n  invalidFragment: 'Invalid fragment $0.',\n  invalidPackageName: 'Invalid package name.',\n  invalidPackageVersion: \"Can't add $0: invalid package version $1.\",\n  couldntFindManifestIn: \"Couldn't find manifest in $0.\",\n  shrinkwrapWarning:\n    'npm-shrinkwrap.json found. This will not be updated or respected. See https://yarnpkg.com/en/docs/migrating-from-npm for more information.',\n  npmLockfileWarning:\n    'package-lock.json found. Your project contains lock files generated by tools other than Pika. It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files. To clear this warning, remove package-lock.json.',\n  lockfileOutdated: 'Outdated lockfile. Please run `pika install` and try again.',\n  lockfileMerged: 'Merge conflict detected in pika.lock and successfully merged.',\n  lockfileConflict:\n    'A merge conflict was found in pika.lock but it could not be successfully merged, regenerating pika.lock from scratch.',\n  ignoredScripts: 'Ignored scripts due to flag.',\n  missingAddDependencies: 'Missing list of packages to add to your project.',\n  yesWarning:\n    'The yes flag has been set. This will automatically answer yes to all questions, which may have security implications.',\n  networkWarning:\n    \"You don't appear to have an internet connection. Try the --offline flag to use the cache for registry queries.\",\n  flatGlobalError:\n    'The package $0 requires a flat dependency graph. Add `\"flat\": true` to your package.json and try again.',\n  noName: `Package doesn't have a name.`,\n  noVersion: `Package doesn't have a version.`,\n  answerRequired: 'An answer is required.',\n  missingWhyDependency: 'Missing package name, folder or path to file to identify why a package has been installed',\n  bugReport: 'If you think this is a bug, please open a bug report with the information provided in $0.',\n  unexpectedError: 'An unexpected error occurred: $0.',\n  jsonError: 'Error parsing JSON at $0, $1.',\n  noPermission: 'Cannot create $0 due to insufficient permissions.',\n  noGlobalFolder: 'Cannot find a suitable global folder. Tried these: $0',\n  allDependenciesUpToDate: 'All of your dependencies are up to date.',\n  legendColorsForVersionUpdates:\n    'Color legend : \\n $0    : Major Update backward-incompatible updates \\n $1 : Minor Update backward-compatible features \\n $2  : Patch Update backward-compatible bug fixes',\n  frozenLockfileError: 'Your lockfile needs to be updated, but pika was run with `--frozen-lockfile`.',\n  fileWriteError: 'Could not write file $0: $1',\n  fileDeleteError: 'Could not delete file $0: $1',\n  multiplePackagesCantUnpackInSameDestination:\n    'Pattern $0 is trying to unpack in the same destination $1 as pattern $2. This could result in non-deterministic behavior, skipping.',\n  incorrectLockfileEntry: 'Lockfile has incorrect entry for $0. Ignoring it.',\n\n  invalidResolutionName: 'Resolution field $0 does not end with a valid package name and will be ignored',\n  invalidResolutionVersion: 'Resolution field $0 has an invalid version entry and may be ignored',\n  incompatibleResolutionVersion: 'Resolution field $0 is incompatible with requested version $1',\n\n  pikaOutdated: \"Your current version of Pika is out of date. The latest version is $0, while you're on $1.\",\n  pikaOutdatedInstaller: 'To upgrade, download the latest installer at $0.',\n  pikaOutdatedCommand: 'To upgrade, run the following command:',\n\n  tooManyArguments: 'Too many arguments, maximum of $0.',\n  tooFewArguments: 'Not enough arguments, expected at least $0.',\n  noArguments: \"This command doesn't require any arguments.\",\n\n  ownerRemoving: 'Removing owner $0 from package $1.',\n  ownerRemoved: 'Owner removed.',\n  ownerRemoveError: \"Couldn't remove owner.\",\n  ownerGetting: 'Getting owners for package $0',\n  ownerGettingFailed: \"Couldn't get list of owners.\",\n  ownerAlready: 'This user is already an owner of this package.',\n  ownerAdded: 'Added owner.',\n  ownerAdding: 'Adding owner $0 to package $1',\n  ownerAddingFailed: \"Couldn't add owner.\",\n  ownerNone: 'No owners.',\n\n  teamCreating: 'Creating team',\n  teamRemoving: 'Removing team',\n  teamAddingUser: 'Adding user to team',\n  teamRemovingUser: 'Removing user from team',\n  teamListing: 'Listing teams',\n\n  distFailed: `⚠️  Distribution \"$0\" failed to build: $1 $2`,\n  distExiting: `   Exiting...`,\n  distContinuing: `   Continuing...`,\n\n  cleaning: 'Cleaning modules',\n  cleanCreatingFile: 'Creating $0',\n  cleanCreatedFile:\n    'Created $0. Please review the contents of this file then run \"pika autoclean --force\" to perform a clean.',\n  cleanAlreadyExists: '$0 already exists. To revert to the default file, delete $0 then rerun this command.',\n  cleanRequiresForce:\n    'This command required the \"--force\" flag to perform the clean. This is a destructive operation. Files specified in $0 will be deleted.',\n  cleanDoesNotExist:\n    '$0 does not exist. Autoclean will delete files specified by $0. Run \"autoclean --init\" to create $0 with the default entries.',\n\n  binLinkCollision:\n    \"There's already a linked binary called $0 in your global Pika bin. Could not link this package's $0 bin entry.\",\n  linkCollision:\n    \"There's already a package called $0 registered. This command has had no effect. If this command was run in another folder with the same name, the other folder is still linked. Please run pika unlink in the other folder if you want to register this folder.\",\n  linkMissing: 'No registered package found called $0.',\n  linkRegistered: 'Registered $0.',\n  linkRegisteredMessage:\n    'You can now run `pika link $0` in the projects where you want to use this package and it will be used instead.',\n  linkUnregistered: 'Unregistered $0.',\n  linkUnregisteredMessage:\n    'You can now run `pika unlink $0` in the projects where you no longer want to use this package.',\n  linkUsing: 'Using linked package for $0.',\n  linkDisusing: 'Removed linked package $0.',\n  linkDisusingMessage: 'You will need to run `pika` to re-install the package that was linked.',\n  linkTargetMissing: 'The target of linked package $0 is missing. Removing link.',\n\n  createInvalidBin: 'Invalid bin entry found in package $0.',\n  createMissingPackage:\n    'Package not found - this is probably an internal error, and should be reported at https://github.com/yarnpkg/yarn/issues.',\n\n  workspacesAddRootCheck:\n    'Running this command will add the dependency to the workspace root rather than the workspace itself, which might not be what you want - if you really meant it, make it explicit by running this command again with the -W flag (or --ignore-workspace-root-check).',\n  workspacesRemoveRootCheck:\n    'Running this command will remove the dependency from the workspace root rather than the workspace itself, which might not be what you want - if you really meant it, make it explicit by running this command again with the -W flag (or --ignore-workspace-root-check).',\n  workspacesFocusRootCheck: 'This command can only be run inside an individual workspace.',\n  workspacesRequirePrivateProjects: 'Workspaces can only be enabled in private projects.',\n  workspacesSettingMustBeArray: 'The workspaces field in package.json must be an array.',\n  workspacesDisabled:\n    'Your project root defines workspaces but the feature is disabled in your Pika config. Please check \"workspaces-experimental\" in your .pikarc file.',\n\n  workspacesNohoistRequirePrivatePackages:\n    'nohoist config is ignored in $0 because it is not a private package. If you think nohoist should be allowed in public packages, please submit an issue for your use case.',\n  workspacesNohoistDisabled: `$0 defines nohoist but the feature is disabled in your Pika config (\"workspaces-nohoist-experimental\" in .pikarc file)`,\n\n  workspaceRootNotFound: \"Cannot find the root of your workspace - are you sure you're currently in a workspace?\",\n  workspaceMissingWorkspace: 'Missing workspace name.',\n  workspaceMissingCommand: 'Missing command name.',\n  workspaceUnknownWorkspace: 'Unknown workspace $0.',\n  workspaceVersionMandatory: 'Missing version in workspace at $0, ignoring.',\n  workspaceNameMandatory: 'Missing name in workspace at $0, ignoring.',\n  workspaceNameDuplicate: 'There are more than one workspace with name $0',\n\n  cacheFolderSkipped: 'Skipping preferred cache folder $0 because it is not writable.',\n  cacheFolderMissing:\n    \"Pika hasn't been able to find a cache folder it can use. Please use the explicit --cache-folder option to tell it what location to use, or make one of the preferred locations writable.\",\n  cacheFolderSelected: 'Selected the next writable cache folder in the list, will be $0.',\n\n  execMissingCommand: 'Missing command name.',\n\n  noScriptsAvailable: 'There are no scripts specified inside package.json.',\n  noBinAvailable: 'There are no binary scripts available.',\n  dashDashDeprecation: `From Pika 1.0 onwards, scripts don't require \"--\" for options to be forwarded. In a future version, any explicit \"--\" will be forwarded as-is to the scripts.`,\n  commandNotSpecified: 'No command specified.',\n  binCommands: 'Commands available from binary scripts: ',\n  possibleCommands: 'Project commands',\n  commandQuestion: 'Which command would you like to run?',\n  commandFailedWithCode: 'Command failed with exit code $0.',\n  commandFailedWithSignal: 'Command failed with signal $0.',\n  packageRequiresNodeGyp:\n    'This package requires node-gyp, which is not currently installed. Pika will attempt to automatically install it. If this fails, you can run \"pika global add node-gyp\" to manually install it.',\n  nodeGypAutoInstallFailed:\n    'Failed to auto-install node-gyp. Please run \"pika global add node-gyp\" manually. Error: $0',\n\n  foundIncompatible: 'Found incompatible module',\n  incompatibleEngine: 'The engine $0 is incompatible with this module. Expected version $1. Got $2',\n  incompatibleCPU: 'The CPU architecture $0 is incompatible with this module.',\n  incompatibleOS: 'The platform $0 is incompatible with this module.',\n  invalidEngine: 'The engine $0 appears to be invalid.',\n\n  optionalCompatibilityExcluded:\n    '$0 is an optional dependency and failed compatibility check. Excluding it from installation.',\n  optionalModuleFail: 'This module is OPTIONAL, you can safely ignore this error',\n  optionalModuleScriptFail: 'Error running install script for optional dependency: $0',\n  optionalModuleCleanupFail: 'Could not cleanup build artifacts from failed install: $0',\n\n  unmetPeer: '$0 has unmet peer dependency $1.',\n  incorrectPeer: '$0 has incorrect peer dependency $1.',\n  selectedPeer: 'Selecting $1 at level $2 as the peer dependency of $0.',\n  missingBundledDependency: '$0 is missing a bundled dependency $1. This should be reported to the package maintainer.',\n\n  savedNewDependency: 'Saved 1 new dependency.',\n  savedNewDependencies: 'Saved $0 new dependencies.',\n  directDependencies: 'Direct dependencies',\n  allDependencies: 'All dependencies',\n\n  foundWarnings: 'Found $0 warnings.',\n  foundErrors: 'Found $0 errors.',\n\n  savedLockfile: 'Saved lockfile.',\n  noRequiredLockfile: 'No lockfile in this directory. Run `pika install` to generate one.',\n  noLockfileFound: 'No lockfile found.',\n\n  invalidSemver: 'Invalid semver version',\n  newVersion: 'New version',\n  currentVersion: 'Current version',\n  noVersionOnPublish: 'Proceeding with current version',\n\n  manualVersionResolution:\n    'Unable to find a suitable version for $0, please choose one by typing one of the numbers below:',\n  manualVersionResolutionOption: '$0 which resolved to $1',\n\n  createdTag: 'Created tag.',\n  createdTagFail: \"Couldn't add tag.\",\n  deletedTag: 'Deleted tag.',\n  deletedTagFail: \"Couldn't delete tag.\",\n  gettingTags: 'Getting tags',\n  deletingTags: 'Deleting tag',\n  creatingTag: 'Creating tag $0 = $1',\n\n  whyStart: 'Why do we have the module $0?',\n  whyFinding: 'Finding dependency',\n  whyCalculating: 'Calculating file sizes',\n  whyUnknownMatch: \"We couldn't find a match!\",\n  whyInitGraph: 'Initialising dependency graph',\n  whyWhoKnows: \"We don't know why this module exists\",\n  whyDiskSizeWithout: 'Disk size without dependencies: $0',\n  whyDiskSizeUnique: 'Disk size with unique dependencies: $0',\n  whyDiskSizeTransitive: 'Disk size with transitive dependencies: $0',\n  whySharedDependencies: 'Number of shared dependencies: $0',\n  whyHoistedTo: `Has been hoisted to $0`,\n\n  whyHoistedFromSimple: `This module exists because it's hoisted from $0.`,\n  whyNotHoistedSimple: `This module exists here because it's in the nohoist list $0.`,\n  whyDependedOnSimple: `This module exists because $0 depends on it.`,\n  whySpecifiedSimple: `This module exists because it's specified in $0.`,\n  whyReasons: 'Reasons this module exists',\n  whyHoistedFrom: 'Hoisted from $0',\n  whyNotHoisted: `in the nohoist list $0`,\n  whyDependedOn: '$0 depends on it',\n  whySpecified: `Specified in $0`,\n\n  whyMatch: `\\r=> Found $0`,\n\n  uninstalledPackages: 'Uninstalled packages.',\n  uninstallRegenerate: 'Regenerating lockfile and installing missing dependencies',\n\n  cleanRemovedFiles: 'Removed $0 files',\n  cleanSavedSize: 'Saved $0 MB.',\n\n  configFileFound: 'Found configuration file $0.',\n  configPossibleFile: 'Checking for configuration file $0.',\n\n  npmUsername: 'npm username',\n  npmPassword: 'npm password',\n  npmEmail: 'npm email',\n  npmOneTimePassword: 'npm one-time password',\n\n  loggingIn: 'Logging in',\n  loggedIn: 'Logged in.',\n  notRevokingEnvToken: 'Not revoking login token, specified via environment variable.',\n  notRevokingConfigToken: 'Not revoking login token, specified via config file.',\n  noTokenToRevoke: 'No login token to revoke.',\n  revokingToken: 'Revoking token',\n  revokedToken: 'Revoked login token.',\n\n  loginAsPublic: 'Logging in as public',\n  incorrectCredentials: 'Incorrect username or password.',\n  incorrectOneTimePassword: 'Incorrect one-time password.',\n  twoFactorAuthenticationEnabled: 'Two factor authentication enabled.',\n  clearedCredentials: 'Cleared login credentials.',\n\n  publishFail: \"Couldn't publish package: $0\",\n  publishPrivate: 'Package marked as private, not publishing.',\n  published: 'Published.',\n  publishing: 'Publishing',\n\n  nonInteractiveNoVersionSpecified:\n    'You must specify a new version with --new-version when running with --non-interactive.',\n  nonInteractiveNoToken: \"No token found and can't prompt for login when running with --non-interactive.\",\n\n  infoFail: 'Received invalid response from npm.',\n  malformedRegistryResponse: 'Received malformed response from registry for $0. The registry may be down.',\n  registryNoVersions: 'No valid versions found for $0. The package may be unpublished.',\n\n  cantRequestOffline: \"Can't make a request in offline mode ($0)\",\n  requestManagerNotSetupHAR: 'RequestManager was not setup to capture HAR files',\n  requestError: 'Request $0 returned a $1',\n  requestFailed: 'Request failed $0',\n  tarballNotInNetworkOrCache: '$0: Tarball is not in network and can not be located in cache ($1)',\n  fetchBadHashWithPath: \"Integrity check failed for $0 (computed integrity doesn't match our records, got $2)\",\n  fetchBadIntegrityAlgorithm: 'Integrity checked failed for $0 (none of the specified algorithms are supported)',\n  fetchErrorCorrupt:\n    '$0. Mirror tarball appears to be corrupt. You can resolve this by running:\\n\\n  rm -rf $1\\n  pika install',\n  errorExtractingTarball: 'Extracting tar content of $1 failed, the file appears to be corrupt: $0',\n  updateInstalling: 'Installing $0...',\n  hostedGitResolveError: 'Error connecting to repository. Please, check the url.',\n\n  unknownFetcherFor: 'Unknown fetcher for $0',\n\n  downloadGitWithoutCommit: 'Downloading the git repo $0 over plain git without a commit hash',\n  downloadHTTPWithoutCommit: 'Downloading the git repo $0 over HTTP without a commit hash',\n\n  unplugDisabled: \"Packages can only be unplugged when Plug'n'Play is enabled.\",\n\n  plugnplayWindowsSupport: \"Plug'n'Play on Windows doesn't support the cache and project to be kept on separate drives\",\n\n  packageInstalledWithBinaries: 'Installed $0 with binaries:',\n  packageHasBinaries: '$0 has binaries:',\n  packageHasNoBinaries: '$0 has no binaries',\n  packageBinaryNotFound: \"Couldn't find a binary named $0\",\n\n  couldBeDeduped: '$0 could be deduped from $1 to $2',\n  lockfileNotContainPattern: 'Lockfile does not contain pattern: $0',\n  integrityCheckFailed: 'Integrity check failed',\n  noIntegrityFile: \"Couldn't find an integrity file\",\n  integrityFailedExpectedIsNotAJSON: 'Integrity check: integrity file is not a json',\n  integrityCheckLinkedModulesDontMatch: \"Integrity check: Linked modules don't match\",\n  integrityFlagsDontMatch: \"Integrity check: Flags don't match\",\n  integrityLockfilesDontMatch: \"Integrity check: Lock files don't match\",\n  integrityFailedFilesMissing: 'Integrity check: Files are missing',\n  integrityPatternsDontMatch: \"Integrity check: Top level patterns don't match\",\n  integrityModulesFoldersMissing: 'Integrity check: Some module folders are missing',\n  integritySystemParamsDontMatch: \"Integrity check: System parameters don't match\",\n  packageNotInstalled: '$0 not installed',\n  optionalDepNotInstalled: 'Optional dependency $0 not installed',\n  packageWrongVersion: '$0 is wrong version: expected $1, got $2',\n  packageDontSatisfy: \"$0 doesn't satisfy found match of $1\",\n\n  lockfileExists: 'Lockfile already exists, not migrating.',\n  pikaManifestExists: 'pika.package.json manifest already exists, not migrating.',\n  noManifestExists: 'No package.json manifest found. Run `pika init` to generate a new pika.package.json manifest.',\n  skippingImport: 'Skipping import of $0 for $1',\n  importFailed: 'Import of $0 for $1 failed, resolving normally.',\n  importResolveFailed: 'Import of $0 failed starting in $1',\n  importResolvedRangeMatch: 'Using version $0 of $1 instead of $2 for $3',\n  importSourceFilesCorrupted: 'Failed to import from package-lock.json, source file(s) corrupted',\n  importPackageLock: 'found npm package-lock.json, converting to pika.lock',\n  importYarnLock: 'found yarn.lock, converting to pika.lock',\n  importNodeModules: 'creating pika.lock from local node_modules folder',\n  packageContainsPikaAsGlobal:\n    'Installing Pika via Pika will result in you having two separate versions of Pika installed at the same time, which is not recommended. To update Pika please follow https://yarnpkg.com/en/docs/install .',\n\n  watchStarting: `Starting up`,\n  watchRunning: `Ready! Watching source tree for changes`,\n  watchRebuild: `Rebuilding...`,\n  watchError: `Build error!`,\n\n  noValidationErrors: `0 Validation Errors found.`,\n  validationErrors: `$0 Validation Error(s) found. Resolve before publishing.`,\n\n  scopeNotValid: 'The specified scope is not valid.',\n\n  deprecatedCommand: '$0 is deprecated. Please use $1.',\n  deprecatedListArgs: 'Filtering by arguments is deprecated. Please use the pattern option instead.',\n  implicitFileDeprecated:\n    'Using the \"file:\" protocol implicitly is deprecated. Please either prepend the protocol or prepend the path $0 with \"./\".',\n  unsupportedNodeVersion:\n    'You are using Node $0 which is not supported and may encounter bugs or unexpected behavior. Pika supports the following semver range: $1',\n\n  verboseUpgradeBecauseRequested: 'Considering upgrade of $0 to $1 because it was directly requested.',\n  verboseUpgradeBecauseOutdated: 'Considering upgrade of $0 to $1 because a newer version exists in the registry.',\n  verboseUpgradeNotUnlocking: 'Not unlocking $0 in the lockfile because it is a new or direct dependency.',\n  verboseUpgradeUnlocking: 'Unlocking $0 in the lockfile.',\n  folderMissing: \"Directory $0 doesn't exist\",\n  mutexPortBusy: 'Cannot use the network mutex on port $0. It is probably used by another app.',\n\n  auditRunning: 'Auditing packages',\n  auditSummary: '$0 vulnerabilities found - Packages audited: $1',\n  auditSummarySeverity: 'Severity:',\n  auditCritical: '$0 Critical',\n  auditHigh: '$0 High',\n  auditModerate: '$0 Moderate',\n  auditLow: '$0 Low',\n  auditInfo: '$0 Info',\n  auditResolveCommand: '# Run $0 to resolve $1 $2',\n  auditSemverMajorChange: 'SEMVER WARNING: Recommended action is a potentially breaking change',\n  auditManualReview:\n    'Manual Review\\nSome vulnerabilities require your attention to resolve\\n\\nVisit https://go.npm.me/audit-guide for additional guidance',\n  auditRunAuditForDetails: 'Security audit found potential problems. Run \"pika audit\" for additional details.',\n  auditOffline: 'Skipping audit. Security audit cannot be performed in offline mode.',\n};\n\nexport type LanguageKeys = keyof typeof messages;\nexport default messages;\n"
  },
  {
    "path": "src/reporters/lang/index.ts",
    "content": "import en from './en.js';\nexport {en};\n"
  },
  {
    "path": "src/reporters/noop-reporter.ts",
    "content": "import BaseReporter from './base-reporter.js';\nimport {LanguageKeys} from './lang/en.js';\nimport {Package, ReporterSpinner, ReporterSpinnerSet, Trees} from './types.js';\n\nexport default class NoopReporter extends BaseReporter {\n  lang(key: LanguageKeys, ...args: Array<any>): string {\n    return 'do nothing';\n  }\n  verbose(msg: string) {}\n  verboseInspect(val: any) {}\n  initPeakMemoryCounter() {}\n  checkPeakMemory() {}\n  close() {}\n  getTotalTime(): number {\n    return 0;\n  }\n  list(key: string, items: Array<string>, hints?: Object) {}\n  tree(key: string, obj: Trees) {}\n  step(current: number, total: number, message: string, emoji?: string) {}\n  error(message: string) {}\n  info(message: string) {}\n  warn(message: string) {}\n  success(message: string) {}\n  log(message: string) {}\n  command(command: string) {}\n  inspect(value: any) {}\n  header(pkg: Package) {}\n  footer(showPeakMemory: boolean) {}\n  table(head: Array<string>, body: Array<Array<string>>) {}\n\n  activity(): ReporterSpinner {\n    return {\n      tick(name: string) {},\n      end() {},\n    };\n  }\n\n  activitySet(total: number, workers: number): ReporterSpinnerSet {\n    return {\n      spinners: Array(workers).fill({\n        clear() {},\n        setPrefix() {},\n        tick() {},\n        end() {},\n      }),\n      end() {},\n    };\n  }\n\n  progress(total: number): () => void {\n    return function () {};\n  }\n\n  disableProgress() {\n    this.noProgress = true;\n  }\n}\n"
  },
  {
    "path": "src/reporters/types.ts",
    "content": "import {Writable, Readable} from 'stream';\nimport {WriteStream, ReadStream} from 'fs';\n\nexport type Stdout = Writable | WriteStream;\nexport type Stdin = Readable | ReadStream;\nexport type Package = {\n  name: string;\n  version: string;\n};\n\nexport type Tree = {\n  name: string;\n  children?: Trees;\n  hint?: string;\n  hidden?: boolean;\n  color?: string;\n};\n\nexport type Trees = Array<Tree>;\n\nexport type ReporterSpinner = {\n  tick: (name: string) => void;\n  end: () => void;\n};\n\nexport type ReporterSpinnerSet = {\n  spinners: Array<ReporterSetSpinner>;\n  end: () => void;\n};\n\nexport type ReporterSetSpinner = {\n  clear: () => void;\n  setPrefix: (current: number, prefix: string) => void;\n  tick: (msg: string) => void;\n  end: () => void;\n};\n"
  },
  {
    "path": "src/types.ts",
    "content": "import {Reporter} from './reporters/index.js';\nimport Config from './config.js';\n\nexport type CLIFunction = (config: Config, reporter: Reporter, flags: Object, args: Array<string>) => CLIFunctionReturn;\n\ntype _CLIFunctionReturn = boolean;\nexport type CLIFunctionReturn = _CLIFunctionReturn | Promise<_CLIFunctionReturn>;\n\n// person object, the exploded version of a `maintainers`/`authors` field\nexport type PersonObject = {\n  email?: string;\n  name?: string;\n  url?: string;\n};\n\n// `dependencies` field in package info\ntype Dependencies = {\n  [key: string]: string;\n};\n\n// package.json\nexport type Manifest = {\n  name: string;\n  version: string;\n  description?: string;\n  keywords?: string[];\n  sideEffects?: boolean;\n\n  private?: boolean;\n\n  distributions?: any;\n\n  author?: {\n    name?: string;\n    email?: string;\n    url?: string;\n  };\n\n  homepage?: string;\n  flat?: boolean;\n  license?: string;\n  licenseText?: string;\n  noticeText?: string;\n\n  readme?: string;\n  readmeFilename?: string;\n\n  repository?: {\n    type: 'git';\n    url: string;\n  };\n\n  bugs?: {\n    url: string;\n  };\n\n  // the package reference that\n  dist?: {\n    tarball: string;\n    shasum: string;\n  };\n\n  directories?: {\n    man: string;\n    bin: string;\n  };\n\n  man?: Array<string>;\n\n  bin?: {\n    [name: string]: string;\n  };\n\n  scripts?: {\n    [name: string]: string;\n  };\n\n  engines?: {\n    [engineName: string]: string;\n  };\n\n  os?: Array<string>;\n  cpu?: Array<string>;\n\n  dependencies?: Dependencies;\n  devDependencies?: Dependencies;\n  peerDependencies?: Dependencies;\n  optionalDependencies?: Dependencies;\n\n  bundleDependencies?: Array<string>;\n  bundledDependencies?: Array<string>;\n\n  installConfig?: {\n    pnp?: boolean;\n  };\n\n  deprecated?: string;\n  files?: Array<string>;\n  main?: string;\n\n  // This flag is true when we add a new package with `pika add <mypackage>`.\n  // We need to preserve the flag because we print a list of new packages in\n  // the end of the add command\n  fresh?: boolean;\n\n  prebuiltVariants?: {[filename: string]: string};\n};\n\n// Used by outdated and upgrade-interactive\nexport type Dependency = {\n  name: string;\n  current: string;\n  wanted: string;\n  latest: string;\n  url: string;\n  hint?: string;\n  range: string;\n  upgradeTo: string;\n  workspaceName: string;\n  workspaceLoc: string;\n};\n"
  },
  {
    "path": "src/util/babel-plugin-import-rewrite.ts",
    "content": "// @flow\nimport * as nodeFs from 'fs';\nimport * as nodePath from 'path';\nimport * as url from 'url';\nimport chalk from 'chalk';\nimport {validateDynamicImportArguments} from './babel-validate-specifier.js';\n\nconst BareIdentifierFormat = /^((?:@[^\\/]+\\/)?[^\\/]+)(\\/.*)?$/;\n\nfunction log(symbol: string, fileName: string, errors: string | Array<string>) {\n  if (!Array.isArray(errors)) {\n    errors = [errors];\n  }\n  console.log(`${symbol}  `, chalk.bold(fileName));\n  for (const error of errors) {\n    console.log(`  ${chalk.dim('≫')} ${error}`);\n  }\n}\n\nexport default function transform({template, types: t}): any {\n  function rewriteImport(specifier, {opts, file}) {\n    const {deps, addExtensions} = opts;\n\n    try {\n      url.parse(specifier);\n    } catch (err) {\n      return;\n    }\n    // URL w/o protocol\n    if (specifier.substr(0, 2) === '//') {\n      return; // Leave it alone\n    }\n\n    // Local path\n    if (['.', '/'].indexOf(specifier.charAt(0)) >= 0) {\n      if (addExtensions) {\n        const extname = nodePath.extname(specifier);\n        if (extname === '.js') {\n          return;\n        }\n        if (extname) {\n          console.warn('Unexpected file extension:', specifier);\n          return;\n        }\n        const resolvedPath = nodePath.resolve(nodePath.dirname(file.opts.filename), specifier);\n        try {\n          const stat = nodeFs.lstatSync(resolvedPath);\n          if (stat.isDirectory()) {\n            return specifier + '/index';\n          }\n        } catch (err) {\n          // do nothing\n        }\n        return specifier + '.js';\n      }\n      return;\n    }\n\n    // A 'bare' identifier\n    const match = BareIdentifierFormat.exec(specifier);\n    if (deps && match) {\n      const packageName = match[1];\n      // const file = match[2] || '';\n      return deps[packageName];\n    }\n  }\n\n  return {\n    visitor: {\n      'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration'(path, {opts, file}) {\n        if (!path.node.source) {\n          return;\n        }\n        const rewrittenSpecifier = rewriteImport(path.node.source.value, {opts, file});\n        if (rewrittenSpecifier) {\n          path.node.source.value = rewrittenSpecifier;\n        }\n      },\n      Import(path, {opts, file}) {\n        const errors = validateDynamicImportArguments(path);\n        if (errors.size > 0) {\n          return;\n        }\n\n        const [importPath] = path.parent.arguments;\n        const rewrittenSpecifier = rewriteImport(importPath.value, {opts, file});\n        if (rewrittenSpecifier) {\n          importPath.value = rewrittenSpecifier;\n        }\n      },\n    },\n  };\n}\n"
  },
  {
    "path": "src/util/babel-validate-specifier.ts",
    "content": "// @flow\nimport chalk from 'chalk';\n\nfunction getLineCol(node: any): string {\n  const loc = node.loc.start;\n  return chalk.dim(`[${loc.line}:${loc.column}]`);\n}\n\nexport function validateDynamicImportArguments(path): Set<string> {\n  if (path.parent.arguments.length !== 1) {\n    return new Set([\n      `${getLineCol(path.node)} \"\\`import()\\` only accepts 1 argument, but got ${path.parent.arguments.length}`,\n    ]);\n  }\n  const [argNode] = path.parent.arguments;\n  if (argNode.type !== 'StringLiteral') {\n    return new Set([\n      `${getLineCol(\n        path.node,\n      )} Pika expects strings as \\`import()\\` arguments. Treating this as an absolute file path.`,\n    ]);\n  }\n  return new Set();\n}\n"
  },
  {
    "path": "src/util/blocking-queue.ts",
    "content": "import map from './map.js';\n\nexport default class BlockingQueue {\n  constructor(alias: string, maxConcurrency: number = Infinity) {\n    this.concurrencyQueue = [];\n    this.maxConcurrency = maxConcurrency;\n    this.runningCount = 0;\n    this.warnedStuck = false;\n    this.alias = alias;\n    this.first = true;\n\n    this.running = map() || {};\n    this.queue = map() || {};\n\n    this.stuckTick = this.stuckTick.bind(this);\n  }\n\n  concurrencyQueue: Array<() => void>;\n  warnedStuck: boolean;\n  maxConcurrency: number;\n  runningCount: number;\n  stuckTimer?: NodeJS.Timeout;\n  alias: string;\n  first: boolean;\n\n  queue: {\n    [key: string]: Array<{\n      factory: () => Promise<any>;\n      resolve: (val: any) => void;\n      reject: Function;\n    }>;\n  };\n\n  running: {\n    [key: string]: boolean;\n  };\n\n  stillActive() {\n    if (this.stuckTimer) {\n      clearTimeout(this.stuckTimer);\n    }\n\n    this.stuckTimer = setTimeout(this.stuckTick, 5000);\n\n    // We need to check the existence of unref because of https://github.com/facebook/jest/issues/4559\n    // $FlowFixMe: Node's setInterval returns a Timeout, not a Number\n    this.stuckTimer.unref && this.stuckTimer.unref();\n  }\n\n  stuckTick() {\n    if (this.runningCount === 1) {\n      this.warnedStuck = true;\n      console.log(\n        `The ${JSON.stringify(this.alias)} blocking queue may be stuck. 5 seconds ` +\n          `without any activity with 1 worker: ${Object.keys(this.running)[0]}`,\n      );\n    }\n  }\n\n  push<T>(key: string, factory: () => Promise<T>): Promise<T> {\n    if (this.first) {\n      this.first = false;\n    } else {\n      this.stillActive();\n    }\n\n    return new Promise((resolve, reject) => {\n      // we're already running so push ourselves to the queue\n      const queue = (this.queue[key] = this.queue[key] || []);\n      queue.push({factory, resolve, reject});\n\n      if (!this.running[key]) {\n        this.shift(key);\n      }\n    });\n  }\n\n  shift(key: string) {\n    if (this.running[key]) {\n      delete this.running[key];\n      this.runningCount--;\n\n      if (this.stuckTimer) {\n        clearTimeout(this.stuckTimer);\n        this.stuckTimer = null;\n      }\n\n      if (this.warnedStuck) {\n        this.warnedStuck = false;\n        console.log(`${JSON.stringify(this.alias)} blocking queue finally resolved. Nothing to worry about.`);\n      }\n    }\n\n    const queue = this.queue[key];\n    if (!queue) {\n      return;\n    }\n\n    const {resolve, reject, factory} = queue.shift();\n    if (!queue.length) {\n      delete this.queue[key];\n    }\n\n    const next = () => {\n      this.shift(key);\n      this.shiftConcurrencyQueue();\n    };\n\n    const run = () => {\n      this.running[key] = true;\n      this.runningCount++;\n\n      factory()\n        .then(function (val): null {\n          resolve(val);\n          next();\n          return null;\n        })\n        .catch(function (err) {\n          reject(err);\n          next();\n        });\n    };\n\n    this.maybePushConcurrencyQueue(run);\n  }\n\n  maybePushConcurrencyQueue(run: () => void) {\n    if (this.runningCount < this.maxConcurrency) {\n      run();\n    } else {\n      this.concurrencyQueue.push(run);\n    }\n  }\n\n  shiftConcurrencyQueue() {\n    if (this.runningCount < this.maxConcurrency) {\n      const fn = this.concurrencyQueue.shift();\n      if (fn) {\n        fn();\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "src/util/child.ts",
    "content": "/* global child_process$spawnOpts */\n\nimport * as constants from '../constants.js';\nimport BlockingQueue from './blocking-queue.js';\nimport {ProcessSpawnError, ProcessTermError} from '../errors.js';\nimport {promisify} from './promise.js';\nimport {exec as _exec, spawn as _spawn, ChildProcess, SpawnOptions} from 'child_process';\n\nexport const queue = new BlockingQueue('child', constants.CHILD_CONCURRENCY);\n\n// TODO: this uid check is kinda whack\nlet uid = 0;\n\nexport const exec = promisify(_exec);\n\nconst spawnedProcesses = {};\n\nexport function forwardSignalToSpawnedProcesses(signal: string) {\n  for (const key of Object.keys(spawnedProcesses)) {\n    spawnedProcesses[key].kill(signal);\n  }\n}\n\ntype ProcessFn = (\n  proc: ChildProcess,\n  update: (chunk: string) => void,\n  reject: (err: any) => void,\n  done: () => void,\n) => void;\n\nexport function spawn(\n  program: string,\n  args: Array<string>,\n  opts: SpawnOptions & {detached?: boolean; process?: ProcessFn} = {},\n  onData?: (chunk: Buffer | string) => void,\n): Promise<string> {\n  const key = opts.cwd || String(++uid);\n  return queue.push(\n    key,\n    (): Promise<string> =>\n      new Promise((resolve, reject) => {\n        const proc = _spawn(program, args, opts);\n        spawnedProcesses[key] = proc;\n\n        let processingDone = false;\n        let processClosed = false;\n        let err = null;\n\n        let stdout = '';\n\n        proc.on('error', (err: any) => {\n          if (err.code === 'ENOENT') {\n            reject(new ProcessSpawnError(`Couldn't find the binary ${program}`, err.code, program));\n          } else {\n            reject(err);\n          }\n        });\n\n        function updateStdout(chunk: string) {\n          stdout += chunk;\n          if (onData) {\n            onData(chunk);\n          }\n        }\n\n        function finish() {\n          delete spawnedProcesses[key];\n          if (err) {\n            reject(err);\n          } else {\n            resolve(stdout.trim());\n          }\n        }\n\n        if (typeof opts.process === 'function') {\n          opts.process(proc, updateStdout, reject, function () {\n            if (processClosed) {\n              finish();\n            } else {\n              processingDone = true;\n            }\n          });\n        } else {\n          if (proc.stderr) {\n            proc.stderr.on('data', updateStdout);\n          }\n\n          if (proc.stdout) {\n            proc.stdout.on('data', updateStdout);\n          }\n\n          processingDone = true;\n        }\n\n        proc.on('close', (code: number, signal: string) => {\n          if (signal || code >= 1) {\n            err = new ProcessTermError(\n              [\n                'Command failed.',\n                signal ? `Exit signal: ${signal}` : `Exit code: ${code}`,\n                `Command: ${program}`,\n                `Arguments: ${args.join(' ')}`,\n                `Directory: ${opts.cwd || process.cwd()}`,\n                `Output:\\n${stdout.trim()}`,\n              ].join('\\n'),\n            );\n            err.EXIT_SIGNAL = signal;\n            err.EXIT_CODE = code;\n          }\n\n          if (processingDone || err) {\n            finish();\n          } else {\n            processClosed = true;\n          }\n        });\n      }),\n  );\n}\n"
  },
  {
    "path": "src/util/conversion.ts",
    "content": "const FALSY_STRINGS = new Set(['0', 'false']);\n\nexport function boolify(val: string | number | boolean): boolean {\n  return !FALSY_STRINGS.has(val.toString().toLowerCase());\n}\n\nexport function boolifyWithDefault(val: string | number | boolean, defaultResult: boolean): boolean {\n  return val === '' || val === null || val === undefined ? defaultResult : boolify(val);\n}\n"
  },
  {
    "path": "src/util/execute-lifecycle-script.ts",
    "content": "import {StdioOptions} from 'child_process';\nimport Config from '../config.js';\nimport {MessageError} from '@pika/types';\nimport {ProcessTermError} from '../errors.js';\nimport * as child from './child.js';\nimport {fixCmdWinSlashes} from './fix-cmd-win-slashes.js';\n\n// import path from 'path';\n\nexport type LifecycleReturn = Promise<{\n  cwd: string;\n  command: string;\n  stdout: string;\n}>;\n\n// export const IGNORE_MANIFEST_KEYS: Set<string> = new Set(['readme', 'notice', 'licenseText']);\n\n// // We treat these configs as internal, thus not expose them to process.env.\n// // This helps us avoid some gyp issues when building native modules.\n// // See https://github.com/yarnpkg/yarn/issues/2286.\n// const IGNORE_CONFIG_KEYS = ['lastUpdateCheck'];\n\n// async function getPnpParameters(config: Config): Promise<Array<string>> {\n//   if (await fs.exists(`${config.lockfileFolder}/${constants.PNP_FILENAME}`)) {\n//     return ['-r', `${config.lockfileFolder}/${constants.PNP_FILENAME}`];\n//   } else {\n//     return [];\n//   }\n// }\n\n// let wrappersFolder = null;\n\n// export async function getWrappersFolder(config: Config): Promise<string> {\n//   if (wrappersFolder) {\n//     return wrappersFolder;\n//   }\n\n//   wrappersFolder = await fs.makeTempDir();\n\n//   await makePortableProxyScript(process.execPath, wrappersFolder, {\n//     proxyBasename: 'node',\n//     prependArguments: [...(await getPnpParameters(config))],\n//   });\n\n//   await makePortableProxyScript(process.execPath, wrappersFolder, {\n//     proxyBasename: 'pika',\n//     prependArguments: [process.argv[1]],\n//   });\n\n//   return wrappersFolder;\n// }\n\n// const INVALID_CHAR_REGEX = /\\W/g;\n\nexport async function makeEnv(): Promise<{[key: string]: string}> {\n  // stage: string,\n  // cwd: string,\n  // config: Config,\n  const env = {\n    NODE: process.execPath,\n    INIT_CWD: process.cwd(),\n    // This lets `process.env.NODE` to override our `process.execPath`.\n    // This is a bit confusing but it is how `npm` was designed so we\n    // try to be compatible with that.\n    ...process.env,\n  };\n  return env;\n}\n\n//   // Merge in the `env` object specified in .pikarc\n//   const customEnv = config.getOption('env');\n//   if (customEnv && typeof customEnv === 'object') {\n//     Object.assign(env, customEnv);\n//   }\n\n//   env.npm_lifecycle_event = stage;\n//   env.npm_node_execpath = env.NODE;\n//   env.npm_execpath = env.npm_execpath || (process.mainModule && process.mainModule.filename);\n\n//   // Set the env to production for npm compat if production mode.\n//   // https://github.com/npm/npm/blob/30d75e738b9cb7a6a3f9b50e971adcbe63458ed3/lib/utils/lifecycle.js#L336\n//   if (config.production) {\n//     env.NODE_ENV = 'production';\n//   }\n\n//   // Note: npm_config_argv environment variable contains output of nopt - command-line\n//   // parser used by npm. Since we use other parser, we just roughly emulate it's output. (See: #684)\n//   env.npm_config_argv = JSON.stringify({\n//     remain: [],\n//     cooked: config.commandName === 'run' ? [config.commandName, stage] : [config.commandName],\n//     original: process.argv.slice(2),\n//   });\n\n//   const manifest = await config.maybeReadManifest(cwd);\n//   if (manifest) {\n//     if (manifest.scripts && Object.prototype.hasOwnProperty.call(manifest.scripts, stage)) {\n//       env.npm_lifecycle_script = manifest.scripts[stage];\n//     }\n\n//     // add npm_package_*\n//     const queue = [['', manifest]];\n//     while (queue.length) {\n//       const [key, val] = queue.pop();\n//       if (typeof val === 'object') {\n//         for (const subKey in val) {\n//           const fullKey = [key, subKey].filter(Boolean).join('_');\n//           if (fullKey && fullKey[0] !== '_' && !IGNORE_MANIFEST_KEYS.has(fullKey)) {\n//             queue.push([fullKey, val[subKey]]);\n//           }\n//         }\n//       } else {\n//         let cleanVal = String(val);\n//         if (cleanVal.indexOf('\\n') >= 0) {\n//           cleanVal = JSON.stringify(cleanVal);\n//         }\n\n//         //replacing invalid chars with underscore\n//         const cleanKey = key.replace(INVALID_CHAR_REGEX, '_');\n\n//         env[`npm_package_${cleanKey}`] = cleanVal;\n//       }\n//     }\n//   }\n\n//   // add npm_config_* and npm_package_config_* from pika config\n//   const keys: Set<string> = new Set([\n//     ...Object.keys(config.registries.pika.config),\n//     ...Object.keys(config.registries.npm.config),\n//   ]);\n//   const cleaned = Array.from(keys)\n//     .filter(key => !key.match(/:_/) && IGNORE_CONFIG_KEYS.indexOf(key) === -1)\n//     .map(key => {\n//       let val = config.getOption(key);\n//       if (!val) {\n//         val = '';\n//       } else if (typeof val === 'number') {\n//         val = '' + val;\n//       } else if (typeof val !== 'string') {\n//         val = JSON.stringify(val);\n//       }\n\n//       if (val.indexOf('\\n') >= 0) {\n//         val = JSON.stringify(val);\n//       }\n//       return [key, val];\n//     });\n//   // add npm_config_*\n//   for (const [key, val] of cleaned) {\n//     const cleanKey = key.replace(/^_+/, '');\n//     const envKey = `npm_config_${cleanKey}`.replace(INVALID_CHAR_REGEX, '_');\n//     env[envKey] = val;\n//   }\n//   // add npm_package_config_*\n//   if (manifest && manifest.name) {\n//     const packageConfigPrefix = `${manifest.name}:`;\n//     for (const [key, val] of cleaned) {\n//       if (key.indexOf(packageConfigPrefix) !== 0) {\n//         continue;\n//       }\n//       const cleanKey = key.replace(/^_+/, '').replace(packageConfigPrefix, '');\n//       const envKey = `npm_package_config_${cleanKey}`.replace(INVALID_CHAR_REGEX, '_');\n//       env[envKey] = val;\n//     }\n//   }\n\n//   // split up the path\n//   const envPath = env[constants.ENV_PATH_KEY];\n//   const pathParts = envPath ? envPath.split(path.delimiter) : [];\n\n//   // Include the directory that contains node so that we can guarantee that the scripts\n//   // will always run with the exact same Node release than the one use to run Pika\n//   const execBin = path.dirname(process.execPath);\n//   if (pathParts.indexOf(execBin) === -1) {\n//     pathParts.unshift(execBin);\n//   }\n\n//   // Include node-gyp version that was bundled with the current Node.js version,\n//   // if available.\n//   pathParts.unshift(path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'node-gyp-bin'));\n//   pathParts.unshift(\n//     path.join(path.dirname(process.execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin'),\n//   );\n//   // Include node-gyp version from homebrew managed npm, if available.\n//   pathParts.unshift(\n//     path.join(path.dirname(process.execPath), '..', 'libexec', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin'),\n//   );\n\n//   // Add global bin folder if it is not present already, as some packages depend\n//   // on a globally-installed version of node-gyp.\n//   const globalBin = await getGlobalBinFolder(config, {});\n//   if (pathParts.indexOf(globalBin) === -1) {\n//     pathParts.unshift(globalBin);\n//   }\n\n//   // Add node_modules .bin folders to the PATH\n//   for (const registry of Object.keys(registries)) {\n//     const binFolder = path.join(config.registries[registry].folder, '.bin');\n//     if (config.workspacesEnabled && config.workspaceRootFolder) {\n//       pathParts.unshift(path.join(config.workspaceRootFolder, binFolder));\n//     }\n//     pathParts.unshift(path.join(config.linkFolder, binFolder));\n//     pathParts.unshift(path.join(cwd, binFolder));\n//     if (config.modulesFolder) {\n//       pathParts.unshift(path.join(config.modulesFolder, '.bin'));\n//     }\n//   }\n\n//   if (await fs.exists(`${config.lockfileFolder}/${constants.PNP_FILENAME}`)) {\n//     // TODO: Fix. import()? Do we even like that it does this?\n//     throw new Error(\"pnp temporarily not supported\");\n//     const pnpApi = {}; //dynamicRequire(`${config.lockfileFolder}/${constants.PNP_FILENAME}`);\n\n//     const packageLocator = pnpApi.findPackageLocator(`${config.cwd}/`);\n//     const packageInformation = pnpApi.getPackageInformation(packageLocator);\n\n//     for (const [name, reference] of packageInformation.packageDependencies.entries()) {\n//       const dependencyInformation = pnpApi.getPackageInformation({name, reference});\n\n//       if (!dependencyInformation || !dependencyInformation.packageLocation) {\n//         continue;\n//       }\n\n//       pathParts.unshift(`${dependencyInformation.packageLocation}/.bin`);\n//     }\n//   }\n\n//   pathParts.unshift(await getWrappersFolder(config));\n\n//   // join path back together\n//   env[constants.ENV_PATH_KEY] = pathParts.join(path.delimiter);\n\n//   return env;\n// }\n\nexport async function executeLifecycleScript({\n  // config,\n  cwd,\n  cmd,\n  args,\n  isInteractive,\n  onProgress,\n  customShell,\n}: {\n  // config: Config;\n  cwd: string;\n  args: string[];\n  cmd: string;\n  isInteractive?: boolean;\n  onProgress?: (chunk: Buffer | string) => void;\n  customShell?: string;\n}): LifecycleReturn {\n  const env = await makeEnv();\n\n  // await checkForGypIfNeeded(config, cmd, env[constants.ENV_PATH_KEY].split(path.delimiter));\n\n  if (process.platform === 'win32' && (!customShell || customShell === 'cmd')) {\n    // handle windows run scripts starting with a relative path\n    cmd = fixCmdWinSlashes(cmd);\n  }\n\n  // By default (non-interactive), pipe everything to the terminal and run child process detached\n  // as long as it's not Windows (since windows does not have /dev/tty)\n  let stdio: StdioOptions = ['ignore', 'pipe', 'pipe'];\n  let detached = process.platform !== 'win32';\n\n  if (isInteractive) {\n    stdio = 'inherit';\n    detached = false;\n  }\n\n  const shell = customShell || true;\n  const stdout = await child.spawn(cmd, args, {cwd, env, stdio, detached, shell}, onProgress);\n\n  return {cwd, command: cmd, stdout};\n}\n\nexport default executeLifecycleScript;\n\n// let checkGypPromise: Promise<void> = null;\n// // /**\n// //  * Special case: Some packages depend on node-gyp, but don't specify this in\n// //  * their package.json dependencies. They assume that node-gyp is available\n// //  * globally. We need to detect this case and show an error message.\n// //  */\n// function checkForGypIfNeeded(config: Config, cmd: string, paths: Array<string>): Promise<void> {\n//   if (cmd.substr(0, cmd.indexOf(' ')) !== 'node-gyp') {\n//     return Promise.resolve();\n//   }\n\n//   // Ensure this only runs once, rather than multiple times in parallel.\n//   if (!checkGypPromise) {\n//     checkGypPromise = _checkForGyp(config, paths);\n//   }\n//   return checkGypPromise;\n// }\n\n// async function _checkForGyp(config: Config, paths: Array<string>): Promise<void> {\n//   const {reporter} = config;\n\n//   // Check every directory in the PATH\n//   const allChecks = await Promise.all(paths.map(dir => fs.exists(path.join(dir, 'node-gyp'))));\n//   if (allChecks.some(Boolean)) {\n//     // node-gyp is available somewhere\n//     return;\n//   }\n\n//   reporter.info(reporter.lang('packageRequiresNodeGyp'));\n// }\n\n// export async function execFromDistributions(config: Config, cwd: string, dist: string, step: string): Promise<void> {\n//   const pkg = await config.maybeReadManifest(cwd);\n//   if (!pkg || !pkg.distributions || !pkg.distributions[dist] || typeof pkg.distributions[dist][step] !== 'string') {\n//     return false;\n//   }\n//   const cmd: ?string = pkg.distributions[dist][step];\n//   await execCommand({stage: 'build', config, cmd, cwd, isInteractive: true});\n//   return true;\n// }\n\n// export async function execFromManifest(config: Config, commandName: string, cwd: string): Promise<void> {\n//   const pkg = await config.maybeReadManifest(cwd);\n//   if (!pkg || !pkg.scripts) {\n//     return;\n//   }\n\n//   const cmd: ?string = pkg.scripts[commandName];\n//   if (cmd) {\n//     await execCommand({stage: commandName, config, cmd, cwd, isInteractive: true});\n//   }\n// }\n\n// export async function execCommand({\n//   stage,\n//   config,\n//   cmd,\n//   cwd,\n//   isInteractive,\n//   customShell,\n// }: {\n//   stage: string;\n//   config: Config;\n//   cmd: string;\n//   cwd: string;\n//   isInteractive: boolean;\n//   customShell?: string;\n// }): Promise<void> {\n//   const {reporter} = config;\n//   try {\n//     reporter.command(cmd);\n//     await executeLifecycleScript({config, cwd, cmd, isInteractive, customShell});\n//     return Promise.resolve();\n//   } catch (err) {\n//     if (err instanceof ProcessTermError) {\n//       throw new MessageError(\n//         err.EXIT_SIGNAL\n//           ? reporter.lang('commandFailedWithSignal', err.EXIT_SIGNAL)\n//           : reporter.lang('commandFailedWithCode', err.EXIT_CODE),\n//       );\n//     } else {\n//       throw err;\n//     }\n//   }\n// }\n"
  },
  {
    "path": "src/util/fix-cmd-win-slashes.ts",
    "content": "export function fixCmdWinSlashes(cmd: string): string {\n  function findQuotes(quoteSymbol: string): {from: number; to: number}[] {\n    const quotes = [];\n    const addQuote = (_, index) => {\n      quotes.push({from: index, to: index + _.length});\n      return _;\n    };\n    const regEx = new RegExp(quoteSymbol + '.*' + quoteSymbol);\n    cmd.replace(regEx, addQuote);\n    return quotes;\n  }\n  const quotes = findQuotes('\"').concat(findQuotes(\"'\"));\n\n  function isInsideQuotes(index: number): boolean {\n    return quotes.reduce((result, quote) => {\n      return result || (quote.from <= index && index <= quote.to);\n    }, false);\n  }\n\n  const cmdPrePattern = '((?:^|&&|&|\\\\|\\\\||\\\\|)\\\\s*)';\n  const cmdPattern = '(\".*?\"|\\'.*?\\'|\\\\S*)';\n  const regExp = new RegExp(`${cmdPrePattern}${cmdPattern}`, 'g');\n  return cmd.replace(regExp, (whole, pre, cmd, index) => {\n    if ((pre[0] === '&' || pre[0] === '|') && isInsideQuotes(index)) {\n      return whole;\n    }\n    return pre + cmd.replace(/\\//g, '\\\\');\n  });\n}\n"
  },
  {
    "path": "src/util/fs-normalized.ts",
    "content": "//\n\n// // This module serves as a wrapper for file operations that are inconsistant across node and OS versions.\n\n// import fs from 'fs';\n// import {promisify} from './promise.js';\n\n// import {constants} from './fs.js';\n\n// export type CopyFileAction = {\n//   src: string,\n//   dest: string,\n//   atime: Date,\n//   mtime: Date,\n//   mode: number,\n// };\n\n// let disableTimestampCorrection: boolean; // OS dependent. will be detected on first file copy.\n\n// const readFileBuffer = promisify(fs.readFile);\n// const close: (fd: number) => Promise<void> = promisify(fs.close);\n// const lstat: (path: string) => Promise<fs.Stats> = promisify(fs.lstat);\n// const open: (path: string, flags: string | number, mode: number) => Promise<number> = promisify(fs.open);\n// const futimes: (fd: number, atime: number, mtime: number) => Promise<void> = promisify(fs.futimes);\n\n// const write: (\n//   fd: number,\n//   buffer: Buffer,\n//   offset?: number,\n//   length?: number,\n//   position?: number,\n// ) => Promise<void> = promisify(fs.write);\n\n// /**\n//  * Unlinks the destination to force a recreation. This is needed on case-insensitive file systems\n//  * to force the correct naming when the filename has changed only in character-casing. (Jest -> jest).\n//  */\n// export const copyFile = async function(data: CopyFileAction, cleanup: () => any): Promise<void> {\n//   // $FlowFixMe: Flow doesn't currently support COPYFILE_FICLONE\n//   const ficloneFlag = (constants as any).COPYFILE_FICLONE || 0;\n//   try {\n//     await unlink(data.dest);\n//     await copyFilePoly(data.src, data.dest, ficloneFlag, data);\n//   } finally {\n//     if (cleanup) {\n//       cleanup();\n//     }\n//   }\n// };\n\n// // Node 8.5.0 introduced `fs.copyFile` which is much faster, so use that when available.\n// // Otherwise we fall back to reading and writing files as buffers.\n// const copyFilePoly: (src: string, dest: string, flags: number, data: CopyFileAction) => Promise<void> = (\n//   src,\n//   dest,\n//   flags,\n//   data,\n// ) => {\n//   if (fs.copyFile) {\n//     return new Promise((resolve, reject) =>\n//       fs.copyFile(src, dest, flags, err => {\n//         if (err) {\n//           reject(err);\n//         } else {\n//           fixTimes(undefined, dest, data).then(() => resolve()).catch(ex => reject(ex));\n//         }\n//       }),\n//     );\n//   } else {\n//     return copyWithBuffer(src, dest, flags, data);\n//   }\n// };\n\n// const copyWithBuffer: (src: string, dest: string, flags: number, data: CopyFileAction) => Promise<void> = async (\n//   src,\n//   dest,\n//   flags,\n//   data,\n// ) => {\n//   // Use open -> write -> futimes -> close sequence to avoid opening the file twice:\n//   // one with writeFile and one with utimes\n//   const fd = await open(dest, 'w', data.mode);\n//   try {\n//     const buffer = await readFileBuffer(src);\n//     await write(fd, buffer, 0, buffer.length);\n//     await fixTimes(fd, dest, data);\n//   } finally {\n//     await close(fd);\n//   }\n// };\n\n// // We want to preserve file timestamps when copying a file, since pika uses them to decide if a file has\n// // changed compared to the cache.\n// // There are some OS specific cases here:\n// // * On linux, fs.copyFile does not preserve timestamps, but does on OSX and Win.\n// // * On windows, you must open a file with write permissions to call `fs.futimes`.\n// // * On OSX you can open with read permissions and still call `fs.futimes`.\n// async function fixTimes(fd: number | undefined, dest: string, data: CopyFileAction): Promise<void> {\n//   const doOpen = fd === undefined;\n//   let openfd: number = fd ? fd : -1;\n\n//   if (disableTimestampCorrection === undefined) {\n//     // if timestamps match already, no correction is needed.\n//     // the need to correct timestamps varies based on OS and node versions.\n//     const destStat = await lstat(dest);\n//     disableTimestampCorrection = fileDatesEqual(destStat.mtime, data.mtime);\n//   }\n\n//   if (disableTimestampCorrection) {\n//     return;\n//   }\n\n//   if (doOpen) {\n//     try {\n//       openfd = await open(dest, 'a', data.mode);\n//     } catch (er) {\n//       // file is likely read-only\n//       try {\n//         openfd = await open(dest, 'r', data.mode);\n//       } catch (err) {\n//         // We can't even open this file for reading.\n//         return;\n//       }\n//     }\n//   }\n\n//   try {\n//     if (openfd) {\n//       await futimes(openfd, data.atime, data.mtime);\n//     }\n//   } catch (er) {\n//     // If `futimes` throws an exception, we probably have a case of a read-only file on Windows.\n//     // In this case we can just return. The incorrect timestamp will just cause that file to be recopied\n//     // on subsequent installs, which will effect pika performance but not break anything.\n//   } finally {\n//     if (doOpen && openfd) {\n//       await close(openfd);\n//     }\n//   }\n// }\n\n// // Compare file timestamps.\n// // Some versions of Node on windows zero the milliseconds when utime is used.\n// export const fileDatesEqual = (a: Date, b: Date) => {\n//   const aTime = a.getTime();\n//   const bTime = b.getTime();\n\n//   if (process.platform !== 'win32') {\n//     return aTime === bTime;\n//   }\n\n//   // See https://github.com/nodejs/node/pull/12607\n//   // Submillisecond times from stat and utimes are truncated on Windows,\n//   // causing a file with mtime 8.0079998 and 8.0081144 to become 8.007 and 8.008\n//   // and making it impossible to update these files to their correct timestamps.\n//   if (Math.abs(aTime - bTime) <= 1) {\n//     return true;\n//   }\n\n//   const aTimeSec = Math.floor(aTime / 1000);\n//   const bTimeSec = Math.floor(bTime / 1000);\n\n//   // See https://github.com/nodejs/node/issues/2069\n//   // Some versions of Node on windows zero the milliseconds when utime is used\n//   // So if any of the time has a milliseconds part of zero we suspect that the\n//   // bug is present and compare only seconds.\n//   if (aTime - aTimeSec * 1000 === 0 || bTime - bTimeSec * 1000 === 0) {\n//     return aTimeSec === bTimeSec;\n//   }\n\n//   return aTime === bTime;\n// };\n"
  },
  {
    "path": "src/util/fs.ts",
    "content": "import {promisify} from 'util';\nimport _rimraf from 'rimraf';\nimport _mkdirp from 'mkdirp';\nimport _glob from 'glob';\n\nexport const unlink: (path: string) => Promise<void> = promisify(_rimraf);\nexport const glob: (path: string, options?: Object) => Promise<Array<string>> = promisify(_glob);\nexport const mkdirp: (path: string) => Promise<void> = promisify(_mkdirp);\n\n//\n\n// import {ReadStream} from 'fs';\n// import Reporter from '../reporters/base-reporter.js';\n// import {CopyFileAction} from './fs-normalized.js';\n\nimport * as os from 'os';\nimport * as path from 'path';\n\n// import BlockingQueue from './blocking-queue.js';\n// import * as promise from './promise.js';\nimport map from './map.js';\n// import {copyFile, fileDatesEqual, unlink} from './fs-normalized.js';\n\n// export const constants =\n//   typeof fs.constants !== 'undefined'\n//     ? fs.constants\n//     : {\n//         R_OK: fs.R_OK,\n//         W_OK: fs.W_OK,\n//         X_OK: fs.X_OK,\n//       };\n\n// export const lockQueue = new BlockingQueue('fs lock');\n\nimport * as fs from 'fs';\nimport * as util from 'util';\nexport const open = util.promisify(fs.open);\nexport const writeFile = util.promisify(fs.writeFile);\nexport const readlink = util.promisify(fs.readlink);\nexport const realpath = util.promisify(fs.realpath);\nexport const readdir = util.promisify(fs.readdir);\nexport const rename = util.promisify(fs.rename);\nexport const access = util.promisify(fs.access);\nexport const stat = util.promisify(fs.stat);\nexport const exists = util.promisify(fs.exists);\nexport const lstat = util.promisify(fs.lstat);\nexport const chmod = util.promisify(fs.chmod);\nexport const link = util.promisify(fs.link);\nexport const copyFile = util.promisify(fs.copyFile);\nconst readFileBuffer = util.promisify(fs.readFile);\nexport const readFile = (path: string) => {\n  return util.promisify(fs.readFile)(path, {encoding: 'utf-8'});\n};\n// export {unlink};\n\n// // fs.copyFile uses the native file copying instructions on the system, performing much better\n// // than any JS-based solution and consumes fewer resources. Repeated testing to fine tune the\n// // concurrency level revealed 128 as the sweet spot on a quad-core, 16 CPU Intel system with SSD.\n// const CONCURRENT_QUEUE_ITEMS = fs.copyFile ? 128 : 4;\n\n// const fsSymlink: (target: string, path: string, type?: 'dir' | 'file' | 'junction') => Promise<void> = promisify(\n//   fs.symlink,\n// );\n// import invariant from 'invariant';\nimport stripBOM from 'strip-bom';\n\n// const noop = () => {};\n\n// export type CopyQueueItem = {\n//   src: string,\n//   dest: string,\n//   type?: string,\n//   onFresh?: () => void,\n//   onDone?: () => void,\n// };\n\n// type CopyQueue = Array<CopyQueueItem>;\n\n// type LinkFileAction = {\n//   src: string,\n//   dest: string,\n//   removeDest: boolean,\n// };\n\n// type CopySymlinkAction = {\n//   dest: string,\n//   linkname: string,\n// };\n\n// type CopyActions = {\n//   file: Array<CopyFileAction>,\n//   symlink: Array<CopySymlinkAction>,\n//   link: Array<LinkFileAction>,\n// };\n\n// type CopyOptions = {\n//   onProgress: (dest: string) => void,\n//   onStart: (num: number) => void,\n//   possibleExtraneous: Set<string>,\n//   ignoreBasenames: Array<string>,\n//   artifactFiles: Array<string>,\n// };\n\n// type FailedFolderQuery = {\n//   error: Error,\n//   folder: string,\n// };\n\n// type FolderQueryResult = {\n//   skipped: Array<FailedFolderQuery>,\n//   folder?: string,\n// };\n\n// async function buildActionsForCopy(\n//   queue: CopyQueue,\n//   events: CopyOptions,\n//   possibleExtraneous: Set<string>,\n//   reporter: Reporter,\n// ): Promise<CopyActions> {\n//   const artifactFiles: Set<string> = new Set(events.artifactFiles || []);\n//   const files: Set<string> = new Set();\n\n//   // initialise events\n//   for (const item of queue) {\n//     const onDone = item.onDone;\n//     item.onDone = () => {\n//       events.onProgress(item.dest);\n//       if (onDone) {\n//         onDone();\n//       }\n//     };\n//   }\n//   events.onStart(queue.length);\n\n//   // start building actions\n//   const actions: CopyActions = {\n//     file: [],\n//     symlink: [],\n//     link: [],\n//   };\n\n//   // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items\n//   // at a time due to the requirement to push items onto the queue\n//   while (queue.length) {\n//     const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);\n//     await Promise.all(items.map(build));\n//   }\n\n//   // simulate the existence of some files to prevent considering them extraneous\n//   for (const file of artifactFiles) {\n//     if (possibleExtraneous.has(file)) {\n//       reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));\n//       possibleExtraneous.delete(file);\n//     }\n//   }\n\n//   for (const loc of possibleExtraneous) {\n//     if (files.has(loc.toLowerCase())) {\n//       possibleExtraneous.delete(loc);\n//     }\n//   }\n\n//   return actions;\n\n//   //\n//   async function build(data: CopyQueueItem): Promise<void> {\n//     const {src, dest, type} = data;\n//     const onFresh = data.onFresh || noop;\n//     const onDone = data.onDone || noop;\n\n//     // TODO https://github.com/yarnpkg/yarn/issues/3751\n//     // related to bundled dependencies handling\n//     if (files.has(dest.toLowerCase())) {\n//       reporter.verbose(`The case-insensitive file ${dest} shouldn't be copied twice in one bulk copy`);\n//     } else {\n//       files.add(dest.toLowerCase());\n//     }\n\n//     if (type === 'symlink') {\n//       await mkdirp(path.dirname(dest));\n//       onFresh();\n//       actions.symlink.push({\n//         dest,\n//         linkname: src,\n//       });\n//       onDone();\n//       return;\n//     }\n\n//     if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {\n//       // ignored file\n//       return;\n//     }\n\n//     const srcStat = await lstat(src);\n//     let srcFiles;\n\n//     if (srcStat.isDirectory()) {\n//       srcFiles = await readdir(src);\n//     }\n\n//     let destStat;\n//     try {\n//       // try accessing the destination\n//       destStat = await lstat(dest);\n//     } catch (e) {\n//       // proceed if destination doesn't exist, otherwise error\n//       if (e.code !== 'ENOENT') {\n//         throw e;\n//       }\n//     }\n\n//     // if destination exists\n//     if (destStat) {\n//       const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();\n//       const bothFolders = srcStat.isDirectory() && destStat.isDirectory();\n//       const bothFiles = srcStat.isFile() && destStat.isFile();\n\n//       // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving\n//       // us modes that aren't valid. investigate this, it's generally safe to proceed.\n\n//       /* if (srcStat.mode !== destStat.mode) {\n//         try {\n//           await access(dest, srcStat.mode);\n//         } catch (err) {}\n//       } */\n\n//       if (bothFiles && artifactFiles.has(dest)) {\n//         // this file gets changed during build, likely by a custom install script. Don't bother checking it.\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkipArtifact', src));\n//         return;\n//       }\n\n//       if (bothFiles && srcStat.size === destStat.size && fileDatesEqual(srcStat.mtime, destStat.mtime)) {\n//         // we can safely assume this is the same file\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime));\n//         return;\n//       }\n\n//       if (bothSymlinks) {\n//         const srcReallink = await readlink(src);\n//         if (srcReallink === (await readlink(dest))) {\n//           // if both symlinks are the same then we can continue on\n//           onDone();\n//           reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));\n//           return;\n//         }\n//       }\n\n//       if (bothFolders) {\n//         // mark files that aren't in this folder as possibly extraneous\n//         const destFiles = await readdir(dest);\n//         invariant(srcFiles, 'src files not initialised');\n\n//         for (const file of destFiles) {\n//           if (srcFiles.indexOf(file) < 0) {\n//             const loc = path.join(dest, file);\n//             possibleExtraneous.add(loc);\n\n//             if ((await lstat(loc)).isDirectory()) {\n//               for (const file of await readdir(loc)) {\n//                 possibleExtraneous.add(path.join(loc, file));\n//               }\n//             }\n//           }\n//         }\n//       }\n//     }\n\n//     if (destStat && destStat.isSymbolicLink()) {\n//       await unlink(dest);\n//       destStat = null;\n//     }\n\n//     if (srcStat.isSymbolicLink()) {\n//       onFresh();\n//       const linkname = await readlink(src);\n//       actions.symlink.push({\n//         dest,\n//         linkname,\n//       });\n//       onDone();\n//     } else if (srcStat.isDirectory()) {\n//       if (!destStat) {\n//         reporter.verbose(reporter.lang('verboseFileFolder', dest));\n//         await mkdirp(dest);\n//       }\n\n//       const destParts = dest.split(path.sep);\n//       while (destParts.length) {\n//         files.add(destParts.join(path.sep).toLowerCase());\n//         destParts.pop();\n//       }\n\n//       // push all files to queue\n//       invariant(srcFiles, 'src files not initialised');\n//       let remaining = srcFiles.length;\n//       if (!remaining) {\n//         onDone();\n//       }\n//       for (const file of srcFiles) {\n//         queue.push({\n//           dest: path.join(dest, file),\n//           onFresh,\n//           onDone: () => {\n//             if (--remaining === 0) {\n//               onDone();\n//             }\n//           },\n//           src: path.join(src, file),\n//         });\n//       }\n//     } else if (srcStat.isFile()) {\n//       onFresh();\n//       actions.file.push({\n//         src,\n//         dest,\n//         atime: srcStat.atime,\n//         mtime: srcStat.mtime,\n//         mode: srcStat.mode,\n//       });\n//       onDone();\n//     } else {\n//       throw new Error(`unsure how to copy this: ${src}`);\n//     }\n//   }\n// }\n\n// async function buildActionsForHardlink(\n//   queue: CopyQueue,\n//   events: CopyOptions,\n//   possibleExtraneous: Set<string>,\n//   reporter: Reporter,\n// ): Promise<CopyActions> {\n//   const artifactFiles: Set<string> = new Set(events.artifactFiles || []);\n//   const files: Set<string> = new Set();\n\n//   // initialise events\n//   for (const item of queue) {\n//     const onDone = item.onDone || noop;\n//     item.onDone = () => {\n//       events.onProgress(item.dest);\n//       onDone();\n//     };\n//   }\n//   events.onStart(queue.length);\n\n//   // start building actions\n//   const actions: CopyActions = {\n//     file: [],\n//     symlink: [],\n//     link: [],\n//   };\n\n//   // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items\n//   // at a time due to the requirement to push items onto the queue\n//   while (queue.length) {\n//     const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);\n//     await Promise.all(items.map(build));\n//   }\n\n//   // simulate the existence of some files to prevent considering them extraneous\n//   for (const file of artifactFiles) {\n//     if (possibleExtraneous.has(file)) {\n//       reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));\n//       possibleExtraneous.delete(file);\n//     }\n//   }\n\n//   for (const loc of possibleExtraneous) {\n//     if (files.has(loc.toLowerCase())) {\n//       possibleExtraneous.delete(loc);\n//     }\n//   }\n\n//   return actions;\n\n//   //\n//   async function build(data: CopyQueueItem): Promise<void> {\n//     const {src, dest} = data;\n//     const onFresh = data.onFresh || noop;\n//     const onDone = data.onDone || noop;\n//     if (files.has(dest.toLowerCase())) {\n//       // Fixes issue https://github.com/yarnpkg/yarn/issues/2734\n//       // When bulk hardlinking we have A -> B structure that we want to hardlink to A1 -> B1,\n//       // package-linker passes that modules A1 and B1 need to be hardlinked,\n//       // the recursive linking algorithm of A1 ends up scheduling files in B1 to be linked twice which will case\n//       // an exception.\n//       onDone();\n//       return;\n//     }\n//     files.add(dest.toLowerCase());\n\n//     if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {\n//       // ignored file\n//       return;\n//     }\n\n//     const srcStat = await lstat(src);\n//     let srcFiles;\n\n//     if (srcStat.isDirectory()) {\n//       srcFiles = await readdir(src);\n//     }\n\n//     const destExists = await exists(dest);\n//     if (destExists) {\n//       const destStat = await lstat(dest);\n\n//       const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();\n//       const bothFolders = srcStat.isDirectory() && destStat.isDirectory();\n//       const bothFiles = srcStat.isFile() && destStat.isFile();\n\n//       if (srcStat.mode !== destStat.mode) {\n//         try {\n//           await access(dest, srcStat.mode);\n//         } catch (err) {\n//           // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving\n//           // us modes that aren't valid. investigate this, it's generally safe to proceed.\n//           reporter.verbose(err);\n//         }\n//       }\n\n//       if (bothFiles && artifactFiles.has(dest)) {\n//         // this file gets changed during build, likely by a custom install script. Don't bother checking it.\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkipArtifact', src));\n//         return;\n//       }\n\n//       // correct hardlink\n//       if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) {\n//         onDone();\n//         reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino));\n//         return;\n//       }\n\n//       if (bothSymlinks) {\n//         const srcReallink = await readlink(src);\n//         if (srcReallink === (await readlink(dest))) {\n//           // if both symlinks are the same then we can continue on\n//           onDone();\n//           reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));\n//           return;\n//         }\n//       }\n\n//       if (bothFolders) {\n//         // mark files that aren't in this folder as possibly extraneous\n//         const destFiles = await readdir(dest);\n//         invariant(srcFiles, 'src files not initialised');\n\n//         for (const file of destFiles) {\n//           if (srcFiles.indexOf(file) < 0) {\n//             const loc = path.join(dest, file);\n//             possibleExtraneous.add(loc);\n\n//             if ((await lstat(loc)).isDirectory()) {\n//               for (const file of await readdir(loc)) {\n//                 possibleExtraneous.add(path.join(loc, file));\n//               }\n//             }\n//           }\n//         }\n//       }\n//     }\n\n//     if (srcStat.isSymbolicLink()) {\n//       onFresh();\n//       const linkname = await readlink(src);\n//       actions.symlink.push({\n//         dest,\n//         linkname,\n//       });\n//       onDone();\n//     } else if (srcStat.isDirectory()) {\n//       reporter.verbose(reporter.lang('verboseFileFolder', dest));\n//       await mkdirp(dest);\n\n//       const destParts = dest.split(path.sep);\n//       while (destParts.length) {\n//         files.add(destParts.join(path.sep).toLowerCase());\n//         destParts.pop();\n//       }\n\n//       // push all files to queue\n//       invariant(srcFiles, 'src files not initialised');\n//       let remaining = srcFiles.length;\n//       if (!remaining) {\n//         onDone();\n//       }\n//       for (const file of srcFiles) {\n//         queue.push({\n//           onFresh,\n//           src: path.join(src, file),\n//           dest: path.join(dest, file),\n//           onDone: () => {\n//             if (--remaining === 0) {\n//               onDone();\n//             }\n//           },\n//         });\n//       }\n//     } else if (srcStat.isFile()) {\n//       onFresh();\n//       actions.link.push({\n//         src,\n//         dest,\n//         removeDest: destExists,\n//       });\n//       onDone();\n//     } else {\n//       throw new Error(`unsure how to copy this: ${src}`);\n//     }\n//   }\n// }\n\n// export function copy(src: string, dest: string, reporter: Reporter): Promise<void> {\n//   return copyBulk([{src, dest}], reporter);\n// }\n\n// export async function copyBulk(\n//   queue: CopyQueue,\n//   reporter: Reporter,\n//   _events?: {\n//     onProgress?: (dest: string) => void,\n//     onStart?: (num: number) => void,\n//     possibleExtraneous: Set<string>,\n//     ignoreBasenames?: Array<string>,\n//     artifactFiles?: Array<string>,\n//   },\n// ): Promise<void> {\n//   const events: CopyOptions = {\n//     onStart: (_events && _events.onStart) || noop,\n//     onProgress: (_events && _events.onProgress) || noop,\n//     possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),\n//     ignoreBasenames: (_events && _events.ignoreBasenames) || [],\n//     artifactFiles: (_events && _events.artifactFiles) || [],\n//   };\n\n//   const actions: CopyActions = await buildActionsForCopy(queue, events, events.possibleExtraneous, reporter);\n//   events.onStart(actions.file.length + actions.symlink.length + actions.link.length);\n\n//   const fileActions: Array<CopyFileAction> = actions.file;\n\n//   const currentlyWriting: Map<string, Promise<void>> = new Map();\n\n//   await promise.queue(\n//     fileActions,\n//     async (data: CopyFileAction): Promise<void> => {\n//       let writePromise;\n//       while ((writePromise = currentlyWriting.get(data.dest))) {\n//         await writePromise;\n//       }\n\n//       reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest));\n//       const copier = copyFile(data, () => currentlyWriting.delete(data.dest));\n//       currentlyWriting.set(data.dest, copier);\n//       events.onProgress(data.dest);\n//       return copier;\n//     },\n//     CONCURRENT_QUEUE_ITEMS,\n//   );\n\n//   // we need to copy symlinks last as they could reference files we were copying\n//   const symlinkActions: Array<CopySymlinkAction> = actions.symlink;\n//   await promise.queue(symlinkActions, (data): Promise<void> => {\n//     const linkname = path.resolve(path.dirname(data.dest), data.linkname);\n//     reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));\n//     return symlink(linkname, data.dest);\n//   });\n// }\n\n// export async function hardlinkBulk(\n//   queue: CopyQueue,\n//   reporter: Reporter,\n//   _events?: {\n//     onProgress?: (dest: string) => void,\n//     onStart?: (num: number) => void,\n//     possibleExtraneous: Set<string>,\n//     artifactFiles?: Array<string>,\n//   },\n// ): Promise<void> {\n//   const events: CopyOptions = {\n//     onStart: (_events && _events.onStart) || noop,\n//     onProgress: (_events && _events.onProgress) || noop,\n//     possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),\n//     artifactFiles: (_events && _events.artifactFiles) || [],\n//     ignoreBasenames: [],\n//   };\n\n//   const actions: CopyActions = await buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter);\n//   events.onStart(actions.file.length + actions.symlink.length + actions.link.length);\n\n//   const fileActions: Array<LinkFileAction> = actions.link;\n\n//   await promise.queue(\n//     fileActions,\n//     async (data): Promise<void> => {\n//       reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest));\n//       if (data.removeDest) {\n//         await unlink(data.dest);\n//       }\n//       await link(data.src, data.dest);\n//     },\n//     CONCURRENT_QUEUE_ITEMS,\n//   );\n\n//   // we need to copy symlinks last as they could reference files we were copying\n//   const symlinkActions: Array<CopySymlinkAction> = actions.symlink;\n//   await promise.queue(symlinkActions, (data): Promise<void> => {\n//     const linkname = path.resolve(path.dirname(data.dest), data.linkname);\n//     reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));\n//     return symlink(linkname, data.dest);\n//   });\n// }\n\n// function _readFile(loc: string, encoding: string): Promise<any> {\n//   return new Promise((resolve, reject) => {\n//     fs.readFile(loc, encoding, function(err, content) {\n//       if (err) {\n//         reject(err);\n//       } else {\n//         resolve(content);\n//       }\n//     });\n//   });\n// }\n\n// export function readFile(loc: string): Promise<string> {\n//   return _readFile(loc, 'utf8').then(normalizeOS);\n// }\n\n// export function readFileRaw(loc: string): Promise<Buffer> {\n//   return _readFile(loc, 'binary');\n// }\n\n// export async function readFileAny(files: Array<string>): Promise<string | null> {\n//   for (const file of files) {\n//     if (await exists(file)) {\n//       return readFile(file);\n//     }\n//   }\n//   return null;\n// }\n\nexport async function readJson(loc: string): Promise<Object> {\n  return (await readJsonAndFile(loc)).object;\n}\n\nexport async function readJsonAndFile(\n  loc: string,\n): Promise<{\n  object: Object;\n  content: string;\n}> {\n  const file = await readFile(loc);\n  try {\n    return {\n      object: map(JSON.parse(stripBOM(file))),\n      content: file,\n    };\n  } catch (err) {\n    err.message = `${loc}: ${err.message}`;\n    throw err;\n  }\n}\n\n// export async function find(filename: string, dir: string): Promise<string | false> {\n//   const parts = dir.split(path.sep);\n\n//   while (parts.length) {\n//     const loc = parts.concat(filename).join(path.sep);\n\n//     if (await exists(loc)) {\n//       return loc;\n//     } else {\n//       parts.pop();\n//     }\n//   }\n\n//   return false;\n// }\n\n// export async function symlink(src: string, dest: string): Promise<void> {\n//   if (process.platform !== 'win32') {\n//     // use relative paths otherwise which will be retained if the directory is moved\n//     src = path.relative(path.dirname(dest), src);\n//     // When path.relative returns an empty string for the current directory, we should instead use\n//     // '.', which is a valid fs.symlink target.\n//     src = src || '.';\n//   }\n\n//   try {\n//     const stats = await lstat(dest);\n//     if (stats.isSymbolicLink()) {\n//       const resolved = dest;\n//       if (resolved === src) {\n//         return;\n//       }\n//     }\n//   } catch (err) {\n//     if (err.code !== 'ENOENT') {\n//       throw err;\n//     }\n//   }\n\n//   // We use rimraf for unlink which never throws an ENOENT on missing target\n//   await unlink(dest);\n\n//   if (process.platform === 'win32') {\n//     // use directory junctions if possible on win32, this requires absolute paths\n//     await fsSymlink(src, dest, 'junction');\n//   } else {\n//     await fsSymlink(src, dest);\n//   }\n// }\n\nexport type WalkFiles = Array<{\n  relative: string;\n  absolute: string;\n  basename: string;\n  mtime: number;\n}>;\n\nexport async function walk(\n  dir: string,\n  relativeDir?: string,\n  ignoreBasenames: Set<string> = new Set(),\n): Promise<WalkFiles> {\n  let files = [];\n\n  let filenames = await readdir(dir);\n  if (ignoreBasenames.size) {\n    filenames = filenames.filter((name) => !ignoreBasenames.has(name));\n  }\n\n  for (const name of filenames) {\n    const relative = relativeDir ? path.join(relativeDir, name) : name;\n    const loc = path.join(dir, name);\n    const stat = await lstat(loc);\n\n    files.push({\n      relative,\n      basename: name,\n      absolute: loc,\n      mtime: +stat.mtime,\n    });\n\n    if (stat.isDirectory()) {\n      files = files.concat(await walk(loc, relative, ignoreBasenames));\n    }\n  }\n\n  return files;\n}\n\n// export async function getFileSizeOnDisk(loc: string): Promise<number> {\n//   const stat = await lstat(loc);\n//   const {size, blksize: blockSize} = stat;\n\n//   return Math.ceil(size / blockSize) * blockSize;\n// }\n\n// export function normalizeOS(body: string): string {\n//   return body.replace(/\\r\\n/g, '\\n');\n// }\n\nconst cr = '\\r'.charCodeAt(0);\nconst lf = '\\n'.charCodeAt(0);\n\nasync function getEolFromFile(path: string): Promise<string | void> {\n  if (!(await exists(path))) {\n    return undefined;\n  }\n\n  const buffer = await readFileBuffer(path);\n\n  for (let i = 0; i < buffer.length; ++i) {\n    if (buffer[i] === cr) {\n      return '\\r\\n';\n    }\n    if (buffer[i] === lf) {\n      return '\\n';\n    }\n  }\n  return undefined;\n}\n\nexport async function writeFilePreservingEol(path: string, data: string): Promise<void> {\n  const eol = (await getEolFromFile(path)) || os.EOL;\n  if (eol !== '\\n') {\n    data = data.replace(/\\n/g, eol);\n  }\n  await writeFile(path, data);\n}\n\n// export async function hardlinksWork(dir: string): Promise<boolean> {\n//   const filename = 'test-file' + Math.random();\n//   const file = path.join(dir, filename);\n//   const fileLink = path.join(dir, filename + '-link');\n//   try {\n//     await writeFile(file, 'test');\n//     await link(file, fileLink);\n//   } catch (err) {\n//     return false;\n//   } finally {\n//     await unlink(file);\n//     await unlink(fileLink);\n//   }\n//   return true;\n// }\n\n// // not a strict polyfill for Node's fs.mkdtemp\n// export async function makeTempDir(prefix?: string): Promise<string> {\n//   const dir = path.join(os.tmpdir(), `pika-${prefix || ''}-${Date.now()}-${Math.random()}`);\n//   await unlink(dir);\n//   await mkdirp(dir);\n//   return dir;\n// }\n\n// export async function readFirstAvailableStream(paths: Iterable<string>): Promise<?ReadStream> {\n//   for (const path of paths) {\n//     try {\n//       const fd = await open(path, 'r');\n//       return fs.createReadStream(path, {fd});\n//     } catch (err) {\n//       // Try the next one\n//     }\n//   }\n//   return null;\n// }\n\n// export async function getFirstSuitableFolder(\n//   paths: Iterable<string>,\n//   mode: number = constants.W_OK | constants.X_OK, // eslint-disable-line no-bitwise\n// ): Promise<FolderQueryResult> {\n//   const result: FolderQueryResult = {\n//     skipped: [],\n//     folder: null,\n//   };\n\n//   for (const folder of paths) {\n//     try {\n//       await mkdirp(folder);\n//       await access(folder, mode);\n\n//       result.folder = folder;\n\n//       return result;\n//     } catch (error) {\n//       result.skipped.push({\n//         error,\n//         folder,\n//       });\n//     }\n//   }\n//   return result;\n// }\n"
  },
  {
    "path": "src/util/map.ts",
    "content": "export default function nullify<T>(obj?: T): T {\n  if (Array.isArray(obj)) {\n    for (const item of obj) {\n      nullify(item);\n    }\n  } else if ((obj !== null && typeof obj === 'object') || typeof obj === 'function') {\n    Object.setPrototypeOf(obj, null);\n\n    // for..in can only be applied to 'object', not 'function'\n    if (typeof obj === 'object') {\n      for (const key in obj) {\n        nullify(obj[key]);\n      }\n    }\n  }\n\n  return obj;\n}\n"
  },
  {
    "path": "src/util/misc.ts",
    "content": "/* @flow */\n\nexport function sortAlpha(a: string, b: string): number {\n  // sort alphabetically in a deterministic way\n  const shortLen = Math.min(a.length, b.length);\n  for (let i = 0; i < shortLen; i++) {\n    const aChar = a.charCodeAt(i);\n    const bChar = b.charCodeAt(i);\n    if (aChar !== bChar) {\n      return aChar - bChar;\n    }\n  }\n  return a.length - b.length;\n}\n\nexport function sortOptionsByFlags(a: any, b: any): number {\n  const aOpt = a.flags.replace(/-/g, '');\n  const bOpt = b.flags.replace(/-/g, '');\n  return sortAlpha(aOpt, bOpt);\n}\n\nexport function entries<T>(obj: {[key: string]: T}): Array<[string, T]> {\n  const entries = [];\n  if (obj) {\n    for (const key in obj) {\n      entries.push([key, obj[key]]);\n    }\n  }\n  return entries;\n}\n\nexport function removePrefix(pattern: string, prefix: string): string {\n  if (pattern.startsWith(prefix)) {\n    pattern = pattern.slice(prefix.length);\n  }\n\n  return pattern;\n}\n\nexport function removeSuffix(pattern: string, suffix: string): string {\n  if (pattern.endsWith(suffix)) {\n    return pattern.slice(0, -suffix.length);\n  }\n\n  return pattern;\n}\n\nexport function addSuffix(pattern: string, suffix: string): string {\n  if (!pattern.endsWith(suffix)) {\n    return pattern + suffix;\n  }\n\n  return pattern;\n}\n\nexport function hyphenate(str: string): string {\n  return str.replace(/[A-Z]/g, (match) => {\n    return '-' + match.charAt(0).toLowerCase();\n  });\n}\n\nexport function compareSortedArrays<T>(array1: Array<T>, array2: Array<T>): boolean {\n  if (array1.length !== array2.length) {\n    return false;\n  }\n  for (let i = 0, len = array1.length; i < len; i++) {\n    if (array1[i] !== array2[i]) {\n      return false;\n    }\n  }\n  return true;\n}\n\nexport function sleep(ms: number): Promise<void> {\n  return new Promise((resolve) => {\n    setTimeout(resolve, ms);\n  });\n}\n"
  },
  {
    "path": "src/util/normalize-manifest/fix.ts",
    "content": "import {MANIFEST_FIELDS} from '../../constants.js';\nimport {Reporter} from '../../reporters/index.js';\nimport {isValidLicense} from './util.js';\nimport {normalizePerson, extractDescription} from './util.js';\nimport inferLicense from './infer-license.js';\nimport * as fs from '../fs.js';\n\nimport semver from 'semver';\nimport * as path from 'path';\nimport * as nodeUrl from 'url';\n\nconst LICENSE_RENAMES = {\n  'MIT/X11': 'MIT',\n  X11: 'MIT',\n};\n\ntype Dict<T> = {\n  [key: string]: T;\n};\n\ntype WarnFunction = (msg: string) => void;\n\nexport default (async function (\n  info: Dict<any>,\n  moduleLoc: string,\n  reporter: Reporter,\n  warn: WarnFunction,\n): Promise<void> {\n  const files = await fs.readdir(moduleLoc);\n\n  // clean info.version\n  if (typeof info.version === 'string') {\n    info.version = semver.clean(info.version) || info.version;\n  }\n\n  // if name or version aren't set then set them to empty strings\n  info.name = info.name || '';\n  info.version = info.version || '';\n\n  // if the man field is a string then coerce it to an array\n  if (typeof info.man === 'string') {\n    info.man = [info.man];\n  }\n\n  // if the keywords field is a string then split it on any whitespace\n  if (typeof info.keywords === 'string') {\n    info.keywords = info.keywords.split(/\\s+/g);\n  }\n\n  // if there's no contributors field but an authors field then expand it\n  if (!info.contributors && files.indexOf('AUTHORS') >= 0) {\n    const authorsFilepath = path.join(moduleLoc, 'AUTHORS');\n    const authorsFilestats = await fs.stat(authorsFilepath);\n    if (authorsFilestats.isFile()) {\n      let authors = await fs.readFile(authorsFilepath);\n      info.contributors = authors\n        .split(/\\r?\\n/g) // split on lines\n        .map((line): string => line.replace(/^\\s*#.*$/, '').trim()) // remove comments\n        .filter((line): boolean => !!line); // remove empty lines;\n    }\n  }\n\n  // expand people fields to objects\n  if (typeof info.author === 'string' || typeof info.author === 'object') {\n    info.author = normalizePerson(info.author);\n  }\n  if (Array.isArray(info.contributors)) {\n    info.contributors = info.contributors.map(normalizePerson);\n  }\n  if (Array.isArray(info.maintainers)) {\n    info.maintainers = info.maintainers.map(normalizePerson);\n  }\n\n  // if there's no readme field then load the README file from the cwd\n  if (!info.readme) {\n    const readmeCandidates = files\n      .filter((filename): boolean => {\n        const lower = filename.toLowerCase();\n        return lower === 'readme' || lower.indexOf('readme.') === 0;\n      })\n      .sort((filename1, filename2): number => {\n        // favor files with extensions\n        return filename2.indexOf('.') - filename1.indexOf('.');\n      });\n\n    for (const readmeFilename of readmeCandidates) {\n      const readmeFilepath = path.join(moduleLoc, readmeFilename);\n      const readmeFileStats = await fs.stat(readmeFilepath);\n      if (readmeFileStats.isFile()) {\n        info.readmeFilename = readmeFilename;\n        info.readme = await fs.readFile(readmeFilepath);\n        break;\n      }\n    }\n  }\n\n  // if there's no description then take the first paragraph from the readme\n  if (!info.description && info.readme) {\n    const desc = extractDescription(info.readme);\n    if (desc) {\n      info.description = desc;\n    }\n  }\n\n  // support array of engine keys\n  if (Array.isArray(info.engines)) {\n    const engines = {};\n    for (const str of info.engines) {\n      if (typeof str === 'string') {\n        const [name, ...patternParts] = str.trim().split(/ +/g);\n        engines[name] = patternParts.join(' ');\n      }\n    }\n    info.engines = engines;\n  }\n\n  // allow bugs to be specified as a string, expand it to an object with a single url prop\n  if (typeof info.bugs === 'string') {\n    info.bugs = {url: info.bugs};\n  }\n\n  // normalize homepage url to http\n  if (typeof info.homepage === 'string') {\n    const parts = nodeUrl.parse(info.homepage);\n    parts.protocol = parts.protocol || 'http:';\n    if (parts.pathname && !parts.hostname) {\n      parts.hostname = parts.pathname;\n      parts.pathname = '';\n    }\n    info.homepage = nodeUrl.format(parts);\n  }\n\n  // if the `bin` field is as string then expand it to an object with a single property\n  // based on the original `bin` field and `name field`\n  // { name: \"foo\", bin: \"cli.js\" } -> { name: \"foo\", bin: { foo: \"cli.js\" } }\n  if (typeof info.name === 'string' && typeof info.bin === 'string' && info.bin.length > 0) {\n    // Remove scoped package name for consistency with NPM's bin field fixing behaviour\n    const name = info.name.replace(/^@[^\\/]+\\//, '');\n    info.bin = {[name]: info.bin};\n  }\n\n  // bundleDependencies is an alias for bundledDependencies\n  if (info.bundledDependencies) {\n    info.bundleDependencies = info.bundledDependencies;\n    delete info.bundledDependencies;\n  }\n\n  let scripts: {[key: string]: string};\n\n  // dummy script object to shove file inferred scripts onto\n  if (info.scripts && typeof info.scripts === 'object') {\n    scripts = info.scripts;\n  } else {\n    scripts = {};\n  }\n\n  // if there's a server.js file and no start script then set it to `node server.js`\n  if (!scripts.start && files.indexOf('server.js') >= 0) {\n    scripts.start = 'node server';\n  }\n\n  // if there's a binding.gyp file and no install script then set it to `node-gyp rebuild`\n  if (!scripts.install && files.indexOf('binding.gyp') >= 0) {\n    scripts.install = 'node-gyp rebuild';\n  }\n\n  // set scripts if we've polluted the empty object\n  if (Object.keys(scripts).length) {\n    info.scripts = scripts;\n  }\n\n  const dirs = info.directories;\n\n  if (dirs && typeof dirs === 'object') {\n    const binDir = dirs.bin;\n\n    if (!info.bin && binDir && typeof binDir === 'string') {\n      const bin = (info.bin = {});\n      const fullBinDir = path.join(moduleLoc, binDir);\n\n      if (await fs.exists(fullBinDir)) {\n        for (const scriptName of await fs.readdir(fullBinDir)) {\n          if (scriptName[0] === '.') {\n            continue;\n          }\n          bin[scriptName] = path.join('.', binDir, scriptName);\n        }\n      } else {\n        warn(reporter.lang('manifestDirectoryNotFound', binDir, info.name));\n      }\n    }\n\n    const manDir = dirs.man;\n\n    if (!info.man && typeof manDir === 'string') {\n      const man = (info.man = []);\n      const fullManDir = path.join(moduleLoc, manDir);\n\n      if (await fs.exists(fullManDir)) {\n        for (const filename of await fs.readdir(fullManDir)) {\n          if (/^(.*?)\\.[0-9]$/.test(filename)) {\n            man.push(path.join('.', manDir, filename));\n          }\n        }\n      } else {\n        warn(reporter.lang('manifestDirectoryNotFound', manDir, info.name));\n      }\n    }\n  }\n\n  delete info.directories;\n\n  // normalize licenses field\n  const licenses = info.licenses;\n  if (Array.isArray(licenses) && !info.license) {\n    let licenseTypes = [];\n\n    for (let license of licenses) {\n      if (license && typeof license === 'object') {\n        license = license.type;\n      }\n      if (typeof license === 'string') {\n        licenseTypes.push(license);\n      }\n    }\n\n    licenseTypes = licenseTypes.filter(isValidLicense);\n\n    if (licenseTypes.length === 1) {\n      info.license = licenseTypes[0];\n    } else if (licenseTypes.length) {\n      info.license = `(${licenseTypes.join(' OR ')})`;\n    }\n  }\n\n  const license = info.license;\n\n  // normalize license\n  if (license && typeof license === 'object') {\n    info.license = license.type;\n  }\n\n  // get license file\n  const licenseFile = files.find((filename): boolean => {\n    const lower = filename.toLowerCase();\n    return (\n      lower === 'license' || lower.startsWith('license.') || lower === 'unlicense' || lower.startsWith('unlicense.')\n    );\n  });\n  if (licenseFile) {\n    const licenseFilepath = path.join(moduleLoc, licenseFile);\n    const licenseFileStats = await fs.stat(licenseFilepath);\n    if (licenseFileStats.isFile()) {\n      const licenseContent = await fs.readFile(licenseFilepath);\n      const inferredLicense = inferLicense(licenseContent);\n      info.licenseText = licenseContent;\n\n      const license = info.license;\n\n      if (typeof license === 'string') {\n        if (inferredLicense && isValidLicense(inferredLicense) && !isValidLicense(license)) {\n          // some packages don't specify their license version but we can infer it based on their license file\n          const basicLicense = license.toLowerCase().replace(/(-like|\\*)$/g, '');\n          const expandedLicense = inferredLicense.toLowerCase();\n          if (expandedLicense.startsWith(basicLicense)) {\n            // TODO consider doing something to notify the user\n            info.license = inferredLicense;\n          }\n        }\n      } else if (inferredLicense) {\n        // if there's no license then infer it based on the license file\n        info.license = inferredLicense;\n      } else {\n        // valid expression to refer to a license in a file\n        info.license = `SEE LICENSE IN ${licenseFile}`;\n      }\n    }\n  }\n\n  if (typeof info.license === 'string') {\n    // sometimes licenses are known by different names, reduce them\n    info.license = LICENSE_RENAMES[info.license] || info.license;\n  } else if (typeof info.readme === 'string') {\n    // the license might be at the bottom of the README\n    const inferredLicense = inferLicense(info.readme);\n    if (inferredLicense) {\n      info.license = inferredLicense;\n    }\n  }\n\n  // get notice file\n  const noticeFile = files.find((filename): boolean => {\n    const lower = filename.toLowerCase();\n    return lower === 'notice' || lower.startsWith('notice.');\n  });\n  if (noticeFile) {\n    const noticeFilepath = path.join(moduleLoc, noticeFile);\n    const noticeFileStats = await fs.stat(noticeFilepath);\n    if (noticeFileStats.isFile()) {\n      info.noticeText = await fs.readFile(noticeFilepath);\n    }\n  }\n\n  for (const dependencyType of MANIFEST_FIELDS) {\n    const dependencyList = info[dependencyType];\n    if (dependencyList && typeof dependencyList === 'object') {\n      delete dependencyList['//'];\n      for (const name in dependencyList) {\n        dependencyList[name] = dependencyList[name] || '';\n      }\n    }\n  }\n});\n"
  },
  {
    "path": "src/util/normalize-manifest/for-publish.ts",
    "content": "import {Manifest} from '../../types';\nimport Config from '../../config';\n\nexport async function generatePublishManifest(\n  manifest: any,\n  config: Config,\n  _dists?: Array<[Function, any]>,\n): Promise<object> {\n  const {\n    name,\n    version,\n    description,\n    keywords,\n    homepage,\n    bugs,\n    bin,\n    license,\n    authors,\n    contributors,\n    man,\n    sideEffects,\n    repository,\n    dependencies,\n    peerDependencies,\n    devDependencies,\n    bundledDependencies,\n    optionalDependencies,\n    engines,\n    enginesStrict,\n    private: priv,\n    publishConfig,\n  } = manifest;\n\n  const newManifest = {\n    name,\n    description,\n    version,\n    license,\n    bin,\n    files: ['dist-*/', 'bin/'],\n    pika: true,\n    sideEffects: sideEffects || false,\n    keywords,\n    homepage,\n    bugs,\n    authors,\n    contributors,\n    man,\n    repository,\n    dependencies: dependencies || {},\n    peerDependencies,\n    devDependencies,\n    bundledDependencies,\n    optionalDependencies,\n    engines,\n    enginesStrict,\n    private: priv,\n    publishConfig,\n  };\n\n  const dists = _dists || (await config.getDistributions());\n  for (const [runner, options] of dists) {\n    if (runner.manifest) {\n      await runner.manifest(newManifest, {\n        cwd: config.cwd,\n        isFull: true,\n        manifest,\n        options,\n      });\n    }\n  }\n\n  newManifest.pika = true;\n  return newManifest;\n}\n\nexport function generatePrettyManifest(manifest) {\n  return JSON.stringify(\n    {\n      ...manifest,\n      dependencies: Object.keys(manifest.dependencies).length === 0 ? {} : '{ ... }',\n    },\n    null,\n    2,\n  );\n}\n"
  },
  {
    "path": "src/util/normalize-manifest/index.ts",
    "content": "import {Manifest} from '../../types.js';\nimport Config from '../../config.js';\nimport validate from './validate.js';\nimport fix from './fix.js';\n\nimport * as path from 'path';\n\nexport default (async function (info: any, moduleLoc: string, config: Config, isRoot: boolean): Promise<Manifest> {\n  // Append dependencies\n  // if (depInfo) {\n  //   info.dependencies = depInfo.main;\n  //   info.devDependencies = depInfo.dev;\n  // }\n  // create human readable name\n  const {name, version} = info;\n  let human: string | undefined;\n  if (typeof name === 'string') {\n    human = name;\n  }\n  if (human && typeof version === 'string' && version) {\n    human += `@${version}`;\n  }\n  if (isRoot && info._loc) {\n    human = path.relative(config.cwd, info._loc);\n  }\n\n  function warn(msg: string) {\n    if (human) {\n      msg = `${human}: ${msg}`;\n    }\n    config.reporter.warn(msg);\n  }\n\n  await fix(info, moduleLoc, config.reporter, warn);\n\n  try {\n    validate(info, isRoot, config.reporter, warn);\n  } catch (err) {\n    if (human) {\n      err.message = `${human}: ${err.message}`;\n    }\n    throw err;\n  }\n\n  return info;\n});\n"
  },
  {
    "path": "src/util/normalize-manifest/infer-license.ts",
    "content": "import LICENSES from './licenses.js';\n\nfunction clean(str: string): string {\n  return str\n    .replace(/[^A-Za-z\\s]/g, ' ')\n    .replace(/[\\s]+/g, ' ')\n    .trim()\n    .toLowerCase();\n}\n\nconst REGEXES: {[key: string]: Array<RegExp>} = {\n  Apache: [/Apache License\\b/],\n  BSD: [/BSD\\b/],\n  ISC: [/The ISC License/, /ISC\\b/],\n  MIT: [/MIT\\b/],\n  Unlicense: [/http:\\/\\/unlicense.org\\//],\n  WTFPL: [/DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE/, /WTFPL\\b/],\n};\n\nexport default function inferLicense(license: string): string | null {\n  // check if we have any explicit licenses\n  const cleanLicense = clean(license);\n  for (const licenseName in LICENSES) {\n    const testLicense = LICENSES[licenseName];\n    if (cleanLicense.search(testLicense) >= 0) {\n      return licenseName;\n    }\n  }\n\n  // infer based on some keywords\n  for (const licenseName in REGEXES) {\n    for (const regex of REGEXES[licenseName]) {\n      if (license.search(regex) >= 0) {\n        return `${licenseName}*`;\n      }\n    }\n  }\n\n  return null;\n}\n"
  },
  {
    "path": "src/util/normalize-manifest/licenses.ts",
    "content": "export default {\n  'Apache-2.0': new RegExp(\n    '(licensed under the apache license version the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license$|apache license version january http www apache org licenses terms and conditions for use reproduction and distribution definitions license shall mean the terms and conditions for use reproduction and distribution as defined by sections through of this document licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the license legal entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity for the purposes of this definition control means i the power direct or indirect to cause the direction or management of such entity whether by contract or otherwise or ii ownership of fifty percent or more of the outstanding shares or iii beneficial ownership of such entity you or your shall mean an individual or legal entity exercising permissions granted by this license source form shall mean the preferred form for making modifications including but not limited to software source code documentation source and configuration files object form shall mean any form resulting from mechanical transformation or translation of a source form including but not limited to compiled object code generated documentation and conversions to other media types work shall mean the work of authorship whether in source or object form made available under the license as indicated by a copyright notice that is included in or attached to the work an example is provided in the appendix below derivative works shall mean any work whether in source or object form that is based on or derived from the work and for which the editorial revisions annotations elaborations or other modifications represent as a whole an original work of authorship for the purposes of this license derivative works shall not include works that remain separable from or merely link or bind by name to the interfaces of the work and derivative works thereof contribution shall mean any work of authorship including the original version of the work and any modifications or additions to that work or derivative works thereof that is intentionally submitted to licensor for inclusion in the work by the copyright owner or by an individual or legal entity authorized to submit on behalf of the copyright owner for the purposes of this definition submitted means any form of electronic verbal or written communication sent to the licensor or its representatives including but not limited to communication on electronic mailing lists source code control systems and issue tracking systems that are managed by or on behalf of the licensor for the purpose of discussing and improving the work but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as not a contribution contributor shall mean licensor and any individual or legal entity on behalf of whom a contribution has been received by licensor and subsequently incorporated within the work grant of copyright license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable copyright license to reproduce prepare derivative works of publicly display publicly perform sublicense and distribute the work and such derivative works in source or object form grant of patent license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable except as stated in this section patent license to make have made use offer to sell sell import and otherwise transfer the work where such license applies only to those patent claims licensable by such contributor that are necessarily infringed by their contribution s alone or by combination of their contribution s with the work to which such contribution s was submitted if you institute patent litigation against any entity including a cross claim or counterclaim in a lawsuit alleging that the work or a contribution incorporated within the work constitutes direct or contributory patent infringement then any patent licenses granted to you under this license for that work shall terminate as of the date such litigation is filed redistribution you may reproduce and distribute copies of the work or derivative works thereof in any medium with or without modifications and in source or object form provided that you meet the following conditions a you must give any other recipients of the work or derivative works a copy of this license and b you must cause any modified files to carry prominent notices stating that you changed the files and c you must retain in the source form of any derivative works that you distribute all copyright patent trademark and attribution notices from the source form of the work excluding those notices that do not pertain to any part of the derivative works and d if the work includes a notice text file as part of its distribution then any derivative works that you distribute must include a readable copy of the attribution notices contained within such notice file excluding those notices that do not pertain to any part of the derivative works in at least one of the following places within a notice text file distributed as part of the derivative works within the source form or documentation if provided along with the derivative works or within a display generated by the derivative works if and wherever such third party notices normally appear the contents of the notice file are for informational purposes only and do not modify the license you may add your own attribution notices within derivative works that you distribute alongside or as an addendum to the notice text from the work provided that such additional attribution notices cannot be construed as modifying the license you may add your own copyright statement to your modifications and may provide additional or different license terms and conditions for use reproduction or distribution of your modifications or for any such derivative works as a whole provided your use reproduction and distribution of the work otherwise complies with the conditions stated in this license submission of contributions unless you explicitly state otherwise any contribution intentionally submitted for inclusion in the work by you to the licensor shall be under the terms and conditions of this license without any additional terms or conditions notwithstanding the above nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with licensor regarding such contributions trademarks this license does not grant permission to use the trade names trademarks service marks or product names of the licensor except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the notice file disclaimer of warranty unless required by applicable law or agreed to in writing licensor provides the work and each contributor provides its contributions on an as is basis without warranties or conditions of any kind either express or implied including without limitation any warranties or conditions of title non infringement merchantability or fitness for a particular purpose you are solely responsible for determining the appropriateness of using or redistributing the work and assume any risks associated with your exercise of permissions under this license limitation of liability in no event and under no legal theory whether in tort including negligence contract or otherwise unless required by applicable law such as deliberate and grossly negligent acts or agreed to in writing shall any contributor be liable to you for damages including any direct indirect special incidental or consequential damages of any character arising as a result of this license or out of the use or inability to use the work including but not limited to damages for loss of goodwill work stoppage computer failure or malfunction or any and all other commercial damages or losses even if such contributor has been advised of the possibility of such damages accepting warranty or additional liability while redistributing the work or derivative works thereof you may choose to offer and charge a fee for acceptance of support warranty indemnity or other liability obligations and or rights consistent with this license however in accepting such obligations you may act only on your own behalf and on your sole responsibility not on behalf of any other contributor and only if you agree to indemnify defend and hold each contributor harmless for any liability incurred by or claims asserted against such contributor by reason of your accepting any such warranty or additional liability end of terms and conditions$)',\n    'g',\n  ),\n  'BSD-2-Clause': new RegExp(\n    '(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this(.*?| )is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this(.*?| )even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$)',\n    'g',\n  ),\n  'BSD-3-Clause': new RegExp(\n    '(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name of(.*?| )nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution the names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall the copyright holders and contributors be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name(.*?| )nor the names of(.*?| )contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by(.*?| )as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$))',\n    'g',\n  ),\n  MIT: new RegExp(\n    'permission is hereby granted free of charge to any person obtaining a copy of this software and associated documentation files the software to deal in the software without restriction including without limitation the rights to use copy modify merge publish distribute sublicense and or sell copies of the software and to permit persons to whom the software is furnished to do so subject to the following conditions the above copyright notice and this permission notice shall be included in all copies or substantial portions of the software the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors or copyright holders be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software$',\n    'g',\n  ),\n  Unlicense: new RegExp(\n    'this is free and unencumbered software released into the public domain anyone is free to copy modify publish use compile sell or distribute this software either in source code form or as a compiled binary for any purpose commercial or non commercial and by any means in jurisdictions that recognize copyright laws the author or authors of this software dedicate any and all copyright interest in the software to the public domain we make this dedication for the benefit of the public at large and to the detriment of our heirs and successors we intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software for more information please refer to wildcard$',\n    'g',\n  ),\n};\n"
  },
  {
    "path": "src/util/normalize-manifest/typos.ts",
    "content": "export default {\n  autohr: 'author',\n  autor: 'author',\n  contributers: 'contributors',\n  depdenencies: 'dependencies',\n  dependancies: 'dependencies',\n  dependecies: 'dependencies',\n  depends: 'dependencies',\n  'dev-dependencies': 'devDependencies',\n  devDependences: 'devDependencies',\n  devDepenencies: 'devDependencies',\n  devEependencies: 'devDependencies',\n  devdependencies: 'devDependencies',\n  hampage: 'homepage',\n  hompage: 'homepage',\n  prefereGlobal: 'preferGlobal',\n  publicationConfig: 'publishConfig',\n  repo: 'repository',\n  repostitory: 'repository',\n  script: 'scripts',\n};\n"
  },
  {
    "path": "src/util/normalize-manifest/util.ts",
    "content": "import {PersonObject} from '../../types.js';\n\nimport validateLicense from 'validate-npm-package-license';\n\nexport function isValidLicense(license: string): boolean {\n  return !!license && validateLicense(license).validForNewPackages;\n}\n\nexport function stringifyPerson(person: any): any {\n  if (!person || typeof person !== 'object') {\n    return person;\n  }\n\n  const parts = [];\n  if (person.name) {\n    parts.push(person.name);\n  }\n\n  const email = person.email || person.mail;\n  if (typeof email === 'string') {\n    parts.push(`<${email}>`);\n  }\n\n  const url = person.url || person.web;\n  if (typeof url === 'string') {\n    parts.push(`(${url})`);\n  }\n\n  return parts.join(' ');\n}\n\nexport function parsePerson(person: any): PersonObject {\n  if (typeof person !== 'string') {\n    return person;\n  }\n\n  // format: name (url) <email>\n  const obj: PersonObject = {};\n\n  let name = person.match(/^([^\\(<]+)/);\n  if (name && name[0].trim()) {\n    obj.name = name[0].trim();\n  }\n\n  const email = person.match(/<([^>]+)>/);\n  if (email) {\n    obj.email = email[1];\n  }\n\n  const url = person.match(/\\(([^\\)]+)\\)/);\n  if (url) {\n    obj.url = url[1];\n  }\n\n  return obj;\n}\n\nexport function normalizePerson(person: any): any | PersonObject {\n  return parsePerson(stringifyPerson(person));\n}\n\nexport function extractDescription(readme: any): string {\n  if (typeof readme !== 'string' || readme === '') {\n    return undefined;\n  }\n\n  // split into lines\n  const lines = readme\n    .trim()\n    .split('\\n')\n    .map((line): string => line.trim());\n\n  // find the start of the first paragraph, ignore headings\n  let start = 0;\n  for (; start < lines.length; start++) {\n    const line = lines[start];\n    if (line && line.match(/^(#|$)/)) {\n      // line isn't empty and isn't a heading so this is the start of a paragraph\n      start++;\n      break;\n    }\n  }\n\n  // skip newlines from the header to the first line\n  while (start < lines.length && !lines[start]) {\n    start++;\n  }\n\n  // continue to the first non empty line\n  let end = start;\n  while (end < lines.length && lines[end]) {\n    end++;\n  }\n\n  return lines.slice(start, end).join(' ');\n}\n"
  },
  {
    "path": "src/util/normalize-manifest/validate.ts",
    "content": "import {Reporter} from '../../reporters/index.js';\nimport {MessageError} from '@pika/types';\nimport typos from './typos.js';\n\nimport isBuiltinModule from 'is-builtin-module';\n\nconst strings = ['name', 'version'];\n\nconst dependencyKeys = [\n  // npm registry will include optionalDependencies in dependencies and we'll want to dedupe them from the\n  // other fields first\n  'optionalDependencies',\n\n  // it's seemingly common to include a dependency in dependencies and devDependencies of the same name but\n  // different ranges, this can cause a lot of issues with our determinism and the behaviour of npm is\n  // currently unspecified.\n  'dependencies',\n\n  'devDependencies',\n];\n\nfunction isValidName(name: string): boolean {\n  return !name.match(/[\\/@\\s\\+%:]/) && encodeURIComponent(name) === name;\n}\n\nfunction isValidScopedName(name: string): boolean {\n  if (name[0] !== '@') {\n    return false;\n  }\n\n  const parts = name.slice(1).split('/');\n  return parts.length === 2 && isValidName(parts[0]) && isValidName(parts[1]);\n}\n\nexport function isValidPackageName(name: string): boolean {\n  return isValidName(name) || isValidScopedName(name);\n}\n\ntype WarnFunction = (msg: string) => void;\n\nexport default function (info: any, isRoot: boolean, reporter: Reporter, warn: WarnFunction) {\n  if (isRoot) {\n    for (const key in typos) {\n      if (key in info) {\n        warn(reporter.lang('manifestPotentialTypo', key, typos[key]));\n      }\n    }\n  }\n\n  // validate name\n  const {name} = info;\n  if (typeof name === 'string') {\n    if (isRoot && isBuiltinModule(name)) {\n      warn(reporter.lang('manifestBuiltinModule', name));\n    }\n\n    // cannot start with a dot\n    if (name[0] === '.') {\n      throw new MessageError(reporter.lang('manifestNameDot'));\n    }\n\n    // cannot contain the following characters\n    if (!isValidPackageName(name)) {\n      throw new MessageError(reporter.lang('manifestNameIllegalChars'));\n    }\n\n    // cannot equal node_modules or favicon.ico\n    const lower = name.toLowerCase();\n    if (lower === 'node_modules' || lower === 'favicon.ico') {\n      throw new MessageError(reporter.lang('manifestNameBlacklisted'));\n    }\n  }\n\n  // Only care if you are trying to publish to npm.\n  // // validate license\n  // if (isRoot && !info.private) {\n  //   if (typeof info.license === 'string') {\n  //     const license = info.license.replace(/\\*$/g, '');\n  //     if (!isValidLicense(license)) {\n  //       warn(reporter.lang('manifestLicenseInvalid'));\n  //     }\n  //   } else {\n  //     warn(reporter.lang('manifestLicenseNone'));\n  //   }\n  // }\n\n  // validate strings\n  for (const key of strings) {\n    const val = info[key];\n    if (val && typeof val !== 'string') {\n      throw new MessageError(reporter.lang('manifestStringExpected', key));\n    }\n  }\n\n  cleanDependencies(info, isRoot, reporter, warn);\n}\n\nexport function cleanDependencies(info: Object, isRoot: boolean, reporter: Reporter, warn: WarnFunction) {\n  // get dependency objects\n  const depTypes = [];\n  for (const type of dependencyKeys) {\n    const deps = info[type];\n    if (!deps || typeof deps !== 'object') {\n      continue;\n    }\n    depTypes.push([type, deps]);\n  }\n\n  // aggregate all non-trivial deps (not '' or '*')\n  const nonTrivialDeps: Map<string, {type: string; version: string}> = new Map();\n  for (const [type, deps] of depTypes) {\n    for (const name of Object.keys(deps)) {\n      const version = deps[name];\n      if (!nonTrivialDeps.has(name) && version && version !== '*') {\n        nonTrivialDeps.set(name, {type, version});\n      }\n    }\n  }\n\n  // overwrite first dep of package with non-trivial version, remove the rest\n  const setDeps: Set<string> = new Set();\n  for (const [type, deps] of depTypes) {\n    for (const name of Object.keys(deps)) {\n      let version = deps[name];\n\n      const dep = nonTrivialDeps.get(name);\n      if (dep) {\n        if (version && version !== '*' && version !== dep.version && isRoot) {\n          // only throw a warning when at the root\n          warn(reporter.lang('manifestDependencyCollision', dep.type, name, dep.version, type, version));\n        }\n        version = dep.version;\n      }\n\n      if (setDeps.has(name)) {\n        delete deps[name];\n      } else {\n        deps[name] = version;\n        setDeps.add(name);\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "src/util/promise.ts",
    "content": "export function wait(delay: number): Promise<void> {\n  return new Promise((resolve) => {\n    setTimeout(resolve, delay);\n  });\n}\n\nexport function promisify(fn: Function, firstData?: boolean): (...args: Array<any>) => Promise<any> {\n  return function (...args): Promise<any> {\n    return new Promise(function (resolve, reject) {\n      args.push(function (err, ...result) {\n        let res = result;\n\n        if (result.length <= 1) {\n          res = result[0];\n        }\n\n        if (firstData) {\n          res = err;\n          err = null;\n        }\n\n        if (err) {\n          reject(err);\n        } else {\n          resolve(res);\n        }\n      });\n\n      fn.apply(null, args);\n    });\n  };\n}\n\nexport function queue<T, U>(\n  arr: Array<U>,\n  promiseProducer: (result: U) => Promise<T>,\n  concurrency: number = Infinity,\n): Promise<Array<T>> {\n  concurrency = Math.min(concurrency, arr.length);\n\n  // clone\n  arr = arr.slice();\n\n  const results = [];\n  let total = arr.length;\n  if (!total) {\n    return Promise.resolve(results);\n  }\n\n  return new Promise((resolve, reject) => {\n    for (let i = 0; i < concurrency; i++) {\n      next();\n    }\n\n    function next() {\n      const item = arr.shift();\n      const promise = promiseProducer(item);\n\n      promise.then(function (result) {\n        results.push(result);\n\n        total--;\n        if (total === 0) {\n          resolve(results);\n        } else {\n          if (arr.length) {\n            next();\n          }\n        }\n      }, reject);\n    }\n  });\n}\n"
  },
  {
    "path": "src/util/signal-handler.ts",
    "content": "import {forwardSignalToSpawnedProcesses} from './child.js';\n\nfunction forwardSignalAndExit(signal: string) {\n  forwardSignalToSpawnedProcesses(signal);\n  // We want to exit immediately here since `SIGTERM` means that\n  // If we lose stdout messages due to abrupt exit, shoot the messenger?\n  process.exit(1); // eslint-disable-line no-process-exit\n}\n\nexport default function handleSignals() {\n  process.on('SIGTERM', () => {\n    forwardSignalAndExit('SIGTERM');\n  });\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"esModuleInterop\": true\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\"]\n}\n"
  }
]