Showing preview only (577K chars total). Download the full file or copy to clipboard to get everything.
Repository: snowpackjs/pack
Branch: master
Commit: db05a6c653f4
Files: 135
Total size: 536.7 KB
Directory structure:
gitextract_c_u851k3/
├── .babelrc
├── .github/
│ └── ISSUE_TEMPLATE.md
├── .gitignore
├── .prettierrc
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── checkpoint/
│ ├── LICENSE
│ ├── README.md
│ ├── dist-node/
│ │ ├── index.bin.js
│ │ └── index.js
│ ├── dist-src/
│ │ ├── commands/
│ │ │ └── build.js
│ │ ├── config.js
│ │ ├── constants.js
│ │ ├── errors.js
│ │ ├── index.js
│ │ ├── reporters/
│ │ │ ├── base-reporter.js
│ │ │ ├── console/
│ │ │ │ ├── console-reporter.js
│ │ │ │ ├── helpers/
│ │ │ │ │ └── tree-helper.js
│ │ │ │ ├── progress-bar.js
│ │ │ │ ├── spinner-progress.js
│ │ │ │ └── util.js
│ │ │ ├── format.js
│ │ │ ├── index.js
│ │ │ ├── json-reporter.js
│ │ │ ├── lang/
│ │ │ │ ├── en.js
│ │ │ │ └── index.js
│ │ │ ├── noop-reporter.js
│ │ │ └── types.js
│ │ ├── types.js
│ │ └── util/
│ │ ├── babel-plugin-import-rewrite.js
│ │ ├── babel-validate-specifier.js
│ │ ├── blocking-queue.js
│ │ ├── child.js
│ │ ├── conversion.js
│ │ ├── execute-lifecycle-script.js
│ │ ├── fix-cmd-win-slashes.js
│ │ ├── fs-normalized.js
│ │ ├── fs.js
│ │ ├── map.js
│ │ ├── misc.js
│ │ ├── normalize-manifest/
│ │ │ ├── fix.js
│ │ │ ├── for-publish.js
│ │ │ ├── index.js
│ │ │ ├── infer-license.js
│ │ │ ├── licenses.js
│ │ │ ├── typos.js
│ │ │ ├── util.js
│ │ │ └── validate.js
│ │ ├── promise.js
│ │ └── signal-handler.js
│ ├── dist-types/
│ │ ├── commands/
│ │ │ └── build.d.ts
│ │ ├── config.d.ts
│ │ ├── constants.d.ts
│ │ ├── errors.d.ts
│ │ ├── index.d.ts
│ │ ├── reporters/
│ │ │ ├── base-reporter.d.ts
│ │ │ ├── console/
│ │ │ │ ├── console-reporter.d.ts
│ │ │ │ ├── helpers/
│ │ │ │ │ └── tree-helper.d.ts
│ │ │ │ ├── progress-bar.d.ts
│ │ │ │ ├── spinner-progress.d.ts
│ │ │ │ └── util.d.ts
│ │ │ ├── format.d.ts
│ │ │ ├── index.d.ts
│ │ │ ├── json-reporter.d.ts
│ │ │ ├── lang/
│ │ │ │ ├── en.d.ts
│ │ │ │ └── index.d.ts
│ │ │ ├── noop-reporter.d.ts
│ │ │ └── types.d.ts
│ │ ├── types.d.ts
│ │ └── util/
│ │ ├── babel-plugin-import-rewrite.d.ts
│ │ ├── babel-validate-specifier.d.ts
│ │ ├── blocking-queue.d.ts
│ │ ├── child.d.ts
│ │ ├── conversion.d.ts
│ │ ├── execute-lifecycle-script.d.ts
│ │ ├── fix-cmd-win-slashes.d.ts
│ │ ├── fs-normalized.d.ts
│ │ ├── fs.d.ts
│ │ ├── map.d.ts
│ │ ├── misc.d.ts
│ │ ├── normalize-manifest/
│ │ │ ├── fix.d.ts
│ │ │ ├── for-publish.d.ts
│ │ │ ├── index.d.ts
│ │ │ ├── infer-license.d.ts
│ │ │ ├── licenses.d.ts
│ │ │ ├── typos.d.ts
│ │ │ ├── util.d.ts
│ │ │ └── validate.d.ts
│ │ ├── promise.d.ts
│ │ └── signal-handler.d.ts
│ └── package.json
├── package.json
├── src/
│ ├── commands/
│ │ └── build.ts
│ ├── config.ts
│ ├── constants.ts
│ ├── errors.ts
│ ├── index.ts
│ ├── reporters/
│ │ ├── base-reporter.ts
│ │ ├── console/
│ │ │ ├── console-reporter.ts
│ │ │ ├── helpers/
│ │ │ │ └── tree-helper.ts
│ │ │ ├── progress-bar.ts
│ │ │ ├── spinner-progress.ts
│ │ │ └── util.ts
│ │ ├── format.ts
│ │ ├── index.ts
│ │ ├── json-reporter.ts
│ │ ├── lang/
│ │ │ ├── en.ts
│ │ │ └── index.ts
│ │ ├── noop-reporter.ts
│ │ └── types.ts
│ ├── types.ts
│ └── util/
│ ├── babel-plugin-import-rewrite.ts
│ ├── babel-validate-specifier.ts
│ ├── blocking-queue.ts
│ ├── child.ts
│ ├── conversion.ts
│ ├── execute-lifecycle-script.ts
│ ├── fix-cmd-win-slashes.ts
│ ├── fs-normalized.ts
│ ├── fs.ts
│ ├── map.ts
│ ├── misc.ts
│ ├── normalize-manifest/
│ │ ├── fix.ts
│ │ ├── for-publish.ts
│ │ ├── index.ts
│ │ ├── infer-license.ts
│ │ ├── licenses.ts
│ │ ├── typos.ts
│ │ ├── util.ts
│ │ └── validate.ts
│ ├── promise.ts
│ └── signal-handler.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .babelrc
================================================
{
"presets": [],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
================================================
FILE: .github/ISSUE_TEMPLATE.md
================================================
To create a new issue or search existing discussions, start here:
👉 **https://www.pika.dev/packages/@pika/pack/discuss** 👈
All new issues created directly through GitHub will be closed.
Learn more: https://www.pika.dev/discussions
================================================
FILE: .gitignore
================================================
lib-node/
local/
.DS_Store
/pkg
/lib
/lib-legacy
/node_modules
*.log
/.nyc_output
/coverage
/dist-*
/dist
/dist-debug
/artifacts
/updates
/resources/winsetup/generated.wxs
/resources/winsetup/obj
/resources/winsetup/bin
/resources/win-chocolatey/tools/chocolateyinstall.ps1
.vs
*.msi
*.nupkg
test/fixtures/**/.fbkpm
/tmp/
/__tests__/fixtures/**/_*
/__tests__/fixtures/request-cache/GET/localhost/.bin
.idea
.pika-meta
.pnp.js
.pnp
/packages/lockfile/index.js
.vscode/
================================================
FILE: .prettierrc
================================================
{
"singleQuote": true,
"trailingComma": "all",
"bracketSpacing": false,
"printWidth": 120
}
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at fkschott@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to @pika/pack
All contributions are welcome!
## Building the Project
It 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.
```
git clone https://github.com/pikapkg/pack.git
npm install
npm run build
```
## Testing the Project
Writing unit tests for the project is still TODO. I know, I know, I'm more embarassed than anyone.
The 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.
```
npm t
```
================================================
FILE: LICENSE
================================================
"""
The MIT License
Copyright (c) 2019 Fred K. Schott
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.
""
This license applies to parts of @pika/pack originating from the
https://github.com/sindresorhus/np repository:
"""
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
"""
This license applies to parts of @pika/pack originating from the
https://github.com/yarnpkg/yarn repository:
"""
BSD 2-Clause License
For Yarn software
Copyright (c) 2016-present, Yarn Contributors. All rights reserved.
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 THE COPYRIGHT HOLDER OR 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.
"""
================================================
FILE: README.md
================================================
<p align="center">
<img alt="Logo" src="https://www.pika.dev/static/img/pika-pack-logo.jpg" width="280">
</p>
<p align="center">
<strong>@pika/pack</strong> • npm package building, reimagined.
</p>
<p align="center">
<img alt="Demo" src="https://www.pika.dev/static/img/pack-build-demo.gif" width="720">
</p>
## @pika/pack helps you build amazing packages without the hassle:
- **Simple** ⚡️ Use pre-configured plugins to build your package for you.
- **Flexible** 🏋️♀️ Choose plugins and optimizations to match your needs.
- **Holistic** ⚛️ Let us build the entire package... *including package.json.*
## Quickstart
```bash
npx @pika/pack # Run once.
npm install --dev @pika/pack # Or, run multiple times using "pika pack" in any package.json scripts
```
😎🆒! 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***.
### 1. Create a project pipeline out of simple, pluggable builders.
```js
// Before: Your top-level package.json manifest:
{
"name": "simple-package",
"version": "1.0.0",
"@pika/pack": {
"pipeline": [
["@pika/plugin-standard-pkg", {"exclude": ["__tests__/**/*"]}],
["@pika/plugin-build-node"],
["@pika/plugin-build-web"],
["@pika/plugin-build-types"]
]
}
}
```
Builders 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).
### 2. Builders handle everything, including package configuration.
```js
// After: your built "pkg/" package.json manifest:
{
"name": "simple-package",
"version": "1.0.0",
// Multiple distributions, built & configured automatically:
"esnext": "dist-src/index.js",
"main": "dist-node/index.js",
"module": "dist-web/index.js",
"types": "dist-types/index.d.ts",
// With sensible package defaults:
"sideEffects": false,
"files": ["dist-*/", "assets/", "bin/"]
}
```
This 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.
## Build Plugins
**[Check out the full list](https://github.com/pikapkg/builders)** of official & community-written @pika/pack plugins!
## Lerna Support
Curious 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.
================================================
FILE: checkpoint/LICENSE
================================================
"""
The MIT License
Copyright (c) 2019 Fred K. Schott
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.
""
This license applies to parts of @pika/pack originating from the
https://github.com/sindresorhus/np repository:
"""
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
"""
This license applies to parts of @pika/pack originating from the
https://github.com/yarnpkg/yarn repository:
"""
BSD 2-Clause License
For Yarn software
Copyright (c) 2016-present, Yarn Contributors. All rights reserved.
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 THE COPYRIGHT HOLDER OR 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.
"""
================================================
FILE: checkpoint/README.md
================================================
<p align="center">
<img alt="Logo" src="https://next.pikapkg.com/static/img/new-logo1.png" width="280">
</p>
<p align="center">
<strong>@pika/pack</strong> • npm package building, reimagined.
</p>
<p align="center">
<img alt="Demo" src="https://next.pikapkg.com/static/img/pack-build-demo.gif?" width="720">
</p>
## @pika/pack helps you build amazing packages without the hassle:
- **Simple** ⚡️ Use pre-configured plugins to build your package for you.
- **Flexible** 🏋️♀️ Choose plugins and optimizations to match your needs.
- **Holistic** ⚛️ Let us build the entire package... *including package.json.*
## Quickstart
Getting started is easy:
```js
// 1. Install it!
$ npm install -g @pika/pack
// 2. Add this to your package.json manifest:
"@pika/pack": {
"pipeline": []
}
// 3. Run it!
$ pack build
```
### 😎 🆒
So 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***.
### 1. Create a project pipeline out of simple, pluggable builders.
```js
// Before: Your top-level package.json manifest:
{
"name": "simple-package",
"version": "1.0.0",
"@pika/pack": {
"pipeline": [
["@pika/plugin-standard-pkg", {"exclude": ["__tests__/**/*"]}],
["@pika/plugin-build-node"],
["@pika/plugin-build-web"],
["@pika/plugin-build-types"]
]
}
}
```
Builders 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).
### 2. Builders handle everything, including package configuration.
```js
// After: your built "pkg/" package.json manifest:
{
"name": "simple-package",
"version": "1.0.0",
// Multiple distributions, built & configured automatically:
"esnext": "dist-src/index.js",
"main": "dist-node/index.js",
"module": "dist-web/index.js",
"types": "dist-types/index.d.ts",
// With sensible package defaults:
"sideEffects": false,
"files": ["dist-*/", "assets/", "bin/"]
}
```
This 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.
## Build Plugins
**[Check out the full list](https://github.com/pikapkg/builders)** of official & community-written @pika/pack plugins!
## Lerna Support
Curious 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.
================================================
FILE: checkpoint/dist-node/index.bin.js
================================================
#!/usr/bin/env node
'use strict';
const ver = process.versions.node;
const majorVer = parseInt(ver.split('.')[0], 10);
if (majorVer < 8) {
console.error('Node version ' + ver + ' is not supported, please use Node.js 8.0 or higher.');
process.exit(1);
}
let hasBundled = true
try {
require.resolve('./index.bundled.js');
} catch(err) {
// We don't have/need this on legacy builds and dev builds
// If an error happens here, throw it, that means no Node.js distribution exists at all.
hasBundled = false;
}
const cli = !hasBundled ? require('../') : require('./index.bundled.js');
if (cli.autoRun) {
return;
}
const run = cli.run || cli.cli || cli.default;
run(process.argv).catch(function (error) {
console.error(error.stack || error.message || error);
process.exitCode = 1;
});
================================================
FILE: checkpoint/dist-node/index.js
================================================
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var path = require('path');
var chalk = _interopDefault(require('chalk'));
var fs = require('fs');
var invariant = _interopDefault(require('invariant'));
var loudRejection = _interopDefault(require('loud-rejection'));
var readline = require('readline');
var stripAnsi = _interopDefault(require('strip-ansi'));
var util = require('util');
require('camelcase');
var isCI = require('is-ci');
var os = require('os');
var events = require('events');
var tty = require('tty');
var _rimraf = _interopDefault(require('rimraf'));
var _mkdirp = _interopDefault(require('mkdirp'));
var _glob = _interopDefault(require('glob'));
var stripBOM = _interopDefault(require('strip-bom'));
var types = require('@pika/types');
var isBuiltinModule = _interopDefault(require('is-builtin-module'));
var validateLicense = _interopDefault(require('validate-npm-package-license'));
var semver = _interopDefault(require('semver'));
var nodeUrl = require('url');
var child_process = require('child_process');
var importFrom = _interopDefault(require('import-from'));
var uri2path = _interopDefault(require('file-uri-to-path'));
var yargs = _interopDefault(require('yargs-parser'));
/* @flow */
function removeSuffix(pattern, suffix) {
if (pattern.endsWith(suffix)) {
return pattern.slice(0, -suffix.length);
}
return pattern;
}
function formatFunction(...strs) {
return strs.join(' ');
}
const defaultFormatter = {
bold: formatFunction,
dim: formatFunction,
italic: formatFunction,
underline: formatFunction,
inverse: formatFunction,
strikethrough: formatFunction,
black: formatFunction,
red: formatFunction,
green: formatFunction,
yellow: formatFunction,
blue: formatFunction,
magenta: formatFunction,
cyan: formatFunction,
white: formatFunction,
gray: formatFunction,
grey: formatFunction,
stripColor: formatFunction
};
const messages = {
upToDate: 'Already up-to-date.',
folderInSync: 'Folder in sync.',
nothingToInstall: 'Nothing to install.',
resolvingPackages: 'Resolving packages',
checkingManifest: 'Validating package.json',
fetchingPackages: 'Fetching packages',
linkingDependencies: 'Linking dependencies',
rebuildingPackages: 'Rebuilding all packages',
buildingFreshPackages: 'Building fresh packages',
cleaningModules: 'Cleaning modules',
bumpingVersion: 'Bumping version',
savingHar: 'Saving HAR file: $0',
answer: 'Answer?',
usage: 'Usage',
installCommandRenamed: '`install` has been replaced with `add` to add new dependencies. Run $0 instead.',
globalFlagRemoved: '`--global` has been deprecated. Please run $0 instead.',
waitingInstance: 'Waiting for the other pika instance to finish (pid $0, inside $1)',
waitingNamedInstance: 'Waiting for the other pika instance to finish ($0)',
offlineRetrying: 'There appears to be trouble with your network connection. Retrying...',
internalServerErrorRetrying: 'There appears to be trouble with the npm registry (returned $1). Retrying...',
clearedCache: 'Cleared cache.',
couldntClearPackageFromCache: "Couldn't clear package $0 from cache",
clearedPackageFromCache: 'Cleared package $0 from cache',
packWroteTarball: 'Wrote tarball to $0.',
helpExamples: ' Examples:\n$0\n',
helpCommands: ' Commands:\n$0\n',
helpCommandsMore: ' Run `$0` for more information on specific commands.',
helpLearnMore: ' Visit $0 to learn more about Pika.\n',
manifestPotentialTypo: 'Potential typo $0, did you mean $1?',
manifestBuiltinModule: '$0 is also the name of a node core module',
manifestNameDot: "Name can't start with a dot",
manifestNameIllegalChars: 'Name contains illegal characters',
manifestNameBlacklisted: 'Name is blacklisted',
manifestLicenseInvalid: 'License should be a valid SPDX license expression',
manifestLicenseNone: 'No license field',
manifestStringExpected: '$0 is not a string',
manifestDependencyCollision: '$0 has dependency $1 with range $2 that collides with a dependency in $3 of the same name with version $4',
manifestDirectoryNotFound: 'Unable to read $0 directory of module $1',
verboseFileCopy: 'Copying $0 to $1.',
verboseFileLink: 'Creating hardlink at $0 to $1.',
verboseFileSymlink: 'Creating symlink at $0 to $1.',
verboseFileSkip: 'Skipping copying of file $0 as the file at $1 is the same size ($2) and mtime ($3).',
verboseFileSkipSymlink: 'Skipping copying of $0 as the file at $1 is the same symlink ($2).',
verboseFileSkipHardlink: 'Skipping copying of $0 as the file at $1 is the same hardlink ($2).',
verboseFileRemoveExtraneous: 'Removing extraneous file $0.',
verboseFilePhantomExtraneous: "File $0 would be marked as extraneous but has been removed as it's listed as a phantom file.",
verboseFileSkipArtifact: 'Skipping copying of $0 as the file is marked as a built artifact and subject to change.',
verboseFileFolder: 'Creating directory $0.',
verboseRequestStart: 'Performing $0 request to $1.',
verboseRequestFinish: 'Request $0 finished with status code $1.',
configSet: 'Set $0 to $1.',
configDelete: 'Deleted $0.',
configNpm: 'npm config',
configPika: 'pika config',
couldntFindPackagejson: "Couldn't find a package.json file in $0",
couldntFindMatch: "Couldn't find match for $0 in $1 for $2.",
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.",
couldntFindVersionThatMatchesRange: "Couldn't find any versions for $0 that matches $1",
chooseVersionFromList: 'Please choose a version of $0 from this list:',
moduleNotInManifest: "This module isn't specified in a package.json file.",
moduleAlreadyInManifest: '$0 is already in $1. Please remove existing entry first before adding it to $2.',
unknownFolderOrTarball: "Passed folder/tarball doesn't exist,",
unknownPackage: "Couldn't find package $0.",
unknownPackageName: "Couldn't find package name.",
unknownUser: "Couldn't find user $0.",
unknownRegistryResolver: 'Unknown registry resolver $0',
userNotAnOwner: "User $0 isn't an owner of this package.",
invalidVersionArgument: 'Use the $0 flag to create a new version.',
invalidVersion: 'Invalid version supplied.',
requiredVersionInRange: 'Required version in range.',
packageNotFoundRegistry: "Couldn't find package $0 on the $1 registry.",
requiredPackageNotFoundRegistry: "Couldn't find package $0 required by $1 on the $2 registry.",
doesntExist: "Package $1 refers to a non-existing file '$0'.",
missingRequiredPackageKey: `Package $0 doesn't have a $1.`,
invalidAccess: 'Invalid argument for access, expected public or restricted.',
invalidCommand: 'Invalid subcommand. Try $0',
invalidGistFragment: 'Invalid gist fragment $0.',
invalidHostedGitFragment: 'Invalid hosted git fragment $0.',
invalidFragment: 'Invalid fragment $0.',
invalidPackageName: 'Invalid package name.',
invalidPackageVersion: "Can't add $0: invalid package version $1.",
couldntFindManifestIn: "Couldn't find manifest in $0.",
shrinkwrapWarning: 'npm-shrinkwrap.json found. This will not be updated or respected. See https://yarnpkg.com/en/docs/migrating-from-npm for more information.',
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.',
lockfileOutdated: 'Outdated lockfile. Please run `pika install` and try again.',
lockfileMerged: 'Merge conflict detected in pika.lock and successfully merged.',
lockfileConflict: 'A merge conflict was found in pika.lock but it could not be successfully merged, regenerating pika.lock from scratch.',
ignoredScripts: 'Ignored scripts due to flag.',
missingAddDependencies: 'Missing list of packages to add to your project.',
yesWarning: 'The yes flag has been set. This will automatically answer yes to all questions, which may have security implications.',
networkWarning: "You don't appear to have an internet connection. Try the --offline flag to use the cache for registry queries.",
flatGlobalError: 'The package $0 requires a flat dependency graph. Add `"flat": true` to your package.json and try again.',
noName: `Package doesn't have a name.`,
noVersion: `Package doesn't have a version.`,
answerRequired: 'An answer is required.',
missingWhyDependency: 'Missing package name, folder or path to file to identify why a package has been installed',
bugReport: 'If you think this is a bug, please open a bug report with the information provided in $0.',
unexpectedError: 'An unexpected error occurred: $0.',
jsonError: 'Error parsing JSON at $0, $1.',
noPermission: 'Cannot create $0 due to insufficient permissions.',
noGlobalFolder: 'Cannot find a suitable global folder. Tried these: $0',
allDependenciesUpToDate: 'All of your dependencies are up to date.',
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',
frozenLockfileError: 'Your lockfile needs to be updated, but pika was run with `--frozen-lockfile`.',
fileWriteError: 'Could not write file $0: $1',
fileDeleteError: 'Could not delete file $0: $1',
multiplePackagesCantUnpackInSameDestination: 'Pattern $0 is trying to unpack in the same destination $1 as pattern $2. This could result in non-deterministic behavior, skipping.',
incorrectLockfileEntry: 'Lockfile has incorrect entry for $0. Ignoring it.',
invalidResolutionName: 'Resolution field $0 does not end with a valid package name and will be ignored',
invalidResolutionVersion: 'Resolution field $0 has an invalid version entry and may be ignored',
incompatibleResolutionVersion: 'Resolution field $0 is incompatible with requested version $1',
pikaOutdated: "Your current version of Pika is out of date. The latest version is $0, while you're on $1.",
pikaOutdatedInstaller: 'To upgrade, download the latest installer at $0.',
pikaOutdatedCommand: 'To upgrade, run the following command:',
tooManyArguments: 'Too many arguments, maximum of $0.',
tooFewArguments: 'Not enough arguments, expected at least $0.',
noArguments: "This command doesn't require any arguments.",
ownerRemoving: 'Removing owner $0 from package $1.',
ownerRemoved: 'Owner removed.',
ownerRemoveError: "Couldn't remove owner.",
ownerGetting: 'Getting owners for package $0',
ownerGettingFailed: "Couldn't get list of owners.",
ownerAlready: 'This user is already an owner of this package.',
ownerAdded: 'Added owner.',
ownerAdding: 'Adding owner $0 to package $1',
ownerAddingFailed: "Couldn't add owner.",
ownerNone: 'No owners.',
teamCreating: 'Creating team',
teamRemoving: 'Removing team',
teamAddingUser: 'Adding user to team',
teamRemovingUser: 'Removing user from team',
teamListing: 'Listing teams',
distFailed: `⚠️ Distribution "$0" failed to build: $1 $2`,
distExiting: ` Exiting...`,
distContinuing: ` Continuing...`,
cleaning: 'Cleaning modules',
cleanCreatingFile: 'Creating $0',
cleanCreatedFile: 'Created $0. Please review the contents of this file then run "pika autoclean --force" to perform a clean.',
cleanAlreadyExists: '$0 already exists. To revert to the default file, delete $0 then rerun this command.',
cleanRequiresForce: 'This command required the "--force" flag to perform the clean. This is a destructive operation. Files specified in $0 will be deleted.',
cleanDoesNotExist: '$0 does not exist. Autoclean will delete files specified by $0. Run "autoclean --init" to create $0 with the default entries.',
binLinkCollision: "There's already a linked binary called $0 in your global Pika bin. Could not link this package's $0 bin entry.",
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.",
linkMissing: 'No registered package found called $0.',
linkRegistered: 'Registered $0.',
linkRegisteredMessage: 'You can now run `pika link $0` in the projects where you want to use this package and it will be used instead.',
linkUnregistered: 'Unregistered $0.',
linkUnregisteredMessage: 'You can now run `pika unlink $0` in the projects where you no longer want to use this package.',
linkUsing: 'Using linked package for $0.',
linkDisusing: 'Removed linked package $0.',
linkDisusingMessage: 'You will need to run `pika` to re-install the package that was linked.',
linkTargetMissing: 'The target of linked package $0 is missing. Removing link.',
createInvalidBin: 'Invalid bin entry found in package $0.',
createMissingPackage: 'Package not found - this is probably an internal error, and should be reported at https://github.com/yarnpkg/yarn/issues.',
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).',
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).',
workspacesFocusRootCheck: 'This command can only be run inside an individual workspace.',
workspacesRequirePrivateProjects: 'Workspaces can only be enabled in private projects.',
workspacesSettingMustBeArray: 'The workspaces field in package.json must be an array.',
workspacesDisabled: 'Your project root defines workspaces but the feature is disabled in your Pika config. Please check "workspaces-experimental" in your .pikarc file.',
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.',
workspacesNohoistDisabled: `$0 defines nohoist but the feature is disabled in your Pika config ("workspaces-nohoist-experimental" in .pikarc file)`,
workspaceRootNotFound: "Cannot find the root of your workspace - are you sure you're currently in a workspace?",
workspaceMissingWorkspace: 'Missing workspace name.',
workspaceMissingCommand: 'Missing command name.',
workspaceUnknownWorkspace: 'Unknown workspace $0.',
workspaceVersionMandatory: 'Missing version in workspace at $0, ignoring.',
workspaceNameMandatory: 'Missing name in workspace at $0, ignoring.',
workspaceNameDuplicate: 'There are more than one workspace with name $0',
cacheFolderSkipped: 'Skipping preferred cache folder $0 because it is not writable.',
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.",
cacheFolderSelected: 'Selected the next writable cache folder in the list, will be $0.',
execMissingCommand: 'Missing command name.',
noScriptsAvailable: 'There are no scripts specified inside package.json.',
noBinAvailable: 'There are no binary scripts available.',
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.`,
commandNotSpecified: 'No command specified.',
binCommands: 'Commands available from binary scripts: ',
possibleCommands: 'Project commands',
commandQuestion: 'Which command would you like to run?',
commandFailedWithCode: 'Command failed with exit code $0.',
commandFailedWithSignal: 'Command failed with signal $0.',
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.',
nodeGypAutoInstallFailed: 'Failed to auto-install node-gyp. Please run "pika global add node-gyp" manually. Error: $0',
foundIncompatible: 'Found incompatible module',
incompatibleEngine: 'The engine $0 is incompatible with this module. Expected version $1. Got $2',
incompatibleCPU: 'The CPU architecture $0 is incompatible with this module.',
incompatibleOS: 'The platform $0 is incompatible with this module.',
invalidEngine: 'The engine $0 appears to be invalid.',
optionalCompatibilityExcluded: '$0 is an optional dependency and failed compatibility check. Excluding it from installation.',
optionalModuleFail: 'This module is OPTIONAL, you can safely ignore this error',
optionalModuleScriptFail: 'Error running install script for optional dependency: $0',
optionalModuleCleanupFail: 'Could not cleanup build artifacts from failed install: $0',
unmetPeer: '$0 has unmet peer dependency $1.',
incorrectPeer: '$0 has incorrect peer dependency $1.',
selectedPeer: 'Selecting $1 at level $2 as the peer dependency of $0.',
missingBundledDependency: '$0 is missing a bundled dependency $1. This should be reported to the package maintainer.',
savedNewDependency: 'Saved 1 new dependency.',
savedNewDependencies: 'Saved $0 new dependencies.',
directDependencies: 'Direct dependencies',
allDependencies: 'All dependencies',
foundWarnings: 'Found $0 warnings.',
foundErrors: 'Found $0 errors.',
savedLockfile: 'Saved lockfile.',
noRequiredLockfile: 'No lockfile in this directory. Run `pika install` to generate one.',
noLockfileFound: 'No lockfile found.',
invalidSemver: 'Invalid semver version',
newVersion: 'New version',
currentVersion: 'Current version',
noVersionOnPublish: 'Proceeding with current version',
manualVersionResolution: 'Unable to find a suitable version for $0, please choose one by typing one of the numbers below:',
manualVersionResolutionOption: '$0 which resolved to $1',
createdTag: 'Created tag.',
createdTagFail: "Couldn't add tag.",
deletedTag: 'Deleted tag.',
deletedTagFail: "Couldn't delete tag.",
gettingTags: 'Getting tags',
deletingTags: 'Deleting tag',
creatingTag: 'Creating tag $0 = $1',
whyStart: 'Why do we have the module $0?',
whyFinding: 'Finding dependency',
whyCalculating: 'Calculating file sizes',
whyUnknownMatch: "We couldn't find a match!",
whyInitGraph: 'Initialising dependency graph',
whyWhoKnows: "We don't know why this module exists",
whyDiskSizeWithout: 'Disk size without dependencies: $0',
whyDiskSizeUnique: 'Disk size with unique dependencies: $0',
whyDiskSizeTransitive: 'Disk size with transitive dependencies: $0',
whySharedDependencies: 'Number of shared dependencies: $0',
whyHoistedTo: `Has been hoisted to $0`,
whyHoistedFromSimple: `This module exists because it's hoisted from $0.`,
whyNotHoistedSimple: `This module exists here because it's in the nohoist list $0.`,
whyDependedOnSimple: `This module exists because $0 depends on it.`,
whySpecifiedSimple: `This module exists because it's specified in $0.`,
whyReasons: 'Reasons this module exists',
whyHoistedFrom: 'Hoisted from $0',
whyNotHoisted: `in the nohoist list $0`,
whyDependedOn: '$0 depends on it',
whySpecified: `Specified in $0`,
whyMatch: `\r=> Found $0`,
uninstalledPackages: 'Uninstalled packages.',
uninstallRegenerate: 'Regenerating lockfile and installing missing dependencies',
cleanRemovedFiles: 'Removed $0 files',
cleanSavedSize: 'Saved $0 MB.',
configFileFound: 'Found configuration file $0.',
configPossibleFile: 'Checking for configuration file $0.',
npmUsername: 'npm username',
npmPassword: 'npm password',
npmEmail: 'npm email',
npmOneTimePassword: 'npm one-time password',
loggingIn: 'Logging in',
loggedIn: 'Logged in.',
notRevokingEnvToken: 'Not revoking login token, specified via environment variable.',
notRevokingConfigToken: 'Not revoking login token, specified via config file.',
noTokenToRevoke: 'No login token to revoke.',
revokingToken: 'Revoking token',
revokedToken: 'Revoked login token.',
loginAsPublic: 'Logging in as public',
incorrectCredentials: 'Incorrect username or password.',
incorrectOneTimePassword: 'Incorrect one-time password.',
twoFactorAuthenticationEnabled: 'Two factor authentication enabled.',
clearedCredentials: 'Cleared login credentials.',
publishFail: "Couldn't publish package: $0",
publishPrivate: 'Package marked as private, not publishing.',
published: 'Published.',
publishing: 'Publishing',
nonInteractiveNoVersionSpecified: 'You must specify a new version with --new-version when running with --non-interactive.',
nonInteractiveNoToken: "No token found and can't prompt for login when running with --non-interactive.",
infoFail: 'Received invalid response from npm.',
malformedRegistryResponse: 'Received malformed response from registry for $0. The registry may be down.',
registryNoVersions: 'No valid versions found for $0. The package may be unpublished.',
cantRequestOffline: "Can't make a request in offline mode ($0)",
requestManagerNotSetupHAR: 'RequestManager was not setup to capture HAR files',
requestError: 'Request $0 returned a $1',
requestFailed: 'Request failed $0',
tarballNotInNetworkOrCache: '$0: Tarball is not in network and can not be located in cache ($1)',
fetchBadHashWithPath: "Integrity check failed for $0 (computed integrity doesn't match our records, got $2)",
fetchBadIntegrityAlgorithm: 'Integrity checked failed for $0 (none of the specified algorithms are supported)',
fetchErrorCorrupt: '$0. Mirror tarball appears to be corrupt. You can resolve this by running:\n\n rm -rf $1\n pika install',
errorExtractingTarball: 'Extracting tar content of $1 failed, the file appears to be corrupt: $0',
updateInstalling: 'Installing $0...',
hostedGitResolveError: 'Error connecting to repository. Please, check the url.',
unknownFetcherFor: 'Unknown fetcher for $0',
downloadGitWithoutCommit: 'Downloading the git repo $0 over plain git without a commit hash',
downloadHTTPWithoutCommit: 'Downloading the git repo $0 over HTTP without a commit hash',
unplugDisabled: "Packages can only be unplugged when Plug'n'Play is enabled.",
plugnplayWindowsSupport: "Plug'n'Play on Windows doesn't support the cache and project to be kept on separate drives",
packageInstalledWithBinaries: 'Installed $0 with binaries:',
packageHasBinaries: '$0 has binaries:',
packageHasNoBinaries: '$0 has no binaries',
packageBinaryNotFound: "Couldn't find a binary named $0",
couldBeDeduped: '$0 could be deduped from $1 to $2',
lockfileNotContainPattern: 'Lockfile does not contain pattern: $0',
integrityCheckFailed: 'Integrity check failed',
noIntegrityFile: "Couldn't find an integrity file",
integrityFailedExpectedIsNotAJSON: 'Integrity check: integrity file is not a json',
integrityCheckLinkedModulesDontMatch: "Integrity check: Linked modules don't match",
integrityFlagsDontMatch: "Integrity check: Flags don't match",
integrityLockfilesDontMatch: "Integrity check: Lock files don't match",
integrityFailedFilesMissing: 'Integrity check: Files are missing',
integrityPatternsDontMatch: "Integrity check: Top level patterns don't match",
integrityModulesFoldersMissing: 'Integrity check: Some module folders are missing',
integritySystemParamsDontMatch: "Integrity check: System parameters don't match",
packageNotInstalled: '$0 not installed',
optionalDepNotInstalled: 'Optional dependency $0 not installed',
packageWrongVersion: '$0 is wrong version: expected $1, got $2',
packageDontSatisfy: "$0 doesn't satisfy found match of $1",
lockfileExists: 'Lockfile already exists, not migrating.',
pikaManifestExists: 'pika.package.json manifest already exists, not migrating.',
noManifestExists: 'No package.json manifest found. Run `pika init` to generate a new pika.package.json manifest.',
skippingImport: 'Skipping import of $0 for $1',
importFailed: 'Import of $0 for $1 failed, resolving normally.',
importResolveFailed: 'Import of $0 failed starting in $1',
importResolvedRangeMatch: 'Using version $0 of $1 instead of $2 for $3',
importSourceFilesCorrupted: 'Failed to import from package-lock.json, source file(s) corrupted',
importPackageLock: 'found npm package-lock.json, converting to pika.lock',
importYarnLock: 'found yarn.lock, converting to pika.lock',
importNodeModules: 'creating pika.lock from local node_modules folder',
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 .',
watchStarting: `Starting up`,
watchRunning: `Ready! Watching source tree for changes`,
watchRebuild: `Rebuilding...`,
watchError: `Build error!`,
noValidationErrors: `0 Validation Errors found.`,
validationErrors: `$0 Validation Error(s) found. Resolve before publishing.`,
scopeNotValid: 'The specified scope is not valid.',
deprecatedCommand: '$0 is deprecated. Please use $1.',
deprecatedListArgs: 'Filtering by arguments is deprecated. Please use the pattern option instead.',
implicitFileDeprecated: 'Using the "file:" protocol implicitly is deprecated. Please either prepend the protocol or prepend the path $0 with "./".',
unsupportedNodeVersion: 'You are using Node $0 which is not supported and may encounter bugs or unexpected behavior. Pika supports the following semver range: $1',
verboseUpgradeBecauseRequested: 'Considering upgrade of $0 to $1 because it was directly requested.',
verboseUpgradeBecauseOutdated: 'Considering upgrade of $0 to $1 because a newer version exists in the registry.',
verboseUpgradeNotUnlocking: 'Not unlocking $0 in the lockfile because it is a new or direct dependency.',
verboseUpgradeUnlocking: 'Unlocking $0 in the lockfile.',
folderMissing: "Directory $0 doesn't exist",
mutexPortBusy: 'Cannot use the network mutex on port $0. It is probably used by another app.',
auditRunning: 'Auditing packages',
auditSummary: '$0 vulnerabilities found - Packages audited: $1',
auditSummarySeverity: 'Severity:',
auditCritical: '$0 Critical',
auditHigh: '$0 High',
auditModerate: '$0 Moderate',
auditLow: '$0 Low',
auditInfo: '$0 Info',
auditResolveCommand: '# Run $0 to resolve $1 $2',
auditSemverMajorChange: 'SEMVER WARNING: Recommended action is a potentially breaking change',
auditManualReview: 'Manual Review\nSome vulnerabilities require your attention to resolve\n\nVisit https://go.npm.me/audit-guide for additional guidance',
auditRunAuditForDetails: 'Security audit found potential problems. Run "pika audit" for additional details.',
auditOffline: 'Skipping audit. Security audit cannot be performed in offline mode.'
};
var languages = /*#__PURE__*/Object.freeze({
en: messages
});
function stringifyLangArgs(args) {
return args.map(function (val) {
if (val != null && val.inspect) {
return val.inspect();
} else {
try {
const str = JSON.stringify(val) || val + ''; // should match all literal line breaks and
// "u001b" that follow an odd number of backslashes and convert them to ESC
// we do this because the JSON.stringify process has escaped these characters
return str.replace(/((?:^|[^\\])(?:\\{2})*)\\u001[bB]/g, '$1\u001b').replace(/[\\]r[\\]n|([\\])?[\\]n/g, (match, precededBacklash) => {
// precededBacklash not null when "\n" is preceded by a backlash ("\\n")
// match will be "\\n" and we don't replace it with os.EOL
return precededBacklash ? match : os.EOL;
});
} catch (e) {
return util.inspect(val);
}
}
});
}
class BaseReporter {
constructor(opts = {}) {
const lang = 'en';
this.language = lang;
this.stdout = opts.stdout || process.stdout;
this.stderr = opts.stderr || process.stderr;
this.stdin = opts.stdin || this._getStandardInput();
this.emoji = !!opts.emoji;
this.nonInteractive = !!opts.nonInteractive;
this.noProgress = !!opts.noProgress || isCI;
this.isVerbose = !!opts.verbose; // @ts-ignore
this.isTTY = this.stdout.isTTY;
this.peakMemory = 0;
this.startTime = Date.now();
this.format = defaultFormatter;
}
lang(key, ...args) {
const msg = languages[this.language][key] || messages[key];
if (!msg) {
throw new ReferenceError(`No message defined for language key ${key}`);
} // stringify args
const stringifiedArgs = stringifyLangArgs(args); // replace $0 placeholders with args
return msg.replace(/\$(\d+)/g, (str, i) => {
return stringifiedArgs[i];
});
}
/**
* `stringifyLangArgs` run `JSON.stringify` on strings too causing
* them to appear quoted. This marks them as "raw" and prevents
* the quoting and escaping
*/
rawText(str) {
return {
inspect() {
return str;
}
};
}
verbose(msg) {
if (this.isVerbose) {
this._verbose(msg);
}
}
verboseInspect(val) {
if (this.isVerbose) {
this._verboseInspect(val);
}
}
_verbose(msg) {}
_verboseInspect(val) {}
_getStandardInput() {
let standardInput; // Accessing stdin in a win32 headless process (e.g., Visual Studio) may throw an exception.
try {
standardInput = process.stdin;
} catch (e) {
console.warn(e.message);
delete process.stdin; // @ts-ignore
process.stdin = new events.EventEmitter();
standardInput = process.stdin;
}
return standardInput;
}
initPeakMemoryCounter() {
this.checkPeakMemory();
this.peakMemoryInterval = setInterval(() => {
this.checkPeakMemory();
}, 1000); // $FlowFixMe: Node's setInterval returns a Timeout, not a Number
this.peakMemoryInterval.unref();
}
checkPeakMemory() {
const {
heapTotal
} = process.memoryUsage();
if (heapTotal > this.peakMemory) {
this.peakMemory = heapTotal;
}
}
close() {
if (this.peakMemoryInterval) {
clearInterval(this.peakMemoryInterval);
this.peakMemoryInterval = null;
}
}
getTotalTime() {
return Date.now() - this.startTime;
} // TODO
list(key, items, hints) {} // Outputs basic tree structure to console
tree(key, obj, {
force = false
} = {}) {} // called whenever we begin a step in the CLI.
step(current, total, message, emoji) {} // a error message has been triggered. this however does not always meant an abrupt
// program end.
error(message) {} // an info message has been triggered. this provides things like stats and diagnostics.
info(message) {} // a warning message has been triggered.
warn(message) {} // a success message has been triggered.
success(message) {} // a simple log message
// TODO: rethink the {force} parameter. In the meantime, please don't use it (cf comments in #4143).
log(message, {
force = false
} = {}) {} // a shell command has been executed
command(command) {} // inspect and pretty-print any value
inspect(value) {} // the screen shown at the very start of the CLI
header(pkg) {} // the screen shown at the very end of the CLI
footer(showPeakMemory) {} // a table structure
table(head, body) {} // render an activity spinner and return a function that will trigger an update
activity() {
return {
tick(name) {},
end() {}
};
} //
activitySet(total, workers) {
return {
spinners: Array(workers).fill({
clear() {},
setPrefix() {},
tick() {},
end() {}
}),
end() {}
};
} // render a progress bar and return a function which when called will trigger an update
progress(total) {
return function () {};
} // utility function to disable progress bar
disableProgress() {
this.noProgress = true;
}
}
// public
function sortTrees(trees) {
return trees.sort(function (tree1, tree2) {
return tree1.name.localeCompare(tree2.name);
});
}
function recurseTree(tree, prefix, recurseFunc) {
const treeLen = tree.length;
const treeEnd = treeLen - 1;
for (let i = 0; i < treeLen; i++) {
const atEnd = i === treeEnd;
recurseFunc(tree[i], prefix + getLastIndentChar(atEnd), prefix + getNextIndentChar(atEnd));
}
}
function getFormattedOutput(fmt) {
const item = formatColor(fmt.color, fmt.name, fmt.formatter);
const suffix = getSuffix(fmt.hint, fmt.formatter);
return `${fmt.prefix}─ ${item}${suffix}\n`;
}
function getNextIndentChar(end) {
return end ? ' ' : '│ ';
}
function getLastIndentChar(end) {
return end ? '└' : '├';
}
function getSuffix(hint, formatter) {
return hint ? ` (${formatter.grey(hint)})` : '';
}
function formatColor(color, strToFormat, formatter) {
return color ? formatter[color](strToFormat) : strToFormat;
}
const CLEAR_WHOLE_LINE = 0;
const CLEAR_RIGHT_OF_CURSOR = 1;
function clearLine(stdout) {
if (!chalk.supportsColor) {
if (stdout instanceof tty.WriteStream) {
if (stdout.columns > 0) {
stdout.write(`\r${' '.repeat(stdout.columns - 1)}`);
}
stdout.write(`\r`);
}
return;
}
readline.clearLine(stdout, CLEAR_WHOLE_LINE);
readline.cursorTo(stdout, 0);
}
function toStartOfLine(stdout) {
if (!chalk.supportsColor) {
stdout.write('\r');
return;
}
readline.cursorTo(stdout, 0);
}
function writeOnNthLine(stdout, n, msg) {
if (!chalk.supportsColor) {
return;
}
if (n == 0) {
readline.cursorTo(stdout, 0);
stdout.write(msg);
readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);
return;
}
readline.cursorTo(stdout, 0);
readline.moveCursor(stdout, 0, -n);
stdout.write(msg);
readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);
readline.cursorTo(stdout, 0);
readline.moveCursor(stdout, 0, n);
}
function clearNthLine(stdout, n) {
if (!chalk.supportsColor) {
return;
}
if (n == 0) {
clearLine(stdout);
return;
}
readline.cursorTo(stdout, 0);
readline.moveCursor(stdout, 0, -n);
readline.clearLine(stdout, CLEAR_WHOLE_LINE);
readline.moveCursor(stdout, 0, n);
}
class ProgressBar {
constructor(total, stdout = process.stderr, callback) {
this.stdout = stdout;
this.total = total;
this.chars = ProgressBar.bars[0];
this.delay = 60;
this.curr = 0;
this._callback = callback;
clearLine(stdout);
}
tick() {
if (this.curr >= this.total) {
return;
}
this.curr++; // schedule render
if (!this.id) {
this.id = setTimeout(() => this.render(), this.delay);
}
}
cancelTick() {
if (this.id) {
clearTimeout(this.id);
this.id = null;
}
}
stop() {
// "stop" by setting current to end so `tick` becomes noop
this.curr = this.total;
this.cancelTick();
clearLine(this.stdout);
if (this._callback) {
this._callback(this);
}
}
render() {
// clear throttle
this.cancelTick();
let ratio = this.curr / this.total;
ratio = Math.min(Math.max(ratio, 0), 1); // progress without bar
let bar = ` ${this.curr}/${this.total}`; // calculate size of actual bar
// $FlowFixMe: investigate process.stderr.columns flow error
// @ts-ignore
const availableSpace = Math.max(0, this.stdout.columns - bar.length - 3);
const width = Math.min(this.total, availableSpace);
const completeLength = Math.round(width * ratio);
const complete = this.chars[0].repeat(completeLength);
const incomplete = this.chars[1].repeat(width - completeLength);
bar = `[${complete}${incomplete}]${bar}`;
toStartOfLine(this.stdout);
this.stdout.write(bar);
}
}
ProgressBar.bars = [['#', '-']];
class Spinner {
constructor(stdout = process.stderr, lineNumber = 0) {
this.current = 0;
this.prefix = '';
this.lineNumber = lineNumber;
this.stdout = stdout;
this.delay = 60;
this.chars = Spinner.spinners[28].split('');
this.text = '';
this.id = null;
}
setPrefix(prefix) {
this.prefix = prefix;
}
setText(text) {
this.text = text;
}
start() {
this.current = 0;
this.render();
}
render() {
if (this.id) {
clearTimeout(this.id);
} // build line ensuring we don't wrap to the next line
let msg = `${this.prefix}${this.chars[this.current]} ${this.text}`; // @ts-ignore
const columns = typeof this.stdout.columns === 'number' ? this.stdout.columns : 100;
msg = msg.slice(0, columns);
writeOnNthLine(this.stdout, this.lineNumber, msg);
this.current = ++this.current % this.chars.length;
this.id = setTimeout(() => this.render(), this.delay);
}
stop() {
if (this.id) {
clearTimeout(this.id);
this.id = null;
}
clearNthLine(this.stdout, this.lineNumber);
}
}
Spinner.spinners = ['|/-\\', '⠂-–—–-', '◐◓◑◒', '◴◷◶◵', '◰◳◲◱', '▖▘▝▗', '■□▪▫', '▌▀▐▄', '▉▊▋▌▍▎▏▎▍▌▋▊▉', '▁▃▄▅▆▇█▇▆▅▄▃', '←↖↑↗→↘↓↙', '┤┘┴└├┌┬┐', '◢◣◤◥', '.oO°Oo.', '.oO@*', '🌍🌎🌏', '◡◡ ⊙⊙ ◠◠', '☱☲☴', '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏', '⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓', '⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆', '⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋', '⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁', '⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈', '⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈', '⢄⢂⢁⡁⡈⡐⡠', '⢹⢺⢼⣸⣇⡧⡗⡏', '⣾⣽⣻⢿⡿⣟⣯⣷', '⠁⠂⠄⡀⢀⠠⠐⠈'];
const auditSeverityColors = {
info: chalk.bold,
low: chalk.bold,
moderate: chalk.yellow,
high: chalk.red,
critical: chalk.bgRed
}; // fixes bold on windows
if (process.platform === 'win32' && !(process.env.TERM && /^xterm/i.test(process.env.TERM))) {
// @ts-ignore
chalk.bold._styles[0].close += '\u001b[m';
}
class ConsoleReporter extends BaseReporter {
constructor(opts) {
super(opts);
this._lastCategorySize = 0;
this._spinners = new Set();
this.format = chalk;
this.format.stripColor = stripAnsi;
this.isSilent = !!opts.isSilent;
}
_prependEmoji(msg, emoji) {
if (this.emoji && emoji && this.isTTY) {
msg = `${emoji} ${msg}`;
}
return msg;
}
_logCategory(category, color, msg) {
this._lastCategorySize = category.length;
this._log(`${this.format[color](category)} ${msg}`);
}
_verbose(msg) {
this._logCategory('verbose', 'grey', `${process.uptime()} ${msg}`);
}
_verboseInspect(obj) {
this.inspect(obj);
}
close() {
for (const spinner of this._spinners) {
spinner.stop();
}
this._spinners.clear();
this.stopProgress();
super.close();
}
table(head, body) {
//
head = head.map(field => this.format.underline(field)); //
const rows = [head].concat(body); // get column widths
const cols = [];
for (let i = 0; i < head.length; i++) {
const widths = rows.map(row => this.format.stripColor(row[i]).length);
cols[i] = Math.max(...widths);
} //
const builtRows = rows.map(row => {
for (let i = 0; i < row.length; i++) {
const field = row[i];
const padding = cols[i] - this.format.stripColor(field).length;
row[i] = field + ' '.repeat(padding);
}
return row.join(' ');
});
this.log(builtRows.join('\n'));
}
step(current, total, msg, emoji) {
msg = this._prependEmoji(msg, emoji);
if (msg.endsWith('?')) {
msg = `${removeSuffix(msg, '?')}...?`;
} else {
msg += '...';
}
this.log(`${this.format.dim(`[${current}/${total}]`)} ${msg}`);
}
inspect(value) {
if (typeof value !== 'number' && typeof value !== 'string') {
value = util.inspect(value, {
breakLength: 0,
colors: this.isTTY,
depth: null,
maxArrayLength: null
});
}
this.log(String(value), {
force: true
});
}
list(key, items, hints) {
const gutterWidth = (this._lastCategorySize || 2) - 1;
if (hints) {
for (const item of items) {
this._log(`${' '.repeat(gutterWidth)}- ${this.format.bold(item)}`);
this._log(` ${' '.repeat(gutterWidth)} ${hints[item]}`);
}
} else {
for (const item of items) {
this._log(`${' '.repeat(gutterWidth)}- ${item}`);
}
}
}
header(pkg) {
this.log(this.format.bold(`${pkg.name} v${pkg.version}`));
}
footer(showPeakMemory) {
this.stopProgress();
const totalTime = (this.getTotalTime() / 1000).toFixed(2);
let msg = `Done in ${totalTime}s.`;
if (showPeakMemory) {
const peakMemory = (this.peakMemory / 1024 / 1024).toFixed(2);
msg += ` Peak memory usage ${peakMemory}MB.`;
}
this.log(this._prependEmoji(msg, '✨'));
}
log(msg, {
force = false
} = {}) {
this._lastCategorySize = 0;
this._log(msg, {
force
});
}
_log(msg, {
force = false
} = {}) {
if (this.isSilent && !force) {
return;
}
clearLine(this.stdout);
this.stdout.write(`${msg}\n`);
}
success(msg) {
this._logCategory('success', 'green', msg);
}
error(msg) {
clearLine(this.stderr);
this.stderr.write(`${this.format.red('error')} ${msg}\n`);
}
info(msg) {
this._logCategory('info', 'blue', msg);
}
command(command) {
this.log(this.format.dim(`$ ${command}`));
}
warn(msg) {
clearLine(this.stderr);
this.stderr.write(`${this.format.yellow('warning')} ${msg}\n`);
} // handles basic tree output to console
tree(key, trees, {
force = false
} = {}) {
this.stopProgress(); //
if (this.isSilent && !force) {
return;
}
const output = ({
name,
children,
hint,
color
}, titlePrefix, childrenPrefix) => {
const formatter = this.format;
const out = getFormattedOutput({
prefix: titlePrefix,
hint,
color,
name,
formatter
});
this.stdout.write(out);
if (children && children.length) {
recurseTree(sortTrees(children), childrenPrefix, output);
}
};
recurseTree(sortTrees(trees), '', output);
}
activitySet(total, workers) {
if (!this.isTTY || this.noProgress) {
return super.activitySet(total, workers);
}
const spinners = [];
const reporterSpinners = this._spinners;
for (let i = 1; i < workers; i++) {
this.log('');
}
for (let i = 0; i < workers; i++) {
const spinner = new Spinner(this.stderr, i);
reporterSpinners.add(spinner);
spinner.start();
let prefix = null;
let current = 0;
const updatePrefix = () => {
spinner.setPrefix(`${this.format.dim(`[${current === 0 ? '-' : current}/${total}]`)} `);
};
const clear = () => {
prefix = null;
current = 0;
updatePrefix();
spinner.setText('waiting...');
};
clear();
spinners.unshift({
clear,
setPrefix(_current, _prefix) {
current = _current;
prefix = _prefix;
spinner.setText(prefix);
updatePrefix();
},
tick(msg) {
if (prefix) {
msg = `${prefix}: ${msg}`;
}
spinner.setText(msg);
},
end() {
spinner.stop();
reporterSpinners.delete(spinner);
}
});
}
return {
spinners,
end: () => {
for (const spinner of spinners) {
spinner.end();
}
readline.moveCursor(this.stdout, 0, -workers + 1);
}
};
}
activity() {
if (!this.isTTY) {
return {
tick() {},
end() {}
};
}
const reporterSpinners = this._spinners;
const spinner = new Spinner(this.stderr);
spinner.start();
reporterSpinners.add(spinner);
return {
tick(name) {
spinner.setText(name);
},
end() {
spinner.stop();
reporterSpinners.delete(spinner);
}
};
}
progress(count) {
if (this.noProgress || count <= 0) {
return function () {// noop
};
}
if (!this.isTTY) {
return function () {// TODO what should the behaviour here be? we could buffer progress messages maybe
};
} // Clear any potentially old progress bars
this.stopProgress();
const bar = this._progressBar = new ProgressBar(count, this.stderr, progress => {
if (progress === this._progressBar) {
this._progressBar = null;
}
});
bar.render();
return function () {
bar.tick();
};
}
stopProgress() {
if (this._progressBar) {
this._progressBar.stop();
}
}
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(source, true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(source).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
class JSONReporter extends BaseReporter {
constructor(opts) {
super(opts);
this._activityId = 0;
this._progressId = 0;
}
_dump(type, data, error) {
let stdout = this.stdout;
if (error) {
stdout = this.stderr;
}
stdout.write(`${JSON.stringify({
type,
data
})}\n`);
}
_verbose(msg) {
this._dump('verbose', msg);
}
list(type, items, hints) {
this._dump('list', {
type,
items,
hints
});
}
tree(type, trees) {
this._dump('tree', {
type,
trees
});
}
step(current, total, message) {
this._dump('step', {
message,
current,
total
});
}
inspect(value) {
this._dump('inspect', value);
}
footer(showPeakMemory) {
this._dump('finished', this.getTotalTime());
}
log(msg) {
this._dump('log', msg);
}
command(msg) {
this._dump('command', msg);
}
table(head, body) {
this._dump('table', {
head,
body
});
}
success(msg) {
this._dump('success', msg);
}
error(msg) {
this._dump('error', msg, true);
}
warn(msg) {
this._dump('warning', msg, true);
}
info(msg) {
this._dump('info', msg);
}
activitySet(total, workers) {
if (!this.isTTY || this.noProgress) {
return super.activitySet(total, workers);
}
const id = this._activityId++;
this._dump('activitySetStart', {
id,
total,
workers
});
const spinners = [];
for (let i = 0; i < workers; i++) {
let current = 0;
let header = '';
spinners.push({
clear() {},
setPrefix(_current, _header) {
current = _current;
header = _header;
},
tick: msg => {
this._dump('activitySetTick', {
id,
header,
current,
worker: i,
message: msg
});
},
end() {}
});
}
return {
spinners,
end: () => {
this._dump('activitySetEnd', {
id
});
}
};
}
activity() {
return this._activity({});
}
_activity(data) {
if (!this.isTTY || this.noProgress) {
return {
tick() {},
end() {}
};
}
const id = this._activityId++;
this._dump('activityStart', _objectSpread2({
id
}, data));
return {
tick: name => {
this._dump('activityTick', {
id,
name
});
},
end: () => {
this._dump('activityEnd', {
id
});
}
};
}
progress(total) {
if (this.noProgress) {
return function () {// noop
};
}
const id = this._progressId++;
let current = 0;
this._dump('progressStart', {
id,
total
});
return () => {
current++;
this._dump('progressTick', {
id,
current
});
if (current === total) {
this._dump('progressFinish', {
id
});
}
};
}
}
// import os from 'os';
// import * as path from 'path';
// import userHome from './util/user-home-dir.js';
// import {getCacheDir, getConfigDir, getDataDir} from './util/user-dirs.js';
const DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDependencies']; // export const OWNED_DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDependencies'];
const RESOLUTIONS = 'resolutions';
const MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES];
// export const NPM_REGISTRY_RE = /https?:\/\/registry\.npmjs\.org/g;
// export const PIKA_DOCS = 'https://yarnpkg.com/en/docs/cli/';
// export const PIKA_INSTALLER_SH = 'https://yarnpkg.com/install.sh';
// export const PIKA_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi';
// export const SELF_UPDATE_VERSION_URL = 'https://www.pikapkg.com/downloads/latest-version';
// // cache version, bump whenever we make backwards incompatible changes
// export const CACHE_VERSION = 3;
// // lockfile version, bump whenever we make backwards incompatible changes
// export const LOCKFILE_VERSION = 1;
// // max amount of network requests to perform concurrently
// export const NETWORK_CONCURRENCY = 8;
// // HTTP timeout used when downloading packages
// export const NETWORK_TIMEOUT = 30 * 1000; // in milliseconds
// // max amount of child processes to execute concurrently
const CHILD_CONCURRENCY = 5; // export const REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid'];
const NODE_PACKAGE_JSON = 'package.json'; // export const PNP_FILENAME = '.pnp';
// export const POSIX_GLOBAL_PREFIX = `${process.env.DESTDIR || ''}/usr/local`;
// export const FALLBACK_GLOBAL_PREFIX = path.join(userHome, '.pika');
// export const META_FOLDER = '.pika-meta';
// export const INTEGRITY_FILENAME = '.pika-integrity';
// export const LOCKFILE_FILENAME = 'pika.lock';
// export const LEGACY_LOCKFILE_FILENAME = 'yarn.lock';
// export const METADATA_FILENAME = '.pika-metadata.json';
// export const TARBALL_FILENAME = '.pika-tarball.tgz';
// export const CLEAN_FILENAME = '.pikaclean';
// export const NPM_LOCK_FILENAME = 'package-lock.json';
// export const NPM_SHRINKWRAP_FILENAME = 'npm-shrinkwrap.json';
const DEFAULT_INDENT = ' '; // export const SINGLE_INSTANCE_PORT = 31997;
// export const SINGLE_INSTANCE_FILENAME = '.pika-single-instance';
const ENV_PATH_KEY = getPathKey(process.platform, process.env);
function getPathKey(platform, env) {
let pathKey = 'PATH'; // windows calls its path "Path" usually, but this is not guaranteed.
if (platform === 'win32') {
pathKey = 'Path';
for (const key in env) {
if (key.toLowerCase() === 'path') {
pathKey = key;
}
}
}
return pathKey;
} // export const VERSION_COLOR_SCHEME: {[key: string]: VersionColor} = {
// major: 'red',
// premajor: 'red',
// minor: 'yellow',
// preminor: 'yellow',
// patch: 'green',
// prepatch: 'green',
// prerelease: 'red',
// unchanged: 'white',
// unknown: 'red',
// };
// export type VersionColor = 'red' | 'yellow' | 'green' | 'white';
// export type RequestHint = 'dev' | 'optional' | 'resolution' | 'workspaces';
function nullify(obj) {
if (Array.isArray(obj)) {
for (const item of obj) {
nullify(item);
}
} else if (obj !== null && typeof obj === 'object' || typeof obj === 'function') {
Object.setPrototypeOf(obj, null); // for..in can only be applied to 'object', not 'function'
if (typeof obj === 'object') {
for (const key in obj) {
nullify(obj[key]);
}
}
}
return obj;
}
const unlink = util.promisify(_rimraf);
const glob = util.promisify(_glob);
const mkdirp = util.promisify(_mkdirp); //
const open = util.promisify(fs.open);
const writeFile = util.promisify(fs.writeFile);
const readlink = util.promisify(fs.readlink);
const realpath = util.promisify(fs.realpath);
const readdir = util.promisify(fs.readdir);
const rename = util.promisify(fs.rename);
const access = util.promisify(fs.access);
const stat = util.promisify(fs.stat);
const exists = util.promisify(fs.exists);
const lstat = util.promisify(fs.lstat);
const chmod = util.promisify(fs.chmod);
const link = util.promisify(fs.link);
const copyFile = util.promisify(fs.copyFile);
const readFileBuffer = util.promisify(fs.readFile);
const readFile = path => {
return util.promisify(fs.readFile)(path, {
encoding: 'utf-8'
});
}; // export {unlink};
// export type CopyQueueItem = {
// src: string,
// dest: string,
// type?: string,
// onFresh?: () => void,
// onDone?: () => void,
// };
// type CopyQueue = Array<CopyQueueItem>;
// type LinkFileAction = {
// src: string,
// dest: string,
// removeDest: boolean,
// };
// type CopySymlinkAction = {
// dest: string,
// linkname: string,
// };
// type CopyActions = {
// file: Array<CopyFileAction>,
// symlink: Array<CopySymlinkAction>,
// link: Array<LinkFileAction>,
// };
// type CopyOptions = {
// onProgress: (dest: string) => void,
// onStart: (num: number) => void,
// possibleExtraneous: Set<string>,
// ignoreBasenames: Array<string>,
// artifactFiles: Array<string>,
// };
// type FailedFolderQuery = {
// error: Error,
// folder: string,
// };
// type FolderQueryResult = {
// skipped: Array<FailedFolderQuery>,
// folder?: string,
// };
// async function buildActionsForCopy(
// queue: CopyQueue,
// events: CopyOptions,
// possibleExtraneous: Set<string>,
// reporter: Reporter,
// ): Promise<CopyActions> {
// const artifactFiles: Set<string> = new Set(events.artifactFiles || []);
// const files: Set<string> = new Set();
// // initialise events
// for (const item of queue) {
// const onDone = item.onDone;
// item.onDone = () => {
// events.onProgress(item.dest);
// if (onDone) {
// onDone();
// }
// };
// }
// events.onStart(queue.length);
// // start building actions
// const actions: CopyActions = {
// file: [],
// symlink: [],
// link: [],
// };
// // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items
// // at a time due to the requirement to push items onto the queue
// while (queue.length) {
// const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);
// await Promise.all(items.map(build));
// }
// // simulate the existence of some files to prevent considering them extraneous
// for (const file of artifactFiles) {
// if (possibleExtraneous.has(file)) {
// reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));
// possibleExtraneous.delete(file);
// }
// }
// for (const loc of possibleExtraneous) {
// if (files.has(loc.toLowerCase())) {
// possibleExtraneous.delete(loc);
// }
// }
// return actions;
// //
// async function build(data: CopyQueueItem): Promise<void> {
// const {src, dest, type} = data;
// const onFresh = data.onFresh || noop;
// const onDone = data.onDone || noop;
// // TODO https://github.com/yarnpkg/yarn/issues/3751
// // related to bundled dependencies handling
// if (files.has(dest.toLowerCase())) {
// reporter.verbose(`The case-insensitive file ${dest} shouldn't be copied twice in one bulk copy`);
// } else {
// files.add(dest.toLowerCase());
// }
// if (type === 'symlink') {
// await mkdirp(path.dirname(dest));
// onFresh();
// actions.symlink.push({
// dest,
// linkname: src,
// });
// onDone();
// return;
// }
// if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {
// // ignored file
// return;
// }
// const srcStat = await lstat(src);
// let srcFiles;
// if (srcStat.isDirectory()) {
// srcFiles = await readdir(src);
// }
// let destStat;
// try {
// // try accessing the destination
// destStat = await lstat(dest);
// } catch (e) {
// // proceed if destination doesn't exist, otherwise error
// if (e.code !== 'ENOENT') {
// throw e;
// }
// }
// // if destination exists
// if (destStat) {
// const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();
// const bothFolders = srcStat.isDirectory() && destStat.isDirectory();
// const bothFiles = srcStat.isFile() && destStat.isFile();
// // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving
// // us modes that aren't valid. investigate this, it's generally safe to proceed.
// /* if (srcStat.mode !== destStat.mode) {
// try {
// await access(dest, srcStat.mode);
// } catch (err) {}
// } */
// if (bothFiles && artifactFiles.has(dest)) {
// // this file gets changed during build, likely by a custom install script. Don't bother checking it.
// onDone();
// reporter.verbose(reporter.lang('verboseFileSkipArtifact', src));
// return;
// }
// if (bothFiles && srcStat.size === destStat.size && fileDatesEqual(srcStat.mtime, destStat.mtime)) {
// // we can safely assume this is the same file
// onDone();
// reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.size, +srcStat.mtime));
// return;
// }
// if (bothSymlinks) {
// const srcReallink = await readlink(src);
// if (srcReallink === (await readlink(dest))) {
// // if both symlinks are the same then we can continue on
// onDone();
// reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));
// return;
// }
// }
// if (bothFolders) {
// // mark files that aren't in this folder as possibly extraneous
// const destFiles = await readdir(dest);
// invariant(srcFiles, 'src files not initialised');
// for (const file of destFiles) {
// if (srcFiles.indexOf(file) < 0) {
// const loc = path.join(dest, file);
// possibleExtraneous.add(loc);
// if ((await lstat(loc)).isDirectory()) {
// for (const file of await readdir(loc)) {
// possibleExtraneous.add(path.join(loc, file));
// }
// }
// }
// }
// }
// }
// if (destStat && destStat.isSymbolicLink()) {
// await unlink(dest);
// destStat = null;
// }
// if (srcStat.isSymbolicLink()) {
// onFresh();
// const linkname = await readlink(src);
// actions.symlink.push({
// dest,
// linkname,
// });
// onDone();
// } else if (srcStat.isDirectory()) {
// if (!destStat) {
// reporter.verbose(reporter.lang('verboseFileFolder', dest));
// await mkdirp(dest);
// }
// const destParts = dest.split(path.sep);
// while (destParts.length) {
// files.add(destParts.join(path.sep).toLowerCase());
// destParts.pop();
// }
// // push all files to queue
// invariant(srcFiles, 'src files not initialised');
// let remaining = srcFiles.length;
// if (!remaining) {
// onDone();
// }
// for (const file of srcFiles) {
// queue.push({
// dest: path.join(dest, file),
// onFresh,
// onDone: () => {
// if (--remaining === 0) {
// onDone();
// }
// },
// src: path.join(src, file),
// });
// }
// } else if (srcStat.isFile()) {
// onFresh();
// actions.file.push({
// src,
// dest,
// atime: srcStat.atime,
// mtime: srcStat.mtime,
// mode: srcStat.mode,
// });
// onDone();
// } else {
// throw new Error(`unsure how to copy this: ${src}`);
// }
// }
// }
// async function buildActionsForHardlink(
// queue: CopyQueue,
// events: CopyOptions,
// possibleExtraneous: Set<string>,
// reporter: Reporter,
// ): Promise<CopyActions> {
// const artifactFiles: Set<string> = new Set(events.artifactFiles || []);
// const files: Set<string> = new Set();
// // initialise events
// for (const item of queue) {
// const onDone = item.onDone || noop;
// item.onDone = () => {
// events.onProgress(item.dest);
// onDone();
// };
// }
// events.onStart(queue.length);
// // start building actions
// const actions: CopyActions = {
// file: [],
// symlink: [],
// link: [],
// };
// // custom concurrency logic as we're always executing stacks of CONCURRENT_QUEUE_ITEMS queue items
// // at a time due to the requirement to push items onto the queue
// while (queue.length) {
// const items = queue.splice(0, CONCURRENT_QUEUE_ITEMS);
// await Promise.all(items.map(build));
// }
// // simulate the existence of some files to prevent considering them extraneous
// for (const file of artifactFiles) {
// if (possibleExtraneous.has(file)) {
// reporter.verbose(reporter.lang('verboseFilePhantomExtraneous', file));
// possibleExtraneous.delete(file);
// }
// }
// for (const loc of possibleExtraneous) {
// if (files.has(loc.toLowerCase())) {
// possibleExtraneous.delete(loc);
// }
// }
// return actions;
// //
// async function build(data: CopyQueueItem): Promise<void> {
// const {src, dest} = data;
// const onFresh = data.onFresh || noop;
// const onDone = data.onDone || noop;
// if (files.has(dest.toLowerCase())) {
// // Fixes issue https://github.com/yarnpkg/yarn/issues/2734
// // When bulk hardlinking we have A -> B structure that we want to hardlink to A1 -> B1,
// // package-linker passes that modules A1 and B1 need to be hardlinked,
// // the recursive linking algorithm of A1 ends up scheduling files in B1 to be linked twice which will case
// // an exception.
// onDone();
// return;
// }
// files.add(dest.toLowerCase());
// if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) {
// // ignored file
// return;
// }
// const srcStat = await lstat(src);
// let srcFiles;
// if (srcStat.isDirectory()) {
// srcFiles = await readdir(src);
// }
// const destExists = await exists(dest);
// if (destExists) {
// const destStat = await lstat(dest);
// const bothSymlinks = srcStat.isSymbolicLink() && destStat.isSymbolicLink();
// const bothFolders = srcStat.isDirectory() && destStat.isDirectory();
// const bothFiles = srcStat.isFile() && destStat.isFile();
// if (srcStat.mode !== destStat.mode) {
// try {
// await access(dest, srcStat.mode);
// } catch (err) {
// // EINVAL access errors sometimes happen which shouldn't because node shouldn't be giving
// // us modes that aren't valid. investigate this, it's generally safe to proceed.
// reporter.verbose(err);
// }
// }
// if (bothFiles && artifactFiles.has(dest)) {
// // this file gets changed during build, likely by a custom install script. Don't bother checking it.
// onDone();
// reporter.verbose(reporter.lang('verboseFileSkipArtifact', src));
// return;
// }
// // correct hardlink
// if (bothFiles && srcStat.ino !== null && srcStat.ino === destStat.ino) {
// onDone();
// reporter.verbose(reporter.lang('verboseFileSkip', src, dest, srcStat.ino));
// return;
// }
// if (bothSymlinks) {
// const srcReallink = await readlink(src);
// if (srcReallink === (await readlink(dest))) {
// // if both symlinks are the same then we can continue on
// onDone();
// reporter.verbose(reporter.lang('verboseFileSkipSymlink', src, dest, srcReallink));
// return;
// }
// }
// if (bothFolders) {
// // mark files that aren't in this folder as possibly extraneous
// const destFiles = await readdir(dest);
// invariant(srcFiles, 'src files not initialised');
// for (const file of destFiles) {
// if (srcFiles.indexOf(file) < 0) {
// const loc = path.join(dest, file);
// possibleExtraneous.add(loc);
// if ((await lstat(loc)).isDirectory()) {
// for (const file of await readdir(loc)) {
// possibleExtraneous.add(path.join(loc, file));
// }
// }
// }
// }
// }
// }
// if (srcStat.isSymbolicLink()) {
// onFresh();
// const linkname = await readlink(src);
// actions.symlink.push({
// dest,
// linkname,
// });
// onDone();
// } else if (srcStat.isDirectory()) {
// reporter.verbose(reporter.lang('verboseFileFolder', dest));
// await mkdirp(dest);
// const destParts = dest.split(path.sep);
// while (destParts.length) {
// files.add(destParts.join(path.sep).toLowerCase());
// destParts.pop();
// }
// // push all files to queue
// invariant(srcFiles, 'src files not initialised');
// let remaining = srcFiles.length;
// if (!remaining) {
// onDone();
// }
// for (const file of srcFiles) {
// queue.push({
// onFresh,
// src: path.join(src, file),
// dest: path.join(dest, file),
// onDone: () => {
// if (--remaining === 0) {
// onDone();
// }
// },
// });
// }
// } else if (srcStat.isFile()) {
// onFresh();
// actions.link.push({
// src,
// dest,
// removeDest: destExists,
// });
// onDone();
// } else {
// throw new Error(`unsure how to copy this: ${src}`);
// }
// }
// }
// export function copy(src: string, dest: string, reporter: Reporter): Promise<void> {
// return copyBulk([{src, dest}], reporter);
// }
// export async function copyBulk(
// queue: CopyQueue,
// reporter: Reporter,
// _events?: {
// onProgress?: (dest: string) => void,
// onStart?: (num: number) => void,
// possibleExtraneous: Set<string>,
// ignoreBasenames?: Array<string>,
// artifactFiles?: Array<string>,
// },
// ): Promise<void> {
// const events: CopyOptions = {
// onStart: (_events && _events.onStart) || noop,
// onProgress: (_events && _events.onProgress) || noop,
// possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),
// ignoreBasenames: (_events && _events.ignoreBasenames) || [],
// artifactFiles: (_events && _events.artifactFiles) || [],
// };
// const actions: CopyActions = await buildActionsForCopy(queue, events, events.possibleExtraneous, reporter);
// events.onStart(actions.file.length + actions.symlink.length + actions.link.length);
// const fileActions: Array<CopyFileAction> = actions.file;
// const currentlyWriting: Map<string, Promise<void>> = new Map();
// await promise.queue(
// fileActions,
// async (data: CopyFileAction): Promise<void> => {
// let writePromise;
// while ((writePromise = currentlyWriting.get(data.dest))) {
// await writePromise;
// }
// reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest));
// const copier = copyFile(data, () => currentlyWriting.delete(data.dest));
// currentlyWriting.set(data.dest, copier);
// events.onProgress(data.dest);
// return copier;
// },
// CONCURRENT_QUEUE_ITEMS,
// );
// // we need to copy symlinks last as they could reference files we were copying
// const symlinkActions: Array<CopySymlinkAction> = actions.symlink;
// await promise.queue(symlinkActions, (data): Promise<void> => {
// const linkname = path.resolve(path.dirname(data.dest), data.linkname);
// reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));
// return symlink(linkname, data.dest);
// });
// }
// export async function hardlinkBulk(
// queue: CopyQueue,
// reporter: Reporter,
// _events?: {
// onProgress?: (dest: string) => void,
// onStart?: (num: number) => void,
// possibleExtraneous: Set<string>,
// artifactFiles?: Array<string>,
// },
// ): Promise<void> {
// const events: CopyOptions = {
// onStart: (_events && _events.onStart) || noop,
// onProgress: (_events && _events.onProgress) || noop,
// possibleExtraneous: _events ? _events.possibleExtraneous : new Set(),
// artifactFiles: (_events && _events.artifactFiles) || [],
// ignoreBasenames: [],
// };
// const actions: CopyActions = await buildActionsForHardlink(queue, events, events.possibleExtraneous, reporter);
// events.onStart(actions.file.length + actions.symlink.length + actions.link.length);
// const fileActions: Array<LinkFileAction> = actions.link;
// await promise.queue(
// fileActions,
// async (data): Promise<void> => {
// reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest));
// if (data.removeDest) {
// await unlink(data.dest);
// }
// await link(data.src, data.dest);
// },
// CONCURRENT_QUEUE_ITEMS,
// );
// // we need to copy symlinks last as they could reference files we were copying
// const symlinkActions: Array<CopySymlinkAction> = actions.symlink;
// await promise.queue(symlinkActions, (data): Promise<void> => {
// const linkname = path.resolve(path.dirname(data.dest), data.linkname);
// reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname));
// return symlink(linkname, data.dest);
// });
// }
// function _readFile(loc: string, encoding: string): Promise<any> {
// return new Promise((resolve, reject) => {
// fs.readFile(loc, encoding, function(err, content) {
// if (err) {
// reject(err);
// } else {
// resolve(content);
// }
// });
// });
// }
// export function readFile(loc: string): Promise<string> {
// return _readFile(loc, 'utf8').then(normalizeOS);
// }
// export function readFileRaw(loc: string): Promise<Buffer> {
// return _readFile(loc, 'binary');
// }
// export async function readFileAny(files: Array<string>): Promise<string | null> {
// for (const file of files) {
// if (await exists(file)) {
// return readFile(file);
// }
// }
// return null;
// }
async function readJson(loc) {
return (await readJsonAndFile(loc)).object;
}
async function readJsonAndFile(loc) {
const file = await readFile(loc);
try {
return {
object: nullify(JSON.parse(stripBOM(file))),
content: file
};
} catch (err) {
err.message = `${loc}: ${err.message}`;
throw err;
}
}
// const stat = await lstat(loc);
// const {size, blksize: blockSize} = stat;
// return Math.ceil(size / blockSize) * blockSize;
// }
// export function normalizeOS(body: string): string {
// return body.replace(/\r\n/g, '\n');
// }
const cr = '\r'.charCodeAt(0);
const lf = '\n'.charCodeAt(0);
async function getEolFromFile(path) {
if (!(await exists(path))) {
return undefined;
}
const buffer = await readFileBuffer(path);
for (let i = 0; i < buffer.length; ++i) {
if (buffer[i] === cr) {
return '\r\n';
}
if (buffer[i] === lf) {
return '\n';
}
}
return undefined;
}
async function writeFilePreservingEol(path, data) {
const eol = (await getEolFromFile(path)) || os.EOL;
if (eol !== '\n') {
data = data.replace(/\n/g, eol);
}
await writeFile(path, data);
} // export async function hardlinksWork(dir: string): Promise<boolean> {
// const filename = 'test-file' + Math.random();
// const file = path.join(dir, filename);
// const fileLink = path.join(dir, filename + '-link');
// try {
// await writeFile(file, 'test');
// await link(file, fileLink);
// } catch (err) {
// return false;
// } finally {
// await unlink(file);
// await unlink(fileLink);
// }
// return true;
// }
// // not a strict polyfill for Node's fs.mkdtemp
// export async function makeTempDir(prefix?: string): Promise<string> {
// const dir = path.join(os.tmpdir(), `pika-${prefix || ''}-${Date.now()}-${Math.random()}`);
// await unlink(dir);
// await mkdirp(dir);
// return dir;
// }
// export async function readFirstAvailableStream(paths: Iterable<string>): Promise<?ReadStream> {
// for (const path of paths) {
// try {
// const fd = await open(path, 'r');
// return fs.createReadStream(path, {fd});
// } catch (err) {
// // Try the next one
// }
// }
// return null;
// }
// export async function getFirstSuitableFolder(
// paths: Iterable<string>,
// mode: number = constants.W_OK | constants.X_OK, // eslint-disable-line no-bitwise
// ): Promise<FolderQueryResult> {
// const result: FolderQueryResult = {
// skipped: [],
// folder: null,
// };
// for (const folder of paths) {
// try {
// await mkdirp(folder);
// await access(folder, mode);
// result.folder = folder;
// return result;
// } catch (error) {
// result.skipped.push({
// error,
// folder,
// });
// }
// }
// return result;
// }
async function generatePublishManifest(manifest, config, _dists) {
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;
const newManifest = {
name,
description,
version,
license,
bin,
files: ['dist-*/', 'bin/'],
pika: true,
sideEffects: sideEffects || false,
keywords,
homepage,
bugs,
authors,
contributors,
man,
repository,
dependencies: dependencies || {},
peerDependencies,
devDependencies,
bundledDependencies,
optionalDependencies,
engines,
enginesStrict,
private: priv,
publishConfig
};
const dists = _dists || (await config.getDistributions());
for (const [runner, options] of dists) {
if (runner.manifest) {
await runner.manifest(newManifest, {
cwd: config.cwd,
isFull: true,
manifest,
options
});
}
}
newManifest.pika = true;
return newManifest;
}
function generatePrettyManifest(manifest) {
return JSON.stringify(_objectSpread2({}, manifest, {
dependencies: Object.keys(manifest.dependencies).length === 0 ? {} : '{ ... }'
}), null, 2);
}
function hasWrapper() {
return true;
}
const examples = null;
class Build {
constructor(flags, config, reporter) {
this.flags = flags;
this.config = config;
this.reporter = reporter;
this.totalNum = 0;
this.out = path.resolve(config.cwd, flags.out || 'pkg/');
if (this.out === this.config.cwd) {
throw new Error('On publish, you cannot write to cwd because a package.json is created');
}
}
async cleanup() {
const {
out
} = this;
await unlink(path.join(out, '*'));
}
async init(isFull) {
const {
config,
out,
reporter,
flags
} = this;
const {
cwd
} = config;
const outPretty = path.relative(cwd, out) + path.sep;
const manifest = await config.manifest;
const {
sourcemap
} = manifest['@pika/pack'] || {
sourcemap: true
};
const distRunners = await config.getDistributions();
const builderConfig = {
out,
cwd,
reporter: {
info: msg => reporter.log(chalk.dim(` » ${msg}`)),
warning: msg => reporter.log(chalk.yellow(` » ${msg}`)),
success: msg => reporter.log(chalk.green(` » ${msg}`)),
created: (filename, entrypoint) => reporter.log(` 📝 ${chalk.green(path.relative(cwd, filename))} ${entrypoint ? chalk.dim(`[${entrypoint}]`) : ''}`)
},
isFull,
manifest,
src: {
loc: path.join(out, 'dist-src'),
entrypoint: path.join(out, 'dist-src', 'index.js'),
// TODO: Deprecated, remove
options: {},
// TODO: Deprecated, remove
files: await (async () => {
const ignoreSet = new Set([]);
ignoreSet.add('**/*/README.md');
const files = await glob(`src/**/*`, {
cwd,
nodir: true,
absolute: true,
ignore: Array.from(ignoreSet).map(g => path.join('src', g))
});
return files.filter(fileAbs => !fileAbs.endsWith('.d.ts'));
})()
}
};
const steps = [];
steps.push(async (curr, total) => {
this.reporter.step(curr, total, 'Validating source');
for (const [runner, options] of distRunners) {
if (runner.validate) {
const result = await runner.validate(_objectSpread2({}, builderConfig, {
options: _objectSpread2({
sourcemap
}, options)
}));
if (result instanceof Error) {
throw result;
}
}
}
});
steps.push(async (curr, total) => {
this.reporter.step(curr, total, `Preparing pipeline`);
await this.cleanup();
reporter.log(` ❇️ ${chalk.green(outPretty)}`);
for (const [runner, options] of distRunners) {
await (runner.beforeBuild && runner.beforeBuild(_objectSpread2({}, builderConfig, {
options: _objectSpread2({
sourcemap
}, options)
})));
}
});
if (distRunners.length === 0) {
steps.push(async (curr, total) => {
this.reporter.step(curr, total, `Pipeline is empty! See ${chalk.underline('https://github.com/pikapkg/pack')} for help getting started`);
});
}
for (const [runner, options] of distRunners) {
steps.push(async (curr, total) => {
this.reporter.step(curr, total, `Running ${chalk.bold(runner.name)}`); // return Promise.resolve(
try {
await (runner.beforeJob && runner.beforeJob(_objectSpread2({}, builderConfig, {
options: _objectSpread2({
sourcemap
}, options)
})));
await (runner.build && runner.build(_objectSpread2({}, builderConfig, {
options: _objectSpread2({
sourcemap
}, options)
})));
await (runner.afterJob && runner.afterJob(_objectSpread2({}, builderConfig, {
options: _objectSpread2({
sourcemap
}, options)
})));
} catch (err) {
if (flags.force) {
console.log(' ❗️ ', chalk.red(err.message), chalk.dim('--force, continuing...'));
} else {
throw err;
}
} // ).catch(err => {
// log(chalk.red(err.message));
// reporter.log(
// reporter.lang("distFailed", runner.name, err.code, err.message),
// { force: true }
// );
// if (err.forceExit === true) {
// reporter.log(reporter.lang("distExiting"));
// throw err;
// return;
// }
// reporter.log(reporter.lang("distContinuing"));
// });
});
}
steps.push(async (curr, total) => {
this.reporter.step(curr, total, `Finalizing package`);
for (const [runner, options] of distRunners) {
await (runner.afterBuild && runner.afterBuild(_objectSpread2({}, builderConfig, {
options: _objectSpread2({
sourcemap
}, options)
})));
}
if (await exists(path.join(cwd, 'CHANGELOG'))) {
copyFile(path.join(cwd, 'CHANGELOG'), path.join(out, 'CHANGELOG'));
reporter.log(chalk.dim(` » copying CHANGELOG...`));
} else if (await exists(path.join(cwd, 'CHANGELOG.md'))) {
copyFile(path.join(cwd, 'CHANGELOG.md'), path.join(out, 'CHANGELOG.md'));
reporter.log(chalk.dim(` » copying CHANGELOG.md...`));
}
if (await exists(path.join(cwd, 'LICENSE'))) {
copyFile(path.join(cwd, 'LICENSE'), path.join(out, 'LICENSE'));
reporter.log(chalk.dim(` » copying LICENSE...`));
} else if (await exists(path.join(cwd, 'LICENSE.md'))) {
copyFile(path.join(cwd, 'LICENSE.md'), path.join(out, 'LICENSE.md'));
reporter.log(chalk.dim(` » copying LICENSE.md...`));
}
if (await exists(path.join(cwd, 'README'))) {
copyFile(path.join(cwd, 'README'), path.join(out, 'README'));
reporter.log(chalk.dim(` » copying README...`));
} else if (await exists(path.join(cwd, 'README.md'))) {
copyFile(path.join(cwd, 'README.md'), path.join(out, 'README.md'));
reporter.log(chalk.dim(` » copying README.md...`));
}
const publishManifest = await generatePublishManifest(config._manifest, config, distRunners);
if (out === cwd) {
reporter.log(`NEW MANIFEST:\n\n`);
reporter.log(generatePrettyManifest(publishManifest));
reporter.log(`\n\n`);
} else {
await writeFilePreservingEol(path.join(out, 'package.json'), JSON.stringify(publishManifest, null, DEFAULT_INDENT) + '\n');
reporter.log(` 📝 ` + chalk.green(outPretty + 'package.json'));
}
reporter.log(` 📦 ` + chalk.green(outPretty));
});
let currentStep = 0;
for (const step of steps) {
await step(++currentStep, steps.length);
}
}
}
async function run(config, reporter, flags, args) {
const isProduction = flags.publish;
const builder = new Build(flags, config, reporter);
await builder.init(isProduction);
}
var buildCommand = /*#__PURE__*/Object.freeze({
hasWrapper: hasWrapper,
examples: examples,
Build: Build,
run: run
});
var typos = {
autohr: 'author',
autor: 'author',
contributers: 'contributors',
depdenencies: 'dependencies',
dependancies: 'dependencies',
dependecies: 'dependencies',
depends: 'dependencies',
'dev-dependencies': 'devDependencies',
devDependences: 'devDependencies',
devDepenencies: 'devDependencies',
devEependencies: 'devDependencies',
devdependencies: 'devDependencies',
hampage: 'homepage',
hompage: 'homepage',
prefereGlobal: 'preferGlobal',
publicationConfig: 'publishConfig',
repo: 'repository',
repostitory: 'repository',
script: 'scripts'
};
const strings = ['name', 'version'];
const dependencyKeys = [// npm registry will include optionalDependencies in dependencies and we'll want to dedupe them from the
// other fields first
'optionalDependencies', // it's seemingly common to include a dependency in dependencies and devDependencies of the same name but
// different ranges, this can cause a lot of issues with our determinism and the behaviour of npm is
// currently unspecified.
'dependencies', 'devDependencies'];
function isValidName(name) {
return !name.match(/[\/@\s\+%:]/) && encodeURIComponent(name) === name;
}
function isValidScopedName(name) {
if (name[0] !== '@') {
return false;
}
const parts = name.slice(1).split('/');
return parts.length === 2 && isValidName(parts[0]) && isValidName(parts[1]);
}
function isValidPackageName(name) {
return isValidName(name) || isValidScopedName(name);
}
function validate (info, isRoot, reporter, warn) {
if (isRoot) {
for (const key in typos) {
if (key in info) {
warn(reporter.lang('manifestPotentialTypo', key, typos[key]));
}
}
} // validate name
const {
name
} = info;
if (typeof name === 'string') {
if (isRoot && isBuiltinModule(name)) {
warn(reporter.lang('manifestBuiltinModule', name));
} // cannot start with a dot
if (name[0] === '.') {
throw new types.MessageError(reporter.lang('manifestNameDot'));
} // cannot contain the following characters
if (!isValidPackageName(name)) {
throw new types.MessageError(reporter.lang('manifestNameIllegalChars'));
} // cannot equal node_modules or favicon.ico
const lower = name.toLowerCase();
if (lower === 'node_modules' || lower === 'favicon.ico') {
throw new types.MessageError(reporter.lang('manifestNameBlacklisted'));
}
} // Only care if you are trying to publish to npm.
// // validate license
// if (isRoot && !info.private) {
// if (typeof info.license === 'string') {
// const license = info.license.replace(/\*$/g, '');
// if (!isValidLicense(license)) {
// warn(reporter.lang('manifestLicenseInvalid'));
// }
// } else {
// warn(reporter.lang('manifestLicenseNone'));
// }
// }
// validate strings
for (const key of strings) {
const val = info[key];
if (val && typeof val !== 'string') {
throw new types.MessageError(reporter.lang('manifestStringExpected', key));
}
}
cleanDependencies(info, isRoot, reporter, warn);
}
function cleanDependencies(info, isRoot, reporter, warn) {
// get dependency objects
const depTypes = [];
for (const type of dependencyKeys) {
const deps = info[type];
if (!deps || typeof deps !== 'object') {
continue;
}
depTypes.push([type, deps]);
} // aggregate all non-trivial deps (not '' or '*')
const nonTrivialDeps = new Map();
for (const [type, deps] of depTypes) {
for (const name of Object.keys(deps)) {
const version = deps[name];
if (!nonTrivialDeps.has(name) && version && version !== '*') {
nonTrivialDeps.set(name, {
type,
version
});
}
}
} // overwrite first dep of package with non-trivial version, remove the rest
const setDeps = new Set();
for (const [type, deps] of depTypes) {
for (const name of Object.keys(deps)) {
let version = deps[name];
const dep = nonTrivialDeps.get(name);
if (dep) {
if (version && version !== '*' && version !== dep.version && isRoot) {
// only throw a warning when at the root
warn(reporter.lang('manifestDependencyCollision', dep.type, name, dep.version, type, version));
}
version = dep.version;
}
if (setDeps.has(name)) {
delete deps[name];
} else {
deps[name] = version;
setDeps.add(name);
}
}
}
}
function isValidLicense(license) {
return !!license && validateLicense(license).validForNewPackages;
}
function stringifyPerson(person) {
if (!person || typeof person !== 'object') {
return person;
}
const parts = [];
if (person.name) {
parts.push(person.name);
}
const email = person.email || person.mail;
if (typeof email === 'string') {
parts.push(`<${email}>`);
}
const url = person.url || person.web;
if (typeof url === 'string') {
parts.push(`(${url})`);
}
return parts.join(' ');
}
function parsePerson(person) {
if (typeof person !== 'string') {
return person;
} // format: name (url) <email>
const obj = {};
let name = person.match(/^([^\(<]+)/);
if (name && name[0].trim()) {
obj.name = name[0].trim();
}
const email = person.match(/<([^>]+)>/);
if (email) {
obj.email = email[1];
}
const url = person.match(/\(([^\)]+)\)/);
if (url) {
obj.url = url[1];
}
return obj;
}
function normalizePerson(person) {
return parsePerson(stringifyPerson(person));
}
function extractDescription(readme) {
if (typeof readme !== 'string' || readme === '') {
return undefined;
} // split into lines
const lines = readme.trim().split('\n').map(line => line.trim()); // find the start of the first paragraph, ignore headings
let start = 0;
for (; start < lines.length; start++) {
const line = lines[start];
if (line && line.match(/^(#|$)/)) {
// line isn't empty and isn't a heading so this is the start of a paragraph
start++;
break;
}
} // skip newlines from the header to the first line
while (start < lines.length && !lines[start]) {
start++;
} // continue to the first non empty line
let end = start;
while (end < lines.length && lines[end]) {
end++;
}
return lines.slice(start, end).join(' ');
}
var LICENSES = {
'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'),
'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'),
'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'),
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'),
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')
};
function clean(str) {
return str.replace(/[^A-Za-z\s]/g, ' ').replace(/[\s]+/g, ' ').trim().toLowerCase();
}
const REGEXES = {
Apache: [/Apache License\b/],
BSD: [/BSD\b/],
ISC: [/The ISC License/, /ISC\b/],
MIT: [/MIT\b/],
Unlicense: [/http:\/\/unlicense.org\//],
WTFPL: [/DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE/, /WTFPL\b/]
};
function inferLicense(license) {
// check if we have any explicit licenses
const cleanLicense = clean(license);
for (const licenseName in LICENSES) {
const testLicense = LICENSES[licenseName];
if (cleanLicense.search(testLicense) >= 0) {
return licenseName;
}
} // infer based on some keywords
for (const licenseName in REGEXES) {
for (const regex of REGEXES[licenseName]) {
if (license.search(regex) >= 0) {
return `${licenseName}*`;
}
}
}
return null;
}
const LICENSE_RENAMES = {
'MIT/X11': 'MIT',
X11: 'MIT'
};
var fix = (async function (info, moduleLoc, reporter, warn) {
const files = await readdir(moduleLoc); // clean info.version
if (typeof info.version === 'string') {
info.version = semver.clean(info.version) || info.version;
} // if name or version aren't set then set them to empty strings
info.name = info.name || '';
info.version = info.version || ''; // if the man field is a string then coerce it to an array
if (typeof info.man === 'string') {
info.man = [info.man];
} // if the keywords field is a string then split it on any whitespace
if (typeof info.keywords === 'string') {
info.keywords = info.keywords.split(/\s+/g);
} // if there's no contributors field but an authors field then expand it
if (!info.contributors && files.indexOf('AUTHORS') >= 0) {
const authorsFilepath = path.join(moduleLoc, 'AUTHORS');
const authorsFilestats = await stat(authorsFilepath);
if (authorsFilestats.isFile()) {
let authors = await readFile(authorsFilepath);
info.contributors = authors.split(/\r?\n/g) // split on lines
.map(line => line.replace(/^\s*#.*$/, '').trim()) // remove comments
.filter(line => !!line); // remove empty lines;
}
} // expand people fields to objects
if (typeof info.author === 'string' || typeof info.author === 'object') {
info.author = normalizePerson(info.author);
}
if (Array.isArray(info.contributors)) {
info.contributors = info.contributors.map(normalizePerson);
}
if (Array.isArray(info.maintainers)) {
info.maintainers = info.maintainers.map(normalizePerson);
} // if there's no readme field then load the README file from the cwd
if (!info.readme) {
const readmeCandidates = files.filter(filename => {
const lower = filename.toLowerCase();
return lower === 'readme' || lower.indexOf('readme.') === 0;
}).sort((filename1, filename2) => {
// favor files with extensions
return filename2.indexOf('.') - filename1.indexOf('.');
});
for (const readmeFilename of readmeCandidates) {
const readmeFilepath = path.join(moduleLoc, readmeFilename);
const readmeFileStats = await stat(readmeFilepath);
if (readmeFileStats.isFile()) {
info.readmeFilename = readmeFilename;
info.readme = await readFile(readmeFilepath);
break;
}
}
} // if there's no description then take the first paragraph from the readme
if (!info.description && info.readme) {
const desc = extractDescription(info.readme);
if (desc) {
info.description = desc;
}
} // support array of engine keys
if (Array.isArray(info.engines)) {
const engines = {};
for (const str of info.engines) {
if (typeof str === 'string') {
const [name, ...patternParts] = str.trim().split(/ +/g);
engines[name] = patternParts.join(' ');
}
}
info.engines = engines;
} // allow bugs to be specified as a string, expand it to an object with a single url prop
if (typeof info.bugs === 'string') {
info.bugs = {
url: info.bugs
};
} // normalize homepage url to http
if (typeof info.homepage === 'string') {
const parts = nodeUrl.parse(info.homepage);
parts.protocol = parts.protocol || 'http:';
if (parts.pathname && !parts.hostname) {
parts.hostname = parts.pathname;
parts.pathname = '';
}
info.homepage = nodeUrl.format(parts);
} // if the `bin` field is as string then expand it to an object with a single property
// based on the original `bin` field and `name field`
// { name: "foo", bin: "cli.js" } -> { name: "foo", bin: { foo: "cli.js" } }
if (typeof info.name === 'string' && typeof info.bin === 'string' && info.bin.length > 0) {
// Remove scoped package name for consistency with NPM's bin field fixing behaviour
const name = info.name.replace(/^@[^\/]+\//, '');
info.bin = {
[name]: info.bin
};
} // bundleDependencies is an alias for bundledDependencies
if (info.bundledDependencies) {
info.bundleDependencies = info.bundledDependencies;
delete info.bundledDependencies;
}
let scripts; // dummy script object to shove file inferred scripts onto
if (info.scripts && typeof info.scripts === 'object') {
scripts = info.scripts;
} else {
scripts = {};
} // if there's a server.js file and no start script then set it to `node server.js`
if (!scripts.start && files.indexOf('server.js') >= 0) {
scripts.start = 'node server';
} // if there's a binding.gyp file and no install script then set it to `node-gyp rebuild`
if (!scripts.install && files.indexOf('binding.gyp') >= 0) {
scripts.install = 'node-gyp rebuild';
} // set scripts if we've polluted the empty object
if (Object.keys(scripts).length) {
info.scripts = scripts;
}
const dirs = info.directories;
if (dirs && typeof dirs === 'object') {
const binDir = dirs.bin;
if (!info.bin && binDir && typeof binDir === 'string') {
const bin = info.bin = {};
const fullBinDir = path.join(moduleLoc, binDir);
if (await exists(fullBinDir)) {
for (const scriptName of await readdir(fullBinDir)) {
if (scriptName[0] === '.') {
continue;
}
bin[scriptName] = path.join('.', binDir, scriptName);
}
} else {
warn(reporter.lang('manifestDirectoryNotFound', binDir, info.name));
}
}
const manDir = dirs.man;
if (!info.man && typeof manDir === 'string') {
const man = info.man = [];
const fullManDir = path.join(moduleLoc, manDir);
if (await exists(fullManDir)) {
for (const filename of await readdir(fullManDir)) {
if (/^(.*?)\.[0-9]$/.test(filename)) {
man.push(path.join('.', manDir, filename));
}
}
} else {
warn(reporter.lang('manifestDirectoryNotFound', manDir, info.name));
}
}
}
delete info.directories; // normalize licenses field
const licenses = info.licenses;
if (Array.isArray(licenses) && !info.license) {
let licenseTypes = [];
for (let license of licenses) {
if (license && typeof license === 'object') {
license = license.type;
}
if (typeof license === 'string') {
licenseTypes.push(license);
}
}
licenseTypes = licenseTypes.filter(isValidLicense);
if (licenseTypes.length === 1) {
info.license = licenseTypes[0];
} else if (licenseTypes.length) {
info.license = `(${licenseTypes.join(' OR ')})`;
}
}
const license = info.license; // normalize license
if (license && typeof license === 'object') {
info.license = license.type;
} // get license file
const licenseFile = files.find(filename => {
const lower = filename.toLowerCase();
return lower === 'license' || lower.startsWith('license.') || lower === 'unlicense' || lower.startsWith('unlicense.');
});
if (licenseFile) {
const licenseFilepath = path.join(moduleLoc, licenseFile);
const licenseFileStats = await stat(licenseFilepath);
if (licenseFileStats.isFile()) {
const licenseContent = await readFile(licenseFilepath);
const inferredLicense = inferLicense(licenseContent);
info.licenseText = licenseContent;
const license = info.license;
if (typeof license === 'string') {
if (inferredLicense && isValidLicense(inferredLicense) && !isValidLicense(license)) {
// some packages don't specify their license version but we can infer it based on their license file
const basicLicense = license.toLowerCase().replace(/(-like|\*)$/g, '');
const expandedLicense = inferredLicense.toLowerCase();
if (expandedLicense.startsWith(basicLicense)) {
// TODO consider doing something to notify the user
info.license = inferredLicense;
}
}
} else if (inferredLicense) {
// if there's no license then infer it based on the license file
info.license = inferredLicense;
} else {
// valid expression to refer to a license in a file
info.license = `SEE LICENSE IN ${licenseFile}`;
}
}
}
if (typeof info.license === 'string') {
// sometimes licenses are known by different names, reduce them
info.license = LICENSE_RENAMES[info.license] || info.license;
} else if (typeof info.readme === 'string') {
// the license might be at the bottom of the README
const inferredLicense = inferLicense(info.readme);
if (inferredLicense) {
info.license = inferredLicense;
}
} // get notice file
const noticeFile = files.find(filename => {
const lower = filename.toLowerCase();
return lower === 'notice' || lower.startsWith('notice.');
});
if (noticeFile) {
const noticeFilepath = path.join(moduleLoc, noticeFile);
const noticeFileStats = await stat(noticeFilepath);
if (noticeFileStats.isFile()) {
info.noticeText = await readFile(noticeFilepath);
}
}
for (const dependencyType of MANIFEST_FIELDS) {
const dependencyList = info[dependencyType];
if (dependencyList && typeof dependencyList === 'object') {
delete dependencyList['//'];
for (const name in dependencyList) {
dependencyList[name] = dependencyList[name] || '';
}
}
}
});
var normalizeManifest = (async function (info, moduleLoc, config, isRoot) {
// Append dependencies
// if (depInfo) {
// info.dependencies = depInfo.main;
// info.devDependencies = depInfo.dev;
// }
// create human readable name
const {
name,
version
} = info;
let human;
if (typeof name === 'string') {
human = name;
}
if (human && typeof version === 'string' && version) {
human += `@${version}`;
}
if (isRoot && info._loc) {
human = path.relative(config.cwd, info._loc);
}
function warn(msg) {
if (human) {
msg = `${human}: ${msg}`;
}
config.reporter.warn(msg);
}
await fix(info, moduleLoc, config.reporter, warn);
try {
validate(info, isRoot, config.reporter, warn);
} catch (err) {
if (human) {
err.message = `${human}: ${err.message}`;
}
throw err;
}
return info;
});
class BlockingQueue {
constructor(alias, maxConcurrency = Infinity) {
this.concurrencyQueue = [];
this.maxConcurrency = maxConcurrency;
this.runningCount = 0;
this.warnedStuck = false;
this.alias = alias;
this.first = true;
this.running = nullify() || {};
this.queue = nullify() || {};
this.stuckTick = this.stuckTick.bind(this);
}
stillActive() {
if (this.stuckTimer) {
clearTimeout(this.stuckTimer);
}
this.stuckTimer = setTimeout(this.stuckTick, 5000); // We need to check the existence of unref because of https://github.com/facebook/jest/issues/4559
// $FlowFixMe: Node's setInterval returns a Timeout, not a Number
this.stuckTimer.unref && this.stuckTimer.unref();
}
stuckTick() {
if (this.runningCount === 1) {
this.warnedStuck = true;
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]}`);
}
}
push(key, factory) {
if (this.first) {
this.first = false;
} else {
this.stillActive();
}
return new Promise((resolve, reject) => {
// we're already running so push ourselves to the queue
const queue = this.queue[key] = this.queue[key] || [];
queue.push({
factory,
resolve,
reject
});
if (!this.running[key]) {
this.shift(key);
}
});
}
shift(key) {
if (this.running[key]) {
delete this.running[key];
this.runningCount--;
if (this.stuckTimer) {
clearTimeout(this.stuckTimer);
this.stuckTimer = null;
}
if (this.warnedStuck) {
this.warnedStuck = false;
console.log(`${JSON.stringify(this.alias)} blocking queue finally resolved. Nothing to worry about.`);
}
}
const queue = this.queue[key];
if (!queue) {
return;
}
const {
resolve,
reject,
factory
} = queue.shift();
if (!queue.length) {
delete this.queue[key];
}
const next = () => {
this.shift(key);
this.shiftConcurrencyQueue();
};
const run = () => {
this.running[key] = true;
this.runningCount++;
factory().then(function (val) {
resolve(val);
next();
return null;
}).catch(function (err) {
reject(err);
next();
});
};
this.maybePushConcurrencyQueue(run);
}
maybePushConcurrencyQueue(run) {
if (this.runningCount < this.maxConcurrency) {
run();
} else {
this.concurrencyQueue.push(run);
}
}
shiftConcurrencyQueue() {
if (this.runningCount < this.maxConcurrency) {
const fn = this.concurrencyQueue.shift();
if (fn) {
fn();
}
}
}
}
class ProcessSpawnError extends types.MessageError {
constructor(msg, code, process) {
super(msg);
this.code = code;
this.process = process;
}
}
class ProcessTermError extends types.MessageError {}
/* global child_process$spawnOpts */
const queue = new BlockingQueue('child', CHILD_CONCURRENCY); // TODO: this uid check is kinda whack
let uid = 0;
const spawnedProcesses = {};
function forwardSignalToSpawnedProcesses(signal) {
for (const key of Object.keys(spawnedProcesses)) {
spawnedProcesses[key].kill(signal);
}
}
function spawn(program, args, opts = {}, onData) {
const key = opts.cwd || String(++uid);
return queue.push(key, () => new Promise((resolve, reject) => {
const proc = child_process.spawn(program, args, opts);
spawnedProcesses[key] = proc;
let processingDone = false;
let processClosed = false;
let err = null;
let stdout = '';
proc.on('error', err => {
if (err.code === 'ENOENT') {
reject(new ProcessSpawnError(`Couldn't find the binary ${program}`, err.code, program));
} else {
reject(err);
}
});
function updateStdout(chunk) {
stdout += chunk;
if (onData) {
onData(chunk);
}
}
function finish() {
delete spawnedProcesses[key];
if (err) {
reject(err);
} else {
resolve(stdout.trim());
}
}
if (typeof opts.process === 'function') {
opts.process(proc, updateStdout, reject, function () {
if (processClosed) {
finish();
} else {
processingDone = true;
}
});
} else {
if (proc.stderr) {
proc.stderr.on('data', updateStdout);
}
if (proc.stdout) {
proc.stdout.on('data', updateStdout);
}
processingDone = true;
}
proc.on('close', (code, signal) => {
if (signal || code >= 1) {
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'));
err.EXIT_SIGNAL = signal;
err.EXIT_CODE = code;
}
if (processingDone || err) {
finish();
} else {
processClosed = true;
}
});
}));
}
function fixCmdWinSlashes(cmd) {
function findQuotes(quoteSymbol) {
const quotes = [];
const addQuote = (_, index) => {
quotes.push({
from: index,
to: index + _.length
});
return _;
};
const regEx = new RegExp(quoteSymbol + '.*' + quoteSymbol);
cmd.replace(regEx, addQuote);
return quotes;
}
const quotes = findQuotes('"').concat(findQuotes("'"));
function isInsideQuotes(index) {
return quotes.reduce((result, quote) => {
return result || quote.from <= index && index <= quote.to;
}, false);
}
const cmdPrePattern = '((?:^|&&|&|\\|\\||\\|)\\s*)';
const cmdPattern = '(".*?"|\'.*?\'|\\S*)';
const regExp = new RegExp(`${cmdPrePattern}${cmdPattern}`, 'g');
return cmd.replace(regExp, (whole, pre, cmd, index) => {
if ((pre[0] === '&' || pre[0] === '|') && isInsideQuotes(index)) {
return whole;
}
return pre + cmd.replace(/\//g, '\\');
});
}
// // We treat these configs as internal, thus not expose them to process.env.
// // This helps us avoid some gyp issues when building native modules.
// // See https://github.com/yarnpkg/yarn/issues/2286.
// const IGNORE_CONFIG_KEYS = ['lastUpdateCheck'];
// async function getPnpParameters(config: Config): Promise<Array<string>> {
// if (await fs.exists(`${config.lockfileFolder}/${constants.PNP_FILENAME}`)) {
// return ['-r', `${config.lockfileFolder}/${constants.PNP_FILENAME}`];
// } else {
// return [];
// }
// }
// let wrappersFolder = null;
// export async function getWrappersFolder(config: Config): Promise<string> {
// if (wrappersFolder) {
// return wrappersFolder;
// }
// wrappersFolder = await fs.makeTempDir();
// await makePortableProxyScript(process.execPath, wrappersFolder, {
// proxyBasename: 'node',
// prependArguments: [...(await getPnpParameters(config))],
// });
// await makePortableProxyScript(process.execPath, wrappersFolder, {
// proxyBasename: 'pika',
// prependArguments: [process.argv[1]],
// });
// return wrappersFolder;
// }
// const INVALID_CHAR_REGEX = /\W/g;
async function makeEnv() {
// stage: string,
// cwd: string,
// config: Config,
const env = _objectSpread2({
NODE: process.execPath,
INIT_CWD: process.cwd()
}, process.env);
return env;
} // // Merge in the `env` object specified in .pikarc
// const customEnv = config.getOption('env');
// if (customEnv && typeof customEnv === 'object') {
// Object.assign(env, customEnv);
// }
// env.npm_lifecycle_event = stage;
// env.npm_node_execpath = env.NODE;
// env.npm_execpath = env.npm_execpath || (process.mainModule && process.mainModule.filename);
// // Set the env to production for npm compat if production mode.
// // https://github.com/npm/npm/blob/30d75e738b9cb7a6a3f9b50e971adcbe63458ed3/lib/utils/lifecycle.js#L336
// if (config.production) {
// env.NODE_ENV = 'production';
// }
// // Note: npm_config_argv environment variable contains output of nopt - command-line
// // parser used by npm. Since we use other parser, we just roughly emulate it's output. (See: #684)
// env.npm_config_argv = JSON.stringify({
// remain: [],
// cooked: config.commandName === 'run' ? [config.commandName, stage] : [config.commandName],
// original: process.argv.slice(2),
// });
// const manifest = await config.maybeReadManifest(cwd);
// if (manifest) {
// if (manifest.scripts && Object.prototype.hasOwnProperty.call(manifest.scripts, stage)) {
// env.npm_lifecycle_script = manifest.scripts[stage];
// }
// // add npm_package_*
// const queue = [['', manifest]];
// while (queue.length) {
// const [key, val] = queue.pop();
// if (typeof val === 'object') {
// for (const subKey in val) {
// const fullKey = [key, subKey].filter(Boolean).join('_');
// if (fullKey && fullKey[0] !== '_' && !IGNORE_MANIFEST_KEYS.has(fullKey)) {
// queue.push([fullKey, val[subKey]]);
// }
// }
// } else {
// let cleanVal = String(val);
// if (cleanVal.indexOf('\n') >= 0) {
// cleanVal = JSON.stringify(cleanVal);
// }
// //replacing invalid chars with underscore
// const cleanKey = key.replace(INVALID_CHAR_REGEX, '_');
// env[`npm_package_${cleanKey}`] = cleanVal;
// }
// }
// }
// // add npm_config_* and npm_package_config_* from pika config
// const keys: Set<string> = new Set([
// ...Object.keys(config.registries.pika.config),
// ...Object.keys(config.registries.npm.config),
// ]);
// const cleaned = Array.from(keys)
// .filter(key => !key.match(/:_/) && IGNORE_CONFIG_KEYS.indexOf(key) === -1)
// .map(key => {
// let val = config.getOption(key);
// if (!val) {
// val = '';
// } else if (typeof val === 'number') {
// val = '' + val;
// } else if (typeof val !== 'string') {
// val = JSON.stringify(val);
// }
// if (val.indexOf('\n') >= 0) {
// val = JSON.stringify(val);
// }
// return [key, val];
// });
// // add npm_config_*
// for (const [key, val] of cleaned) {
// const cleanKey = key.replace(/^_+/, '');
// const envKey = `npm_config_${cleanKey}`.replace(INVALID_CHAR_REGEX, '_');
// env[envKey] = val;
// }
// // add npm_package_config_*
// if (manifest && manifest.name) {
// const packageConfigPrefix = `${manifest.name}:`;
// for (const [key, val] of cleaned) {
// if (key.indexOf(packageConfigPrefix) !== 0) {
// continue;
// }
// const cleanKey = key.replace(/^_+/, '').replace(packageConfigPrefix, '');
// const envKey = `npm_package_config_${cleanKey}`.replace(INVALID_CHAR_REGEX, '_');
// env[envKey] = val;
// }
// }
// // split up the path
// const envPath = env[constants.ENV_PATH_KEY];
// const pathParts = envPath ? envPath.split(path.delimiter) : [];
// // Include the directory that contains node so that we can guarantee that the scripts
// // will always run with the exact same Node release than the one use to run Pika
// const execBin = path.dirname(process.execPath);
// if (pathParts.indexOf(execBin) === -1) {
// pathParts.unshift(execBin);
// }
// // Include node-gyp version that was bundled with the current Node.js version,
// // if available.
// pathParts.unshift(path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'node-gyp-bin'));
// pathParts.unshift(
// path.join(path.dirname(process.execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin'),
// );
// // Include node-gyp version from homebrew managed npm, if available.
// pathParts.unshift(
// path.join(path.dirname(process.execPath), '..', 'libexec', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin'),
// );
// // Add global bin folder if it is not present already, as some packages depend
// // on a globally-installed version of node-gyp.
// const globalBin = await getGlobalBinFolder(config, {});
// if (pathParts.indexOf(globalBin) === -1) {
// pathParts.unshift(globalBin);
// }
// // Add node_modules .bin folders to the PATH
// for (const registry of Object.keys(registries)) {
// const binFolder = path.join(config.registries[registry].folder, '.bin');
// if (config.workspacesEnabled && config.workspaceRootFolder) {
// pathParts.unshift(path.join(config.workspaceRootFolder, binFolder));
// }
// pathParts.unshift(path.join(config.linkFolder, binFolder));
// pathParts.unshift(path.join(cwd, binFolder));
// if (config.modulesFolder) {
// pathParts.unshift(path.join(config.modulesFolder, '.bin'));
// }
// }
// if (await fs.exists(`${config.lockfileFolder}/${constants.PNP_FILENAME}`)) {
// // TODO: Fix. import()? Do we even like that it does this?
// throw new Error("pnp temporarily not supported");
// const pnpApi = {}; //dynamicRequire(`${config.lockfileFolder}/${constants.PNP_FILENAME}`);
// const packageLocator = pnpApi.findPackageLocator(`${config.cwd}/`);
// const packageInformation = pnpApi.getPackageInformation(packageLocator);
// for (const [name, reference] of packageInformation.packageDependencies.entries()) {
// const dependencyInformation = pnpApi.getPackageInformation({name, reference});
// if (!dependencyInformation || !dependencyInformation.packageLocation) {
// continue;
// }
// pathParts.unshift(`${dependencyInformation.packageLocation}/.bin`);
// }
// }
// pathParts.unshift(await getWrappersFolder(config));
// // join path back together
// env[constants.ENV_PATH_KEY] = pathParts.join(path.delimiter);
// return env;
// }
async function executeLifecycleScript({
// config,
cwd,
cmd,
args,
isInteractive,
onProgress,
customShell
}) {
const env = await makeEnv(); // await checkForGypIfNeeded(config, cmd, env[constants.ENV_PATH_KEY].split(path.delimiter));
if (process.platform === 'win32' && (!customShell || customShell === 'cmd')) {
// handle windows run scripts starting with a relative path
cmd = fixCmdWinSlashes(cmd);
} // By default (non-interactive), pipe everything to the terminal and run child process detached
// as long as it's not Windows (since windows does not have /dev/tty)
let stdio = ['ignore', 'pipe', 'pipe'];
let detached = process.platform !== 'win32';
if (isInteractive) {
stdio = 'inherit';
detached = false;
}
const shell = customShell || true;
const stdout = await spawn(cmd, args, {
cwd,
env,
stdio,
detached,
shell
}, onProgress);
return {
cwd,
command: cmd,
stdout
};
}
// // /**
// // * Special case: Some packages depend on node-gyp, but don't specify this in
// // * their package.json dependencies. They assume that node-gyp is available
// // * globally. We need to detect this case and show an error message.
// // */
// function checkForGypIfNeeded(config: Config, cmd: string, paths: Array<string>): Promise<void> {
// if (cmd.substr(0, cmd.indexOf(' ')) !== 'node-gyp') {
// return Promise.resolve();
// }
// // Ensure this only runs once, rather than multiple times in parallel.
// if (!checkGypPromise) {
// checkGypPromise = _checkForGyp(config, paths);
// }
// return checkGypPromise;
// }
// async function _checkForGyp(config: Config, paths: Array<string>): Promise<void> {
// const {reporter} = config;
// // Check every directory in the PATH
// const allChecks = await Promise.all(paths.map(dir => fs.exists(path.join(dir, 'node-gyp'))));
// if (allChecks.some(Boolean)) {
// // node-gyp is available somewhere
// return;
// }
// reporter.info(reporter.lang('packageRequiresNodeGyp'));
// }
// export async function execFromDistributions(config: Config, cwd: string, dist: string, step: string): Promise<void> {
// const pkg = await config.maybeReadManifest(cwd);
// if (!pkg || !pkg.distributions || !pkg.distributions[dist] || typeof pkg.distributions[dist][step] !== 'string') {
// return false;
// }
// const cmd: ?string = pkg.distributions[dist][step];
// await execCommand({stage: 'build', config, cmd, cwd, isInteractive: true});
// return true;
// }
// export async function execFromManifest(config: Config, commandName: string, cwd: string): Promise<void> {
// const pkg = await config.maybeReadManifest(cwd);
// if (!pkg || !pkg.scripts) {
// return;
// }
// const cmd: ?string = pkg.scripts[commandName];
// if (cmd) {
// await execCommand({stage: commandName, config, cmd, cwd, isInteractive: true});
// }
// }
// export async function execCommand({
// stage,
// config,
// cmd,
// cwd,
// isInteractive,
// customShell,
// }: {
// stage: string;
// config: Config;
// cmd: string;
// cwd: string;
// isInteractive: boolean;
// customShell?: string;
// }): Promise<void> {
// const {reporter} = config;
// try {
// reporter.command(cmd);
// await executeLifecycleScript({config, cwd, cmd, isInteractive, customShell});
// return Promise.resolve();
// } catch (err) {
// if (err instanceof ProcessTermError) {
// throw new MessageError(
// err.EXIT_SIGNAL
// ? reporter.lang('commandFailedWithSignal', err.EXIT_SIGNAL)
// : reporter.lang('commandFailedWithCode', err.EXIT_CODE),
// );
// } else {
// throw err;
// }
// }
// }
class Config {
constructor(reporter, cwd, flags) {
this.reporter = reporter; // Ensure the cwd is always an absolute path.
this.cwd = path.resolve(cwd || process.cwd());
this.flags = flags;
}
async loadPackageManifest() {
const loc = path.join(this.cwd, NODE_PACKAGE_JSON);
if (await exists(loc)) {
const info = await this.readJson(loc, readJsonAndFile);
this._manifest = _objectSpread2({}, info.object);
this.manifest = await normalizeManifest(info.object, this.cwd, this, true);
return this.manifest;
} else {
return null;
}
}
readJson(loc, factory = readJson) {
try {
return factory(loc);
} catch (err) {
if (err instanceof SyntaxError) {
throw new types.MessageError(this.reporter.lang('jsonError', loc, err.message));
} else {
throw err;
}
}
}
async getDistributions() {
const raw = this.manifest[`@pika/pack`] || {};
const override = this.flags.pipeline && JSON.parse(this.flags.pipeline);
const cwd = this.cwd;
function cleanRawDistObject(rawVal) {
if (Array.isArray(rawVal)) {
let importStr = rawVal[0].startsWith('./') || rawVal[0].startsWith('../') ? path.join(cwd, rawVal[0]) : rawVal[0];
return [_objectSpread2({}, importFrom(cwd, importStr), {
name: rawVal[0]
}), rawVal[1] || {}];
}
if (typeof rawVal === 'string') {
return [{
build: ({
cwd
}) => {
return executeLifecycleScript({
// config: this,
args: [],
cwd,
cmd: rawVal,
isInteractive: false
});
}
}, {}];
}
if (!rawVal) {
throw new Error('Cannot be false');
}
return false;
}
const pipeline = override || raw.pipeline || [];
return pipeline.map(cleanRawDistObject).filter(Boolean);
}
}
function forwardSignalAndExit(signal) {
forwardSignalToSpawnedProcesses(signal); // We want to exit immediately here since `SIGTERM` means that
// If we lose stdout messages due to abrupt exit, shoot the messenger?
process.exit(1); // eslint-disable-line no-process-exit
}
function handleSignals() {
process.on('SIGTERM', () => {
forwardSignalAndExit('SIGTERM');
});
}
const FALSY_STRINGS = new Set(['0', 'false']);
function boolify(val) {
return !FALSY_STRINGS.has(val.toString().toLowerCase());
}
function boolifyWithDefault(val, defaultResult) {
return val === '' || val === null || val === undefined ? defaultResult : boolify(val);
}
const 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)));
function getVersion() {
const packageJsonContent = fs.readFileSync(path.resolve(currentFilename, '../../package.json'), {
encoding: 'utf-8'
});
const {
version
} = nullify(JSON.parse(stripBOM(packageJsonContent)));
return version;
}
function printHelp() {
console.log(`
${chalk.bold(`@pika/pack`)} - Build npm packages without the mess.
${chalk.bold('Options:')}
--cwd Set the current working directory.
--out Set the output directory. Defaults to "pkg/".
--pipeline Set a build pipeline via JSON string.
--force Continue with the build when a build plugin fails or throws an exception.
--json Log output as JSON.
--verbose Log additional debugging information.
--silent Log almost nothing.
--help Print help.
--version, -v Print version.
`.trim());
}
async function cli(args) {
const version = getVersion();
loudRejection();
handleSignals(); // Handle special flags
if (args.find(arg => arg === '--version' || arg === '-v')) {
console.log(version.trim());
process.exitCode = 0;
return;
}
if (args.find(arg => arg === '--help')) {
printHelp();
process.exitCode = 0;
return;
} // Handle the legacy CLI interface
if (args[2] === 'publish') {
console.log(`The publish flow has moved to the @pika/cli package (included with this package).
Update your publish script to: ${chalk.bold('pika publish [flags]')}
`);
process.exitCode = 1;
return;
}
if (args[2] === 'build') {
console.log(chalk.yellow(`Note: This CLI was recently deprecated. Update your build script to: ${chalk.bold('pika build [flags]')}`));
args.splice(2, 1);
}
const flags = yargs(args);
const cwd = flags.cwd || process.cwd();
const Reporter = flags.json ? JSONReporter : ConsoleReporter;
const reporter = new Reporter({
emoji: true,
verbose: flags.verbose,
isSilent: boolifyWithDefault(process.env.PIKA_SILENT, false) || flags.silent
});
const exit = (exitCode = 0) => {
process.exitCode = exitCode;
reporter.close();
};
const command = buildCommand;
reporter.initPeakMemoryCounter();
const outputWrapperEnabled = boolifyWithDefault(process.env.PIKA_WRAP_OUTPUT, true);
const shouldWrapOutput = outputWrapperEnabled && !flags.json && command.hasWrapper();
if (shouldWrapOutput) {
reporter.header({
name: '@pika/pack',
version
});
}
const run = () => {
invariant(command, 'missing command');
return command.run(config, reporter, flags, args).then(exitCode => {
if (shouldWrapOutput) {
reporter.footer(false);
}
return exitCode;
});
};
function onUnexpectedError(err) {
function indent(str) {
return '\n ' + str.trim().split('\n').join('\n ');
}
const log = [];
log.push(`Arguments: ${indent(process.argv.join(' '))}`);
log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`);
log.push(`Pika version: ${indent(version)}`);
log.push(`Node version: ${indent(process.versions.node)}`);
log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`);
log.push(`Trace: ${indent(err.stack)}`);
reporter.error(reporter.lang('unexpectedError', err.message));
}
const config = new Config(reporter, cwd, flags);
await config.loadPackageManifest();
try {
// option "no-progress" stored in pika config
const noProgressConfig = false; //config.registries.pika.getOption('no-progress');
if (noProgressConfig) {
reporter.disableProgress();
} // verbose logs outputs process.uptime() with this line we can sync uptime to absolute time on the computer
reporter.verbose(`current time: ${new Date().toISOString()}`);
return run().then(exit);
} catch (err) {
reporter.verbose(err.stack);
if (err instanceof types.MessageError) {
reporter.error(err.message);
} else {
onUnexpectedError(err);
}
return exit(1);
}
}
exports.cli = cli;
//# sourceMappingURL=index.js.map
================================================
FILE: checkpoint/dist-src/commands/build.js
================================================
import chalk from 'chalk';
import * as path from 'path';
import { DEFAULT_INDENT } from '../constants.js';
import * as fs from '../util/fs.js';
import { generatePrettyManifest, generatePublishManifest } from '../util/normalize-manifest/for-publish.js';
export function hasWrapper() {
return true;
}
export const examples = null;
export class Build {
constructor(flags, config, reporter) {
this.flags = flags;
this.config = config;
this.reporter = reporter;
this.totalNum = 0;
this.out = path.resolve(config.cwd, flags.out || 'pkg/');
if (this.out === this.config.cwd) {
throw new Error('On publish, you cannot write to cwd because a package.json is created');
}
}
async cleanup() {
const { out } = this;
await fs.unlink(path.join(out, '*'));
}
async init(isFull) {
const { config, out, reporter, flags } = this;
const { cwd } = config;
const outPretty = path.relative(cwd, out) + path.sep;
const manifest = await config.manifest;
const { sourcemap } = manifest['@pika/pack'] || { sourcemap: true };
const distRunners = await config.getDistributions();
const builderConfig = {
out,
cwd,
reporter: {
info: msg => reporter.log(chalk.dim(` » ${msg}`)),
warning: msg => reporter.log(chalk.yellow(` » ${msg}`)),
success: msg => reporter.log(chalk.green(` » ${msg}`)),
created: (filename, entrypoint) => reporter.log(` 📝 ${chalk.green(path.relative(cwd, filename))} ${entrypoint ? chalk.dim(`[${entrypoint}]`) : ''}`),
},
isFull,
manifest,
src: {
loc: path.join(out, 'dist-src'),
entrypoint: path.join(out, 'dist-src', 'index.js'),
// TODO: Deprecated, remove
options: {},
// TODO: Deprecated, remove
files: await (async () => {
const ignoreSet = new Set([]);
ignoreSet.add('**/*/README.md');
const files = await fs.glob(`src/**/*`, {
cwd,
nodir: true,
absolute: true,
ignore: Array.from(ignoreSet).map(g => path.join('src', g)),
});
return files.filter(fileAbs => !fileAbs.endsWith('.d.ts'));
})(),
},
};
const steps = [];
steps.push(async (curr, total) => {
this.reporter.step(curr, total, 'Validating source');
for (const [runner, options] of distRunners) {
if (runner.validate) {
const result = await runner.validate({
...builderConfig,
options: { sourcemap, ...options },
});
if (result instanceof Error) {
throw result;
}
}
}
});
steps.push(async (curr, total) => {
this.reporter.step(curr, total, `Preparing pipeline`);
await this.cleanup();
reporter.log(` ❇️ ${chalk.green(outPretty)}`);
for (const [runner, options] of distRunners) {
await (runner.beforeBuild &&
runner.beforeBuild({
...builderConfig,
options: { sourcemap, ...options },
}));
}
});
if (distRunners.length === 0) {
steps.push(async (curr, total) => {
this.reporter.step(curr, total, `Pipeline is empty! See ${chalk.underline('https://github.com/pikapkg/pack')} for help getting started`);
});
}
for (const [runner, options] of distRunners) {
steps.push(async (curr, total) => {
this.reporter.step(curr, total, `Running ${chalk.bold(runner.name)}`);
// return Promise.resolve(
try {
await (runner.beforeJob &&
runner.beforeJob({
...builderConfig,
options: { sourcemap, ...options },
}));
await (runner.build &&
runner.build({
...builderConfig,
options: { sourcemap, ...options },
}));
await (runner.afterJob &&
runner.afterJob({
...builderConfig,
options: { sourcemap, ...options },
}));
}
catch (err) {
if (flags.force) {
console.log(' ❗️ ', chalk.red(err.message), chalk.dim('--force, continuing...'));
}
else {
throw err;
}
}
// ).catch(err => {
// log(chalk.red(err.message));
// reporter.log(
// reporter.lang("distFailed", runner.name, err.code, err.message),
// { force: true }
// );
// if (err.forceExit === true) {
// reporter.log(reporter.lang("distExiting"));
// throw err;
// return;
// }
// reporter.log(reporter.lang("distContinuing"));
// });
});
}
steps.push(async (curr, total) => {
this.reporter.step(curr, total, `Finalizing package`);
for (const [runner, options] of distRunners) {
await (runner.afterBuild &&
runner.afterBuild({
...builderConfig,
options: { sourcemap, ...options },
}));
}
if (await fs.exists(path.join(cwd, 'CHANGELOG'))) {
fs.copyFile(path.join(cwd, 'CHANGELOG'), path.join(out, 'CHANGELOG'));
reporter.log(chalk.dim(` » copying CHANGELOG...`));
}
else if (await fs.exists(path.join(cwd, 'CHANGELOG.md'))) {
fs.copyFile(path.join(cwd, 'CHANGELOG.md'), path.join(out, 'CHANGELOG.md'));
reporter.log(chalk.dim(` » copying CHANGELOG.md...`));
}
if (await fs.exists(path.join(cwd, 'LICENSE'))) {
fs.copyFile(path.join(cwd, 'LICENSE'), path.join(out, 'LICENSE'));
reporter.log(chalk.dim(` » copying LICENSE...`));
}
else if (await fs.exists(path.join(cwd, 'LICENSE.md'))) {
fs.copyFile(path.join(cwd, 'LICENSE.md'), path.join(out, 'LICENSE.md'));
reporter.log(chalk.dim(` » copying LICENSE.md...`));
}
if (await fs.exists(path.join(cwd, 'README'))) {
fs.copyFile(path.join(cwd, 'README'), path.join(out, 'README'));
reporter.log(chalk.dim(` » copying README...`));
}
else if (await fs.exists(path.join(cwd, 'README.md'))) {
fs.copyFile(path.join(cwd, 'README.md'), path.join(out, 'README.md'));
reporter.log(chalk.dim(` » copying README.md...`));
}
const publishManifest = await generatePublishManifest(config._manifest, config, distRunners);
if (out === cwd) {
reporter.log(`NEW MANIFEST:\n\n`);
reporter.log(generatePrettyManifest(publishManifest));
reporter.log(`\n\n`);
}
else {
await fs.writeFilePreservingEol(path.join(out, 'package.json'), JSON.stringify(publishManifest, null, DEFAULT_INDENT) + '\n');
reporter.log(` 📝 ` + chalk.green(outPretty + 'package.json'));
}
reporter.log(` 📦 ` + chalk.green(outPretty));
});
let currentStep = 0;
for (const step of steps) {
await step(++currentStep, steps.length);
}
}
}
export async function run(config, reporter, flags, args) {
const isProduction = flags.publish;
const builder = new Build(flags, config, reporter);
await builder.init(isProduction);
}
================================================
FILE: checkpoint/dist-src/config.js
================================================
import * as path from 'path';
import * as constants from './constants.js';
import { MessageError } from '@pika/types';
import * as fs from './util/fs.js';
import normalizeManifest from './util/normalize-manifest/index.js';
import executeLifecycleScript from './util/execute-lifecycle-script.js';
import importFrom from 'import-from';
;
;
export default class Config {
constructor(reporter, cwd, flags) {
this.reporter = reporter;
// Ensure the cwd is always an absolute path.
this.cwd = path.resolve(cwd || process.cwd());
this.flags = flags;
}
async loadPackageManifest() {
const loc = path.join(this.cwd, constants.NODE_PACKAGE_JSON);
if (await fs.exists(loc)) {
const info = await this.readJson(loc, fs.readJsonAndFile);
this._manifest = { ...info.object };
this.manifest = await normalizeManifest(info.object, this.cwd, this, true);
return this.manifest;
}
else {
return null;
}
}
readJson(loc, factory = fs.readJson) {
try {
return factory(loc);
}
catch (err) {
if (err instanceof SyntaxError) {
throw new MessageError(this.reporter.lang('jsonError', loc, err.message));
}
else {
throw err;
}
}
}
async getDistributions() {
const raw = this.manifest[`@pika/pack`] || {};
const override = this.flags.pipeline && JSON.parse(this.flags.pipeline);
const cwd = this.cwd;
function cleanRawDistObject(rawVal) {
if (Array.isArray(rawVal)) {
let importStr = (rawVal[0].startsWith('./') || rawVal[0].startsWith('../')) ? path.join(cwd, rawVal[0]) : rawVal[0];
return [{ ...importFrom(cwd, importStr), name: rawVal[0] }, rawVal[1] || {}];
}
if (typeof rawVal === 'string') {
return [{ build: ({ cwd }) => {
return executeLifecycleScript({
// config: this,
args: [],
cwd,
cmd: rawVal,
isInteractive: false
});
} }, {}];
}
if (!rawVal) {
throw new Error('Cannot be false');
}
return false;
}
const pipeline = override || raw.pipeline || [];
return pipeline.map(cleanRawDistObject).filter(Boolean);
}
}
================================================
FILE: checkpoint/dist-src/constants.js
================================================
// import os from 'os';
// import * as path from 'path';
// import userHome from './util/user-home-dir.js';
// import {getCacheDir, getConfigDir, getDataDir} from './util/user-dirs.js';
export const DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDependencies'];
// export const OWNED_DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDependencies'];
export const RESOLUTIONS = 'resolutions';
export const MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES];
export const SUPPORTED_NODE_VERSIONS = '>=8.5.0';
// export const PIKA_REGISTRY = 'https://registry.npmjs.org';
// export const NPM_REGISTRY_RE = /https?:\/\/registry\.npmjs\.org/g;
// export const PIKA_DOCS = 'https://yarnpkg.com/en/docs/cli/';
// export const PIKA_INSTALLER_SH = 'https://yarnpkg.com/install.sh';
// export const PIKA_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi';
// export const SELF_UPDATE_VERSION_URL = 'https://www.pikapkg.com/downloads/latest-version';
// // cache version, bump whenever we make backwards incompatible changes
// export const CACHE_VERSION = 3;
// // lockfile version, bump whenever we make backwards incompatible changes
// export const LOCKFILE_VERSION = 1;
// // max amount of network requests to perform concurrently
// export const NETWORK_CONCURRENCY = 8;
// // HTTP timeout used when downloading packages
// export const NETWORK_TIMEOUT = 30 * 1000; // in milliseconds
// // max amount of child processes to execute concurrently
export const CHILD_CONCURRENCY = 5;
// export const REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid'];
// function getPreferredCacheDirectories(): Array<string> {
// const preferredCacheDirectories = [getCacheDir()];
// if (process.getuid) {
// // $FlowFixMe: process.getuid exists, dammit
// preferredCacheDirectories.push(path.join(os.tmpdir(), `.pika-cache-${process.getuid()}`));
// }
// preferredCacheDirectories.push(path.join(os.tmpdir(), `.pika-cache`));
// return preferredCacheDirectories;
// }
// export const PREFERRED_MODULE_CACHE_DIRECTORIES = getPreferredCacheDirectories();
// export const CONFIG_DIRECTORY = getConfigDir();
// export const DATA_DIRECTORY = getDataDir();
// export const LINK_REGISTRY_DIRECTORY = path.join(DATA_DIRECTORY, 'link');
// export const GLOBAL_MODULE_DIRECTORY = path.join(DATA_DIRECTORY, 'global');
// export const NODE_BIN_PATH = process.execPath;
export const NODE_MODULES_FOLDER = 'node_modules';
export const NODE_PACKAGE_JSON = 'package.json';
// export const PNP_FILENAME = '.pnp';
// export const POSIX_GLOBAL_PREFIX = `${process.env.DESTDIR || ''}/usr/local`;
// export const FALLBACK_GLOBAL_PREFIX = path.join(userHome, '.pika');
// export const META_FOLDER = '.pika-meta';
// export const INTEGRITY_FILENAME = '.pika-integrity';
// export const LOCKFILE_FILENAME = 'pika.lock';
// export const LEGACY_LOCKFILE_FILENAME = 'yarn.lock';
// export const METADATA_FILENAME = '.pika-metadata.json';
// export const TARBALL_FILENAME = '.pika-tarball.tgz';
// export const CLEAN_FILENAME = '.pikaclean';
// export const NPM_LOCK_FILENAME = 'package-lock.json';
// export const NPM_SHRINKWRAP_FILENAME = 'npm-shrinkwrap.json';
export const DEFAULT_INDENT = ' ';
// export const SINGLE_INSTANCE_PORT = 31997;
// export const SINGLE_INSTANCE_FILENAME = '.pika-single-instance';
export const ENV_PATH_KEY = getPathKey(process.platform, process.env);
export function getPathKey(platform, env) {
let pathKey = 'PATH';
// windows calls its path "Path" usually, but this is not guaranteed.
if (platform === 'win32') {
pathKey = 'Path';
for (const key in env) {
if (key.toLowerCase() === 'path') {
pathKey = key;
}
}
}
return pathKey;
}
// export const VERSION_COLOR_SCHEME: {[key: string]: VersionColor} = {
// major: 'red',
// premajor: 'red',
// minor: 'yellow',
// preminor: 'yellow',
// patch: 'green',
// prepatch: 'green',
// prerelease: 'red',
// unchanged: 'white',
// unknown: 'red',
// };
// export type VersionColor = 'red' | 'yellow' | 'green' | 'white';
// export type RequestHint = 'dev' | 'optional' | 'resolution' | 'workspaces';
================================================
FILE: checkpoint/dist-src/errors.js
================================================
import { MessageError } from '@pika/types';
export class ProcessSpawnError extends MessageError {
constructor(msg, code, process) {
super(msg);
this.code = code;
this.process = process;
}
}
export class SecurityError extends MessageError {
}
export class ProcessTermError extends MessageError {
}
export class ResponseError extends Error {
constructor(msg, responseCode) {
super(msg);
this.responseCode = responseCode;
}
}
export class OneTimePasswordError extends Error {
}
================================================
FILE: checkpoint/dist-src/index.js
================================================
import * as path from 'path';
import chalk from 'chalk';
import * as fs from 'fs';
import invariant from 'invariant';
import loudRejection from 'loud-rejection';
import { ConsoleReporter, JSONReporter } from './reporters/index.js';
import * as buildCommand from './commands/build.js';
import { MessageError } from '@pika/types';
import Config from './config.js';
import handleSignals from './util/signal-handler.js';
import { boolifyWithDefault } from './util/conversion.js';
import map from './util/map.js';
import stripBOM from 'strip-bom';
import uri2path from 'file-uri-to-path';
import yargs from 'yargs-parser';
// @ts-ignore
const currentFilename = uri2path(import.meta.url);
function getVersion() {
const packageJsonContent = fs.readFileSync(path.resolve(currentFilename, '../../package.json'), { encoding: 'utf-8' });
const { version } = map(JSON.parse(stripBOM(packageJsonContent)));
return version;
}
function printHelp() {
console.log(`
${chalk.bold(`@pika/pack`)} - Build npm packages without the mess.
${chalk.bold('Options:')}
--cwd Set the current working directory.
--out Set the output directory. Defaults to "pkg/".
--pipeline Set a build pipeline via JSON string.
--force Continue with the build when a build plugin fails or throws an exception.
--json Log output as JSON.
--verbose Log additional debugging information.
--silent Log almost nothing.
--help Print help.
--version, -v Print version.
`.trim());
}
export async function cli(args) {
const version = getVersion();
loudRejection();
handleSignals();
// Handle special flags
if (args.find(arg => arg === '--version' || arg === '-v')) {
console.log(version.trim());
process.exitCode = 0;
return;
}
if (args.find(arg => arg === '--help')) {
printHelp();
process.exitCode = 0;
return;
}
// Handle the legacy CLI interface
if (args[2] === 'publish') {
console.log(`The publish flow has moved to the @pika/cli package (included with this package).
Update your publish script to: ${chalk.bold('pika publish [flags]')}
`);
process.exitCode = 1;
return;
}
if (args[2] === 'build') {
console.log(chalk.yellow(`Note: This CLI was recently deprecated. Update your build script to: ${chalk.bold('pika build [flags]')}`));
args.splice(2, 1);
}
const flags = yargs(args);
const cwd = flags.cwd || process.cwd();
const Reporter = flags.json ? JSONReporter : ConsoleReporter;
const reporter = new Reporter({
emoji: true,
verbose: flags.verbose,
isSilent: boolifyWithDefault(process.env.PIKA_SILENT, false) || flags.silent,
});
const exit = (exitCode = 0) => {
process.exitCode = exitCode;
reporter.close();
};
const command = buildCommand;
reporter.initPeakMemoryCounter();
const outputWrapperEnabled = boolifyWithDefault(process.env.PIKA_WRAP_OUTPUT, true);
const shouldWrapOutput = outputWrapperEnabled && !flags.json && command.hasWrapper();
if (shouldWrapOutput) {
reporter.header({ name: '@pika/pack', version });
}
const run = () => {
invariant(command, 'missing command');
return command.run(config, reporter, flags, args).then(exitCode => {
if (shouldWrapOutput) {
reporter.footer(false);
}
return exitCode;
});
};
function onUnexpectedError(err) {
function indent(str) {
return '\n ' + str.trim().split('\n').join('\n ');
}
const log = [];
log.push(`Arguments: ${indent(process.argv.join(' '))}`);
log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`);
log.push(`Pika version: ${indent(version)}`);
log.push(`Node version: ${indent(process.versions.node)}`);
log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`);
log.push(`Trace: ${indent(err.stack)}`);
reporter.error(reporter.lang('unexpectedError', err.message));
}
const config = new Config(reporter, cwd, flags);
await config.loadPackageManifest();
try {
// option "no-progress" stored in pika config
const noProgressConfig = false; //config.registries.pika.getOption('no-progress');
if (noProgressConfig) {
reporter.disableProgress();
}
// verbose logs outputs process.uptime() with this line we can sync uptime to absolute time on the computer
reporter.verbose(`current time: ${new Date().toISOString()}`);
return run().then(exit);
}
catch (err) {
reporter.verbose(err.stack);
if (err instanceof MessageError) {
reporter.error(err.message);
}
else {
onUnexpectedError(err);
}
return exit(1);
}
}
================================================
FILE: checkpoint/dist-src/reporters/base-reporter.js
================================================
import { defaultFormatter } from './format.js';
import * as languages from './lang/index.js';
import * as isCI from 'is-ci';
import * as os from 'os';
import * as util from 'util';
import { EventEmitter } from 'events';
export function stringifyLangArgs(args) {
return args.map(function (val) {
if (val != null && val.inspect) {
return val.inspect();
}
else {
try {
const str = JSON.stringify(val) || val + '';
// should match all literal line breaks and
// "u001b" that follow an odd number of backslashes and convert them to ESC
// we do this because the JSON.stringify process has escaped these characters
return str
.replace(/((?:^|[^\\])(?:\\{2})*)\\u001[bB]/g, '$1\u001b')
.replace(/[\\]r[\\]n|([\\])?[\\]n/g, (match, precededBacklash) => {
// precededBacklash not null when "\n" is preceded by a backlash ("\\n")
// match will be "\\n" and we don't replace it with os.EOL
return precededBacklash ? match : os.EOL;
});
}
catch (e) {
return util.inspect(val);
}
}
});
}
export default class BaseReporter {
constructor(opts = {}) {
const lang = 'en';
this.language = lang;
this.stdout = opts.stdout || process.stdout;
this.stderr = opts.stderr || process.stderr;
this.stdin = opts.stdin || this._getStandardInput();
this.emoji = !!opts.emoji;
this.nonInteractive = !!opts.nonInteractive;
this.noProgress = !!opts.noProgress || isCI;
this.isVerbose = !!opts.verbose;
// @ts-ignore
this.isTTY = this.stdout.isTTY;
this.peakMemory = 0;
this.startTime = Date.now();
this.format = defaultFormatter;
}
lang(key, ...args) {
const msg = languages[this.language][key] || languages.en[key];
if (!msg) {
throw new ReferenceError(`No message defined for language key ${key}`);
}
// stringify args
const stringifiedArgs = stringifyLangArgs(args);
// replace $0 placeholders with args
return msg.replace(/\$(\d+)/g, (str, i) => {
return stringifiedArgs[i];
});
}
/**
* `stringifyLangArgs` run `JSON.stringify` on strings too causing
* them to appear quoted. This marks them as "raw" and prevents
* the quoting and escaping
*/
rawText(str) {
return {
inspect() {
return str;
},
};
}
verbose(msg) {
if (this.isVerbose) {
this._verbose(msg);
}
}
verboseInspect(val) {
if (this.isVerbose) {
this._verboseInspect(val);
}
}
_verbose(msg) { }
_verboseInspect(val) { }
_getStandardInput() {
let standardInput;
// Accessing stdin in a win32 headless process (e.g., Visual Studio) may throw an exception.
try {
standardInput = process.stdin;
}
catch (e) {
console.warn(e.message);
delete process.stdin;
// @ts-ignore
process.stdin = new EventEmitter();
standardInput = process.stdin;
}
return standardInput;
}
initPeakMemoryCounter() {
this.checkPeakMemory();
this.peakMemoryInterval = setInterval(() => {
this.checkPeakMemory();
}, 1000);
// $FlowFixMe: Node's setInterval returns a Timeout, not a Number
this.peakMemoryInterval.unref();
}
checkPeakMemory() {
const { heapTotal } = process.memoryUsage();
if (heapTotal > this.peakMemory) {
this.peakMemory = heapTotal;
}
}
close() {
if (this.peakMemoryInterval) {
clearInterval(this.peakMemoryInterval);
this.peakMemoryInterval = null;
}
}
getTotalTime() {
return Date.now() - this.startTime;
}
// TODO
list(key, items, hints) { }
// Outputs basic tree structure to console
tree(key, obj, { force = false } = {}) { }
// called whenever we begin a step in the CLI.
step(current, total, message, emoji) { }
// a error message has been triggered. this however does not always meant an abrupt
// program end.
error(message) { }
// an info message has been triggered. this provides things like stats and diagnostics.
info(message) { }
// a warning message has been triggered.
warn(message) { }
// a success message has been triggered.
success(message) { }
// a simple log message
// TODO: rethink the {force} parameter. In the meantime, please don't use it (cf comments in #4143).
log(message, { force = false } = {}) { }
// a shell command has been executed
command(command) { }
// inspect and pretty-print any value
inspect(value) { }
// the screen shown at the very start of the CLI
header(pkg) { }
// the screen shown at the very end of the CLI
footer(showPeakMemory) { }
// a table structure
table(head, body) { }
// render an activity spinner and return a function that will trigger an update
activity() {
return {
tick(name) { },
end() { },
};
}
//
activitySet(total, workers) {
return {
spinners: Array(workers).fill({
clear() { },
setPrefix() { },
tick() { },
end() { },
}),
end() { },
};
}
// render a progress bar and return a function which when called will trigger an update
progress(total) {
return function () { };
}
// utility function to disable progress bar
disableProgress() {
this.noProgress = true;
}
}
================================================
FILE: checkpoint/dist-src/reporters/console/console-reporter.js
================================================
import chalk from 'chalk';
import * as readline from 'readline';
import stripAnsi from 'strip-ansi';
import { inspect } from 'util';
import { removeSuffix } from '../../util/misc.js';
import BaseReporter from '../base-reporter.js';
import { getFormattedOutput, recurseTree, sortTrees } from './helpers/tree-helper.js';
import Progress from './progress-bar.js';
import Spinner from './spinner-progress.js';
import { clearLine } from './util.js';
const AUDIT_COL_WIDTHS = [15, 62];
const auditSeverityColors = {
info: chalk.bold,
low: chalk.bold,
moderate: chalk.yellow,
high: chalk.red,
critical: chalk.bgRed,
};
// fixes bold on windows
if (process.platform === 'win32' && !(process.env.TERM && /^xterm/i.test(process.env.TERM))) {
// @ts-ignore
chalk.bold._styles[0].close += '\u001b[m';
}
export default class ConsoleReporter extends BaseReporter {
constructor(opts) {
super(opts);
this._lastCategorySize = 0;
this._spinners = new Set();
this.format = chalk;
this.format.stripColor = stripAnsi;
this.isSilent = !!opts.isSilent;
}
_prependEmoji(msg, emoji) {
if (this.emoji && emoji && this.isTTY) {
msg = `${emoji} ${msg}`;
}
return msg;
}
_logCategory(category, color, msg) {
this._lastCategorySize = category.length;
this._log(`${this.format[color](category)} ${msg}`);
}
_verbose(msg) {
this._logCategory('verbose', 'grey', `${process.uptime()} ${msg}`);
}
_verboseInspect(obj) {
this.inspect(obj);
}
close() {
for (const spinner of this._spinners) {
spinner.stop();
}
this._spinners.clear();
this.stopProgress();
super.close();
}
table(head, body) {
//
head = head.map((field) => this.format.underline(field));
//
const rows = [head].concat(body);
// get column widths
const cols = [];
for (let i = 0; i < head.length; i++) {
const widths = rows.map((row) => this.format.stripColor(row[i]).length);
cols[i] = Math.max(...widths);
}
//
const builtRows = rows.map((row) => {
for (let i = 0; i < row.length; i++) {
const field = row[i];
const padding = cols[i] - this.format.stripColor(field).length;
row[i] = field + ' '.repeat(padding);
}
return row.join(' ');
});
this.log(builtRows.join('\n'));
}
step(current, total, msg, emoji) {
msg = this._prependEmoji(msg, emoji);
if (msg.endsWith('?')) {
msg = `${removeSuffix(msg, '?')}...?`;
}
else {
msg += '...';
}
this.log(`${this.format.dim(`[${current}/${total}]`)} ${msg}`);
}
inspect(value) {
if (typeof value !== 'number' && typeof value !== 'string') {
value = inspect(value, {
breakLength: 0,
colors: this.isTTY,
depth: null,
maxArrayLength: null,
});
}
this.log(String(value), { force: true });
}
list(key, items, hints) {
const gutterWidth = (this._lastCategorySize || 2) - 1;
if (hints) {
for (const item of items) {
this._log(`${' '.repeat(gutterWidth)}- ${this.format.bold(item)}`);
this._log(` ${' '.repeat(gutterWidth)} ${hints[item]}`);
}
}
else {
for (const item of items) {
this._log(`${' '.repeat(gutterWidth)}- ${item}`);
}
}
}
header(pkg) {
this.log(this.format.bold(`${pkg.name} v${pkg.version}`));
}
footer(showPeakMemory) {
this.stopProgress();
const totalTime = (this.getTotalTime() / 1000).toFixed(2);
let msg = `Done in ${totalTime}s.`;
if (showPeakMemory) {
const peakMemory = (this.peakMemory / 1024 / 1024).toFixed(2);
msg += ` Peak memory usage ${peakMemory}MB.`;
}
this.log(this._prependEmoji(msg, '✨'));
}
log(msg, { force = false } = {}) {
this._lastCategorySize = 0;
this._log(msg, { force });
}
_log(msg, { force = false } = {}) {
if (this.isSilent && !force) {
return;
}
clearLine(this.stdout);
this.stdout.write(`${msg}\n`);
}
success(msg) {
this._logCategory('success', 'green', msg);
}
error(msg) {
clearLine(this.stderr);
this.stderr.write(`${this.format.red('error')} ${msg}\n`);
}
info(msg) {
this._logCategory('info', 'blue', msg);
}
command(command) {
this.log(this.format.dim(`$ ${command}`));
}
warn(msg) {
clearLine(this.stderr);
this.stderr.write(`${this.format.yellow('warning')} ${msg}\n`);
}
// handles basic tree output to console
tree(key, trees, { force = false } = {}) {
this.stopProgress();
//
if (this.isSilent && !force) {
return;
}
const output = ({ name, children, hint, color }, titlePrefix, childrenPrefix) => {
const formatter = this.format;
const out = getFormattedOutput({
prefix: titlePrefix,
hint,
color,
name,
formatter,
});
this.stdout.write(out);
if (children && children.length) {
recurseTree(sortTrees(children), childrenPrefix, output);
}
};
recurseTree(sortTrees(trees), '', output);
}
activitySet(total, workers) {
if (!this.isTTY || this.noProgress) {
return super.activitySet(total, workers);
}
const spinners = [];
const reporterSpinners = this._spinners;
for (let i = 1; i < workers; i++) {
this.log('');
}
for (let i = 0; i < workers; i++) {
const spinner = new Spinner(this.stderr, i);
reporterSpinners.add(spinner);
spinner.start();
let prefix = null;
let current = 0;
const updatePrefix = () => {
spinner.setPrefix(`${this.format.dim(`[${current === 0 ? '-' : current}/${total}]`)} `);
};
const clear = () => {
prefix = null;
current = 0;
gitextract_c_u851k3/ ├── .babelrc ├── .github/ │ └── ISSUE_TEMPLATE.md ├── .gitignore ├── .prettierrc ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── checkpoint/ │ ├── LICENSE │ ├── README.md │ ├── dist-node/ │ │ ├── index.bin.js │ │ └── index.js │ ├── dist-src/ │ │ ├── commands/ │ │ │ └── build.js │ │ ├── config.js │ │ ├── constants.js │ │ ├── errors.js │ │ ├── index.js │ │ ├── reporters/ │ │ │ ├── base-reporter.js │ │ │ ├── console/ │ │ │ │ ├── console-reporter.js │ │ │ │ ├── helpers/ │ │ │ │ │ └── tree-helper.js │ │ │ │ ├── progress-bar.js │ │ │ │ ├── spinner-progress.js │ │ │ │ └── util.js │ │ │ ├── format.js │ │ │ ├── index.js │ │ │ ├── json-reporter.js │ │ │ ├── lang/ │ │ │ │ ├── en.js │ │ │ │ └── index.js │ │ │ ├── noop-reporter.js │ │ │ └── types.js │ │ ├── types.js │ │ └── util/ │ │ ├── babel-plugin-import-rewrite.js │ │ ├── babel-validate-specifier.js │ │ ├── blocking-queue.js │ │ ├── child.js │ │ ├── conversion.js │ │ ├── execute-lifecycle-script.js │ │ ├── fix-cmd-win-slashes.js │ │ ├── fs-normalized.js │ │ ├── fs.js │ │ ├── map.js │ │ ├── misc.js │ │ ├── normalize-manifest/ │ │ │ ├── fix.js │ │ │ ├── for-publish.js │ │ │ ├── index.js │ │ │ ├── infer-license.js │ │ │ ├── licenses.js │ │ │ ├── typos.js │ │ │ ├── util.js │ │ │ └── validate.js │ │ ├── promise.js │ │ └── signal-handler.js │ ├── dist-types/ │ │ ├── commands/ │ │ │ └── build.d.ts │ │ ├── config.d.ts │ │ ├── constants.d.ts │ │ ├── errors.d.ts │ │ ├── index.d.ts │ │ ├── reporters/ │ │ │ ├── base-reporter.d.ts │ │ │ ├── console/ │ │ │ │ ├── console-reporter.d.ts │ │ │ │ ├── helpers/ │ │ │ │ │ └── tree-helper.d.ts │ │ │ │ ├── progress-bar.d.ts │ │ │ │ ├── spinner-progress.d.ts │ │ │ │ └── util.d.ts │ │ │ ├── format.d.ts │ │ │ ├── index.d.ts │ │ │ ├── json-reporter.d.ts │ │ │ ├── lang/ │ │ │ │ ├── en.d.ts │ │ │ │ └── index.d.ts │ │ │ ├── noop-reporter.d.ts │ │ │ └── types.d.ts │ │ ├── types.d.ts │ │ └── util/ │ │ ├── babel-plugin-import-rewrite.d.ts │ │ ├── babel-validate-specifier.d.ts │ │ ├── blocking-queue.d.ts │ │ ├── child.d.ts │ │ ├── conversion.d.ts │ │ ├── execute-lifecycle-script.d.ts │ │ ├── fix-cmd-win-slashes.d.ts │ │ ├── fs-normalized.d.ts │ │ ├── fs.d.ts │ │ ├── map.d.ts │ │ ├── misc.d.ts │ │ ├── normalize-manifest/ │ │ │ ├── fix.d.ts │ │ │ ├── for-publish.d.ts │ │ │ ├── index.d.ts │ │ │ ├── infer-license.d.ts │ │ │ ├── licenses.d.ts │ │ │ ├── typos.d.ts │ │ │ ├── util.d.ts │ │ │ └── validate.d.ts │ │ ├── promise.d.ts │ │ └── signal-handler.d.ts │ └── package.json ├── package.json ├── src/ │ ├── commands/ │ │ └── build.ts │ ├── config.ts │ ├── constants.ts │ ├── errors.ts │ ├── index.ts │ ├── reporters/ │ │ ├── base-reporter.ts │ │ ├── console/ │ │ │ ├── console-reporter.ts │ │ │ ├── helpers/ │ │ │ │ └── tree-helper.ts │ │ │ ├── progress-bar.ts │ │ │ ├── spinner-progress.ts │ │ │ └── util.ts │ │ ├── format.ts │ │ ├── index.ts │ │ ├── json-reporter.ts │ │ ├── lang/ │ │ │ ├── en.ts │ │ │ └── index.ts │ │ ├── noop-reporter.ts │ │ └── types.ts │ ├── types.ts │ └── util/ │ ├── babel-plugin-import-rewrite.ts │ ├── babel-validate-specifier.ts │ ├── blocking-queue.ts │ ├── child.ts │ ├── conversion.ts │ ├── execute-lifecycle-script.ts │ ├── fix-cmd-win-slashes.ts │ ├── fs-normalized.ts │ ├── fs.ts │ ├── map.ts │ ├── misc.ts │ ├── normalize-manifest/ │ │ ├── fix.ts │ │ ├── for-publish.ts │ │ ├── index.ts │ │ ├── infer-license.ts │ │ ├── licenses.ts │ │ ├── typos.ts │ │ ├── util.ts │ │ └── validate.ts │ ├── promise.ts │ └── signal-handler.ts └── tsconfig.json
SYMBOL INDEX (682 symbols across 88 files)
FILE: checkpoint/dist-node/index.js
function _interopDefault (line 5) | function _interopDefault (ex) { return (ex && (typeof ex === 'object') &...
function removeSuffix (line 35) | function removeSuffix(pattern, suffix) {
function formatFunction (line 43) | function formatFunction(...strs) {
function stringifyLangArgs (line 425) | function stringifyLangArgs(args) {
class BaseReporter (line 446) | class BaseReporter {
method constructor (line 447) | constructor(opts = {}) {
method lang (line 464) | lang(key, ...args) {
method rawText (line 485) | rawText(str) {
method verbose (line 494) | verbose(msg) {
method verboseInspect (line 500) | verboseInspect(val) {
method _verbose (line 506) | _verbose(msg) {}
method _verboseInspect (line 508) | _verboseInspect(val) {}
method _getStandardInput (line 510) | _getStandardInput() {
method initPeakMemoryCounter (line 526) | initPeakMemoryCounter() {
method checkPeakMemory (line 535) | checkPeakMemory() {
method close (line 545) | close() {
method getTotalTime (line 552) | getTotalTime() {
method list (line 557) | list(key, items, hints) {}
method tree (line 560) | tree(key, obj, {
method step (line 565) | step(current, total, message, emoji) {}
method error (line 569) | error(message) {}
method info (line 572) | info(message) {}
method warn (line 575) | warn(message) {}
method success (line 578) | success(message) {}
method log (line 582) | log(message, {
method command (line 587) | command(command) {}
method inspect (line 590) | inspect(value) {}
method header (line 593) | header(pkg) {}
method footer (line 596) | footer(showPeakMemory) {}
method table (line 599) | table(head, body) {}
method activity (line 602) | activity() {
method activitySet (line 612) | activitySet(total, workers) {
method progress (line 631) | progress(total) {
method disableProgress (line 636) | disableProgress() {
function sortTrees (line 643) | function sortTrees(trees) {
function recurseTree (line 648) | function recurseTree(tree, prefix, recurseFunc) {
function getFormattedOutput (line 657) | function getFormattedOutput(fmt) {
function getNextIndentChar (line 663) | function getNextIndentChar(end) {
function getLastIndentChar (line 667) | function getLastIndentChar(end) {
function getSuffix (line 671) | function getSuffix(hint, formatter) {
function formatColor (line 675) | function formatColor(color, strToFormat, formatter) {
constant CLEAR_WHOLE_LINE (line 679) | const CLEAR_WHOLE_LINE = 0;
constant CLEAR_RIGHT_OF_CURSOR (line 680) | const CLEAR_RIGHT_OF_CURSOR = 1;
function clearLine (line 681) | function clearLine(stdout) {
function toStartOfLine (line 697) | function toStartOfLine(stdout) {
function writeOnNthLine (line 705) | function writeOnNthLine(stdout, n, msg) {
function clearNthLine (line 724) | function clearNthLine(stdout, n) {
class ProgressBar (line 740) | class ProgressBar {
method constructor (line 741) | constructor(total, stdout = process.stderr, callback) {
method tick (line 751) | tick() {
method cancelTick (line 763) | cancelTick() {
method stop (line 770) | stop() {
method render (line 781) | render() {
class Spinner (line 804) | class Spinner {
method constructor (line 805) | constructor(stdout = process.stderr, lineNumber = 0) {
method setPrefix (line 816) | setPrefix(prefix) {
method setText (line 820) | setText(text) {
method start (line 824) | start() {
method render (line 829) | render() {
method stop (line 844) | stop() {
class ConsoleReporter (line 869) | class ConsoleReporter extends BaseReporter {
method constructor (line 870) | constructor(opts) {
method _prependEmoji (line 879) | _prependEmoji(msg, emoji) {
method _logCategory (line 887) | _logCategory(category, color, msg) {
method _verbose (line 893) | _verbose(msg) {
method _verboseInspect (line 897) | _verboseInspect(obj) {
method close (line 901) | close() {
method table (line 912) | table(head, body) {
method step (line 938) | step(current, total, msg, emoji) {
method inspect (line 950) | inspect(value) {
method list (line 965) | list(key, items, hints) {
method header (line 981) | header(pkg) {
method footer (line 985) | footer(showPeakMemory) {
method log (line 998) | log(msg, {
method _log (line 1008) | _log(msg, {
method success (line 1019) | success(msg) {
method error (line 1023) | error(msg) {
method info (line 1028) | info(msg) {
method command (line 1032) | command(command) {
method warn (line 1036) | warn(msg) {
method tree (line 1042) | tree(key, trees, {
method activitySet (line 1075) | activitySet(total, workers) {
method activity (line 1144) | activity() {
method progress (line 1171) | progress(count) {
method stopProgress (line 1195) | stopProgress() {
function _defineProperty (line 1203) | function _defineProperty(obj, key, value) {
function ownKeys (line 1218) | function ownKeys(object, enumerableOnly) {
function _objectSpread2 (line 1232) | function _objectSpread2(target) {
class JSONReporter (line 1252) | class JSONReporter extends BaseReporter {
method constructor (line 1253) | constructor(opts) {
method _dump (line 1259) | _dump(type, data, error) {
method _verbose (line 1272) | _verbose(msg) {
method list (line 1276) | list(type, items, hints) {
method tree (line 1284) | tree(type, trees) {
method step (line 1291) | step(current, total, message) {
method inspect (line 1299) | inspect(value) {
method footer (line 1303) | footer(showPeakMemory) {
method log (line 1307) | log(msg) {
method command (line 1311) | command(msg) {
method table (line 1315) | table(head, body) {
method success (line 1322) | success(msg) {
method error (line 1326) | error(msg) {
method warn (line 1330) | warn(msg) {
method info (line 1334) | info(msg) {
method activitySet (line 1338) | activitySet(total, workers) {
method activity (line 1389) | activity() {
method _activity (line 1393) | _activity(data) {
method progress (line 1424) | progress(total) {
constant DEPENDENCY_TYPES (line 1460) | const DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDepe...
constant RESOLUTIONS (line 1462) | const RESOLUTIONS = 'resolutions';
constant MANIFEST_FIELDS (line 1463) | const MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES];
constant CHILD_CONCURRENCY (line 1479) | const CHILD_CONCURRENCY = 5;
constant NODE_PACKAGE_JSON (line 1480) | const NODE_PACKAGE_JSON = 'package.json';
constant DEFAULT_INDENT (line 1493) | const DEFAULT_INDENT = ' ';
constant ENV_PATH_KEY (line 1496) | const ENV_PATH_KEY = getPathKey(process.platform, process.env);
function getPathKey (line 1497) | function getPathKey(platform, env) {
function nullify (line 1525) | function nullify(obj) {
function readJson (line 2071) | async function readJson(loc) {
function readJsonAndFile (line 2074) | async function readJsonAndFile(loc) {
function getEolFromFile (line 2098) | async function getEolFromFile(path) {
function writeFilePreservingEol (line 2118) | async function writeFilePreservingEol(path, data) {
function generatePublishManifest (line 2183) | async function generatePublishManifest(manifest, config, _dists) {
function generatePrettyManifest (line 2250) | function generatePrettyManifest(manifest) {
function hasWrapper (line 2256) | function hasWrapper() {
class Build (line 2260) | class Build {
method constructor (line 2261) | constructor(flags, config, reporter) {
method cleanup (line 2273) | async cleanup() {
method init (line 2280) | async init(isFull) {
function run (line 2465) | async function run(config, reporter, flags, args) {
function isValidName (line 2508) | function isValidName(name) {
function isValidScopedName (line 2512) | function isValidScopedName(name) {
function isValidPackageName (line 2521) | function isValidPackageName(name) {
function validate (line 2524) | function validate (info, isRoot, reporter, warn) {
function cleanDependencies (line 2584) | function cleanDependencies(info, isRoot, reporter, warn) {
function isValidLicense (line 2641) | function isValidLicense(license) {
function stringifyPerson (line 2644) | function stringifyPerson(person) {
function parsePerson (line 2669) | function parsePerson(person) {
function normalizePerson (line 2696) | function normalizePerson(person) {
function extractDescription (line 2699) | function extractDescription(readme) {
function clean (line 2742) | function clean(str) {
constant REGEXES (line 2746) | const REGEXES = {
function inferLicense (line 2754) | function inferLicense(license) {
constant LICENSE_RENAMES (line 2778) | const LICENSE_RENAMES = {
function warn (line 3107) | function warn(msg) {
class BlockingQueue (line 3130) | class BlockingQueue {
method constructor (line 3131) | constructor(alias, maxConcurrency = Infinity) {
method stillActive (line 3143) | stillActive() {
method stuckTick (line 3154) | stuckTick() {
method push (line 3161) | push(key, factory) {
method shift (line 3183) | shift(key) {
method maybePushConcurrencyQueue (line 3236) | maybePushConcurrencyQueue(run) {
method shiftConcurrencyQueue (line 3244) | shiftConcurrencyQueue() {
class ProcessSpawnError (line 3256) | class ProcessSpawnError extends types.MessageError {
method constructor (line 3257) | constructor(msg, code, process) {
class ProcessTermError (line 3264) | class ProcessTermError extends types.MessageError {}
function forwardSignalToSpawnedProcesses (line 3271) | function forwardSignalToSpawnedProcesses(signal) {
function spawn (line 3276) | function spawn(program, args, opts = {}, onData) {
function fixCmdWinSlashes (line 3348) | function fixCmdWinSlashes(cmd) {
function makeEnv (line 3414) | async function makeEnv() {
function executeLifecycleScript (line 3567) | async function executeLifecycleScript({
class Config (line 3684) | class Config {
method constructor (line 3685) | constructor(reporter, cwd, flags) {
method loadPackageManifest (line 3692) | async loadPackageManifest() {
method readJson (line 3705) | readJson(loc, factory = readJson) {
method getDistributions (line 3717) | async getDistributions() {
function forwardSignalAndExit (line 3759) | function forwardSignalAndExit(signal) {
function handleSignals (line 3766) | function handleSignals() {
constant FALSY_STRINGS (line 3772) | const FALSY_STRINGS = new Set(['0', 'false']);
function boolify (line 3773) | function boolify(val) {
function boolifyWithDefault (line 3776) | function boolifyWithDefault(val, defaultResult) {
function getVersion (line 3782) | function getVersion() {
function printHelp (line 3792) | function printHelp() {
function cli (line 3808) | async function cli(args) {
FILE: checkpoint/dist-src/commands/build.js
function hasWrapper (line 6) | function hasWrapper() {
class Build (line 10) | class Build {
method constructor (line 11) | constructor(flags, config, reporter) {
method cleanup (line 21) | async cleanup() {
method init (line 25) | async init(isFull) {
function run (line 189) | async function run(config, reporter, flags, args) {
FILE: checkpoint/dist-src/config.js
class Config (line 10) | class Config {
method constructor (line 11) | constructor(reporter, cwd, flags) {
method loadPackageManifest (line 17) | async loadPackageManifest() {
method readJson (line 29) | readJson(loc, factory = fs.readJson) {
method getDistributions (line 42) | async getDistributions() {
FILE: checkpoint/dist-src/constants.js
constant DEPENDENCY_TYPES (line 5) | const DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDepe...
constant RESOLUTIONS (line 7) | const RESOLUTIONS = 'resolutions';
constant MANIFEST_FIELDS (line 8) | const MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES];
constant SUPPORTED_NODE_VERSIONS (line 9) | const SUPPORTED_NODE_VERSIONS = '>=8.5.0';
constant CHILD_CONCURRENCY (line 25) | const CHILD_CONCURRENCY = 5;
constant NODE_MODULES_FOLDER (line 42) | const NODE_MODULES_FOLDER = 'node_modules';
constant NODE_PACKAGE_JSON (line 43) | const NODE_PACKAGE_JSON = 'package.json';
constant DEFAULT_INDENT (line 56) | const DEFAULT_INDENT = ' ';
constant ENV_PATH_KEY (line 59) | const ENV_PATH_KEY = getPathKey(process.platform, process.env);
function getPathKey (line 60) | function getPathKey(platform, env) {
FILE: checkpoint/dist-src/errors.js
class ProcessSpawnError (line 2) | class ProcessSpawnError extends MessageError {
method constructor (line 3) | constructor(msg, code, process) {
class SecurityError (line 9) | class SecurityError extends MessageError {
class ProcessTermError (line 11) | class ProcessTermError extends MessageError {
class ResponseError (line 13) | class ResponseError extends Error {
method constructor (line 14) | constructor(msg, responseCode) {
class OneTimePasswordError (line 19) | class OneTimePasswordError extends Error {
FILE: checkpoint/dist-src/index.js
function getVersion (line 18) | function getVersion() {
function printHelp (line 23) | function printHelp() {
function cli (line 38) | async function cli(args) {
FILE: checkpoint/dist-src/reporters/base-reporter.js
function stringifyLangArgs (line 7) | function stringifyLangArgs(args) {
class BaseReporter (line 32) | class BaseReporter {
method constructor (line 33) | constructor(opts = {}) {
method lang (line 49) | lang(key, ...args) {
method rawText (line 66) | rawText(str) {
method verbose (line 73) | verbose(msg) {
method verboseInspect (line 78) | verboseInspect(val) {
method _verbose (line 83) | _verbose(msg) { }
method _verboseInspect (line 84) | _verboseInspect(val) { }
method _getStandardInput (line 85) | _getStandardInput() {
method initPeakMemoryCounter (line 100) | initPeakMemoryCounter() {
method checkPeakMemory (line 108) | checkPeakMemory() {
method close (line 114) | close() {
method getTotalTime (line 120) | getTotalTime() {
method list (line 124) | list(key, items, hints) { }
method tree (line 126) | tree(key, obj, { force = false } = {}) { }
method step (line 128) | step(current, total, message, emoji) { }
method error (line 131) | error(message) { }
method info (line 133) | info(message) { }
method warn (line 135) | warn(message) { }
method success (line 137) | success(message) { }
method log (line 140) | log(message, { force = false } = {}) { }
method command (line 142) | command(command) { }
method inspect (line 144) | inspect(value) { }
method header (line 146) | header(pkg) { }
method footer (line 148) | footer(showPeakMemory) { }
method table (line 150) | table(head, body) { }
method activity (line 152) | activity() {
method activitySet (line 159) | activitySet(total, workers) {
method progress (line 171) | progress(total) {
method disableProgress (line 175) | disableProgress() {
FILE: checkpoint/dist-src/reporters/console/console-reporter.js
constant AUDIT_COL_WIDTHS (line 11) | const AUDIT_COL_WIDTHS = [15, 62];
class ConsoleReporter (line 24) | class ConsoleReporter extends BaseReporter {
method constructor (line 25) | constructor(opts) {
method _prependEmoji (line 33) | _prependEmoji(msg, emoji) {
method _logCategory (line 39) | _logCategory(category, color, msg) {
method _verbose (line 43) | _verbose(msg) {
method _verboseInspect (line 46) | _verboseInspect(obj) {
method close (line 49) | close() {
method table (line 57) | table(head, body) {
method step (line 79) | step(current, total, msg, emoji) {
method inspect (line 89) | inspect(value) {
method list (line 100) | list(key, items, hints) {
method header (line 114) | header(pkg) {
method footer (line 117) | footer(showPeakMemory) {
method log (line 127) | log(msg, { force = false } = {}) {
method _log (line 131) | _log(msg, { force = false } = {}) {
method success (line 138) | success(msg) {
method error (line 141) | error(msg) {
method info (line 145) | info(msg) {
method command (line 148) | command(command) {
method warn (line 151) | warn(msg) {
method tree (line 156) | tree(key, trees, { force = false } = {}) {
method activitySet (line 178) | activitySet(total, workers) {
method activity (line 233) | activity() {
method progress (line 254) | progress(count) {
method stopProgress (line 277) | stopProgress() {
FILE: checkpoint/dist-src/reporters/console/helpers/tree-helper.js
function sortTrees (line 2) | function sortTrees(trees) {
function recurseTree (line 7) | function recurseTree(tree, prefix, recurseFunc) {
function getFormattedOutput (line 15) | function getFormattedOutput(fmt) {
function getNextIndentChar (line 20) | function getNextIndentChar(end) {
function getLastIndentChar (line 23) | function getLastIndentChar(end) {
function getSuffix (line 26) | function getSuffix(hint, formatter) {
function formatColor (line 29) | function formatColor(color, strToFormat, formatter) {
FILE: checkpoint/dist-src/reporters/console/progress-bar.js
class ProgressBar (line 2) | class ProgressBar {
method constructor (line 3) | constructor(total, stdout = process.stderr, callback) {
method tick (line 12) | tick() {
method cancelTick (line 22) | cancelTick() {
method stop (line 28) | stop() {
method render (line 37) | render() {
FILE: checkpoint/dist-src/reporters/console/spinner-progress.js
class Spinner (line 2) | class Spinner {
method constructor (line 3) | constructor(stdout = process.stderr, lineNumber = 0) {
method setPrefix (line 13) | setPrefix(prefix) {
method setText (line 16) | setText(text) {
method start (line 19) | start() {
method render (line 23) | render() {
method stop (line 36) | stop() {
FILE: checkpoint/dist-src/reporters/console/util.js
constant CLEAR_WHOLE_LINE (line 4) | const CLEAR_WHOLE_LINE = 0;
constant CLEAR_RIGHT_OF_CURSOR (line 5) | const CLEAR_RIGHT_OF_CURSOR = 1;
function clearLine (line 6) | function clearLine(stdout) {
function toStartOfLine (line 19) | function toStartOfLine(stdout) {
function writeOnNthLine (line 26) | function writeOnNthLine(stdout, n, msg) {
function clearNthLine (line 43) | function clearNthLine(stdout, n) {
FILE: checkpoint/dist-src/reporters/format.js
function formatFunction (line 1) | function formatFunction(...strs) {
FILE: checkpoint/dist-src/reporters/json-reporter.js
class JSONReporter (line 2) | class JSONReporter extends BaseReporter {
method constructor (line 3) | constructor(opts) {
method _dump (line 8) | _dump(type, data, error) {
method _verbose (line 15) | _verbose(msg) {
method list (line 18) | list(type, items, hints) {
method tree (line 21) | tree(type, trees) {
method step (line 24) | step(current, total, message) {
method inspect (line 27) | inspect(value) {
method footer (line 30) | footer(showPeakMemory) {
method log (line 33) | log(msg) {
method command (line 36) | command(msg) {
method table (line 39) | table(head, body) {
method success (line 42) | success(msg) {
method error (line 45) | error(msg) {
method warn (line 48) | warn(msg) {
method info (line 51) | info(msg) {
method activitySet (line 54) | activitySet(total, workers) {
method activity (line 89) | activity() {
method _activity (line 92) | _activity(data) {
method progress (line 110) | progress(total) {
FILE: checkpoint/dist-src/reporters/noop-reporter.js
class NoopReporter (line 2) | class NoopReporter extends BaseReporter {
method lang (line 3) | lang(key, ...args) {
method verbose (line 6) | verbose(msg) { }
method verboseInspect (line 7) | verboseInspect(val) { }
method initPeakMemoryCounter (line 8) | initPeakMemoryCounter() { }
method checkPeakMemory (line 9) | checkPeakMemory() { }
method close (line 10) | close() { }
method getTotalTime (line 11) | getTotalTime() {
method list (line 14) | list(key, items, hints) { }
method tree (line 15) | tree(key, obj) { }
method step (line 16) | step(current, total, message, emoji) { }
method error (line 17) | error(message) { }
method info (line 18) | info(message) { }
method warn (line 19) | warn(message) { }
method success (line 20) | success(message) { }
method log (line 21) | log(message) { }
method command (line 22) | command(command) { }
method inspect (line 23) | inspect(value) { }
method header (line 24) | header(pkg) { }
method footer (line 25) | footer(showPeakMemory) { }
method table (line 26) | table(head, body) { }
method activity (line 27) | activity() {
method activitySet (line 33) | activitySet(total, workers) {
method progress (line 44) | progress(total) {
method disableProgress (line 47) | disableProgress() {
FILE: checkpoint/dist-src/util/babel-plugin-import-rewrite.js
function log (line 8) | function log(symbol, fileName, errors) {
function transform (line 17) | function transform({ template, types: t }) {
FILE: checkpoint/dist-src/util/babel-validate-specifier.js
function getLineCol (line 3) | function getLineCol(node) {
function validateDynamicImportArguments (line 7) | function validateDynamicImportArguments(path) {
FILE: checkpoint/dist-src/util/blocking-queue.js
class BlockingQueue (line 2) | class BlockingQueue {
method constructor (line 3) | constructor(alias, maxConcurrency = Infinity) {
method stillActive (line 14) | stillActive() {
method stuckTick (line 23) | stuckTick() {
method push (line 30) | push(key, factory) {
method shift (line 46) | shift(key) {
method maybePushConcurrencyQueue (line 87) | maybePushConcurrencyQueue(run) {
method shiftConcurrencyQueue (line 95) | shiftConcurrencyQueue() {
FILE: checkpoint/dist-src/util/child.js
function forwardSignalToSpawnedProcesses (line 12) | function forwardSignalToSpawnedProcesses(signal) {
function spawn (line 17) | function spawn(program, args, opts = {}, onData) {
FILE: checkpoint/dist-src/util/conversion.js
constant FALSY_STRINGS (line 1) | const FALSY_STRINGS = new Set(['0', 'false']);
function boolify (line 2) | function boolify(val) {
function boolifyWithDefault (line 5) | function boolifyWithDefault(val, defaultResult) {
FILE: checkpoint/dist-src/util/execute-lifecycle-script.js
function makeEnv (line 32) | async function makeEnv() {
function executeLifecycleScript (line 188) | async function executeLifecycleScript({
FILE: checkpoint/dist-src/util/fix-cmd-win-slashes.js
function fixCmdWinSlashes (line 1) | function fixCmdWinSlashes(cmd) {
FILE: checkpoint/dist-src/util/fs.js
function readJson (line 562) | async function readJson(loc) {
function readJsonAndFile (line 565) | async function readJsonAndFile(loc) {
function walk (line 578) | async function walk(dir, relativeDir, ignoreBasenames = new Set()) {
function getEolFromFile (line 610) | async function getEolFromFile(path) {
function writeFilePreservingEol (line 625) | async function writeFilePreservingEol(path, data) {
FILE: checkpoint/dist-src/util/map.js
function nullify (line 1) | function nullify(obj) {
FILE: checkpoint/dist-src/util/misc.js
function sortAlpha (line 3) | function sortAlpha(a, b) {
function sortOptionsByFlags (line 15) | function sortOptionsByFlags(a, b) {
function entries (line 20) | function entries(obj) {
function removePrefix (line 29) | function removePrefix(pattern, prefix) {
function removeSuffix (line 35) | function removeSuffix(pattern, suffix) {
function addSuffix (line 41) | function addSuffix(pattern, suffix) {
function hyphenate (line 47) | function hyphenate(str) {
function camelCase (line 52) | function camelCase(str) {
function compareSortedArrays (line 60) | function compareSortedArrays(array1, array2) {
function sleep (line 71) | function sleep(ms) {
FILE: checkpoint/dist-src/util/normalize-manifest/fix.js
constant LICENSE_RENAMES (line 9) | const LICENSE_RENAMES = {
FILE: checkpoint/dist-src/util/normalize-manifest/for-publish.js
function generatePublishManifest (line 1) | async function generatePublishManifest(manifest, config, _dists) {
function generatePrettyManifest (line 43) | function generatePrettyManifest(manifest) {
FILE: checkpoint/dist-src/util/normalize-manifest/index.js
function warn (line 22) | function warn(msg) {
FILE: checkpoint/dist-src/util/normalize-manifest/infer-license.js
function clean (line 2) | function clean(str) {
constant REGEXES (line 5) | const REGEXES = {
function inferLicense (line 13) | function inferLicense(license) {
FILE: checkpoint/dist-src/util/normalize-manifest/util.js
function isValidLicense (line 2) | function isValidLicense(license) {
function stringifyPerson (line 5) | function stringifyPerson(person) {
function parsePerson (line 23) | function parsePerson(person) {
function normalizePerson (line 43) | function normalizePerson(person) {
function extractDescription (line 46) | function extractDescription(readme) {
FILE: checkpoint/dist-src/util/normalize-manifest/validate.js
function isValidName (line 15) | function isValidName(name) {
function isValidScopedName (line 18) | function isValidScopedName(name) {
function isValidPackageName (line 25) | function isValidPackageName(name) {
function cleanDependencies (line 77) | function cleanDependencies(info, isRoot, reporter, warn) {
FILE: checkpoint/dist-src/util/promise.js
function wait (line 1) | function wait(delay) {
function promisify (line 6) | function promisify(fn, firstData) {
function queue (line 29) | function queue(arr, promiseProducer, concurrency = Infinity) {
FILE: checkpoint/dist-src/util/signal-handler.js
function forwardSignalAndExit (line 2) | function forwardSignalAndExit(signal) {
function handleSignals (line 8) | function handleSignals() {
FILE: checkpoint/dist-types/commands/build.d.ts
class Build (line 5) | class Build {
FILE: checkpoint/dist-types/config.d.ts
type BuildFlags (line 3) | interface BuildFlags {
type GlobalFlags (line 9) | interface GlobalFlags extends BuildFlags {
class Config (line 15) | class Config {
FILE: checkpoint/dist-types/errors.d.ts
class ProcessSpawnError (line 2) | class ProcessSpawnError extends MessageError {
class SecurityError (line 7) | class SecurityError extends MessageError {
class ProcessTermError (line 9) | class ProcessTermError extends MessageError {
class ResponseError (line 13) | class ResponseError extends Error {
class OneTimePasswordError (line 17) | class OneTimePasswordError extends Error {
FILE: checkpoint/dist-types/reporters/base-reporter.d.ts
type Language (line 6) | type Language = keyof typeof languages;
type ReporterOptions (line 7) | type ReporterOptions = {
class BaseReporter (line 20) | class BaseReporter {
FILE: checkpoint/dist-types/reporters/console/console-reporter.d.ts
type Row (line 6) | type Row = Array<string>;
class ConsoleReporter (line 7) | class ConsoleReporter extends BaseReporter {
FILE: checkpoint/dist-types/reporters/console/helpers/tree-helper.d.ts
type FormattedOutput (line 2) | type FormattedOutput = {
FILE: checkpoint/dist-types/reporters/console/progress-bar.d.ts
class ProgressBar (line 3) | class ProgressBar {
FILE: checkpoint/dist-types/reporters/console/spinner-progress.d.ts
class Spinner (line 3) | class Spinner {
FILE: checkpoint/dist-types/reporters/format.d.ts
type FormatFunction (line 21) | type FormatFunction = (...strs: Array<string>) => string;
type FormatKeys (line 22) | type FormatKeys = keyof typeof defaultFormatter;
type Formatter (line 23) | type Formatter = {
FILE: checkpoint/dist-types/reporters/json-reporter.d.ts
class JSONReporter (line 3) | class JSONReporter extends BaseReporter {
FILE: checkpoint/dist-types/reporters/lang/en.d.ts
type LanguageKeys (line 352) | type LanguageKeys = keyof typeof messages;
FILE: checkpoint/dist-types/reporters/noop-reporter.d.ts
class NoopReporter (line 4) | class NoopReporter extends BaseReporter {
FILE: checkpoint/dist-types/reporters/types.d.ts
type Stdout (line 4) | type Stdout = Writable | WriteStream;
type Stdin (line 5) | type Stdin = Readable | ReadStream;
type Package (line 6) | type Package = {
type Tree (line 10) | type Tree = {
type Trees (line 17) | type Trees = Array<Tree>;
type ReporterSpinner (line 18) | type ReporterSpinner = {
type ReporterSpinnerSet (line 22) | type ReporterSpinnerSet = {
type ReporterSetSpinner (line 26) | type ReporterSetSpinner = {
FILE: checkpoint/dist-types/types.d.ts
type CLIFunction (line 3) | type CLIFunction = (config: Config, reporter: Reporter, flags: Object, a...
type _CLIFunctionReturn (line 4) | type _CLIFunctionReturn = boolean;
type CLIFunctionReturn (line 5) | type CLIFunctionReturn = _CLIFunctionReturn | Promise<_CLIFunctionReturn>;
type PersonObject (line 6) | type PersonObject = {
type Dependencies (line 11) | type Dependencies = {
type Manifest (line 14) | type Manifest = {
type Dependency (line 78) | type Dependency = {
FILE: checkpoint/dist-types/util/blocking-queue.d.ts
class BlockingQueue (line 2) | class BlockingQueue {
FILE: checkpoint/dist-types/util/child.d.ts
type ProcessFn (line 7) | type ProcessFn = (proc: ChildProcess, update: (chunk: string) => void, r...
FILE: checkpoint/dist-types/util/execute-lifecycle-script.d.ts
type LifecycleReturn (line 2) | type LifecycleReturn = Promise<{
FILE: checkpoint/dist-types/util/fs.d.ts
type WalkFiles (line 25) | type WalkFiles = Array<{
FILE: checkpoint/dist-types/util/normalize-manifest/fix.d.ts
type Dict (line 2) | type Dict<T> = {
type WarnFunction (line 5) | type WarnFunction = (msg: string) => void;
FILE: checkpoint/dist-types/util/normalize-manifest/validate.d.ts
type WarnFunction (line 3) | type WarnFunction = (msg: string) => void;
FILE: src/commands/build.ts
function hasWrapper (line 10) | function hasWrapper(): boolean {
class Build (line 16) | class Build {
method constructor (line 17) | constructor(flags: BuildFlags, config: Config, reporter: Reporter) {
method cleanup (line 34) | async cleanup(): Promise<void> {
method init (line 39) | async init(isFull?: boolean): Promise<void> {
function run (line 222) | async function run(config: Config, reporter: Reporter, flags: BuildFlags...
FILE: src/config.ts
type BuildFlags (line 13) | interface BuildFlags {
type GlobalFlags (line 20) | interface GlobalFlags extends BuildFlags {
class Config (line 27) | class Config {
method constructor (line 34) | constructor(reporter: BaseReporter, cwd: string, flags: GlobalFlags) {
method loadPackageManifest (line 41) | async loadPackageManifest() {
method readJson (line 53) | readJson(loc: string, factory: (filename: string) => Promise<any> = fs...
method getDistributions (line 65) | async getDistributions(): Promise<[any, any][]> {
FILE: src/constants.ts
constant DEPENDENCY_TYPES (line 6) | const DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'legacyDepe...
constant RESOLUTIONS (line 9) | const RESOLUTIONS = 'resolutions';
constant MANIFEST_FIELDS (line 10) | const MANIFEST_FIELDS = [RESOLUTIONS, ...DEPENDENCY_TYPES];
constant SUPPORTED_NODE_VERSIONS (line 12) | const SUPPORTED_NODE_VERSIONS = '>=8.5.0';
constant CHILD_CONCURRENCY (line 36) | const CHILD_CONCURRENCY = 5;
constant NODE_MODULES_FOLDER (line 61) | const NODE_MODULES_FOLDER = 'node_modules';
constant NODE_PACKAGE_JSON (line 62) | const NODE_PACKAGE_JSON = 'package.json';
constant DEFAULT_INDENT (line 80) | const DEFAULT_INDENT = ' ';
constant ENV_PATH_KEY (line 84) | const ENV_PATH_KEY = getPathKey(process.platform, process.env);
function getPathKey (line 86) | function getPathKey(platform: string, env: NodeJS.ProcessEnv): string {
FILE: src/errors.ts
class ProcessSpawnError (line 3) | class ProcessSpawnError extends MessageError {
method constructor (line 4) | constructor(msg: string, code?: string, process?: string) {
class SecurityError (line 14) | class SecurityError extends MessageError {}
class ProcessTermError (line 16) | class ProcessTermError extends MessageError {
class ResponseError (line 21) | class ResponseError extends Error {
method constructor (line 22) | constructor(msg: string, responseCode: number) {
class OneTimePasswordError (line 30) | class OneTimePasswordError extends Error {}
FILE: src/index.ts
function getVersion (line 20) | function getVersion() {
function printHelp (line 26) | function printHelp() {
function cli (line 44) | async function cli(args: string[]) {
FILE: src/reporters/base-reporter.ts
type Language (line 13) | type Language = keyof typeof languages;
type ReporterOptions (line 15) | type ReporterOptions = {
function stringifyLangArgs (line 28) | function stringifyLangArgs(args: Array<any>): Array<string> {
class BaseReporter (line 52) | class BaseReporter {
method constructor (line 53) | constructor(opts: ReporterOptions = {}) {
method lang (line 89) | lang(key: LanguageKeys, ...args: Array<any>): string {
method rawText (line 109) | rawText(str: string): {inspect(): string} {
method verbose (line 117) | verbose(msg: string) {
method verboseInspect (line 123) | verboseInspect(val: any) {
method _verbose (line 129) | _verbose(msg: string) {}
method _verboseInspect (line 130) | _verboseInspect(val: any) {}
method _getStandardInput (line 132) | _getStandardInput(): Stdin {
method initPeakMemoryCounter (line 149) | initPeakMemoryCounter() {
method checkPeakMemory (line 158) | checkPeakMemory() {
method close (line 165) | close() {
method getTotalTime (line 172) | getTotalTime(): number {
method list (line 177) | list(key: string, items: Array<string>, hints?: Object) {}
method tree (line 180) | tree(key: string, obj: Trees, {force = false}: {force?: boolean} = {}) {}
method step (line 183) | step(current: number, total: number, message: string, emoji?: string) {}
method error (line 187) | error(message: string) {}
method info (line 190) | info(message: string) {}
method warn (line 193) | warn(message: string) {}
method success (line 196) | success(message: string) {}
method log (line 200) | log(message: string, {force = false}: {force?: boolean} = {}) {}
method command (line 203) | command(command: string) {}
method inspect (line 206) | inspect(value: any) {}
method header (line 209) | header(pkg: Package) {}
method footer (line 212) | footer(showPeakMemory: boolean) {}
method table (line 215) | table(head: Array<string>, body: Array<Array<string>>) {}
method activity (line 218) | activity(): ReporterSpinner {
method activitySet (line 226) | activitySet(total: number, workers: number): ReporterSpinnerSet {
method progress (line 239) | progress(total: number): () => void {
method disableProgress (line 244) | disableProgress() {
FILE: src/reporters/console/console-reporter.ts
constant AUDIT_COL_WIDTHS (line 14) | const AUDIT_COL_WIDTHS = [15, 62];
type Row (line 24) | type Row = Array<string>;
class ConsoleReporter (line 32) | class ConsoleReporter extends BaseReporter {
method constructor (line 37) | constructor(opts: ReporterOptions) {
method _prependEmoji (line 47) | _prependEmoji(msg: string, emoji?: string): string {
method _logCategory (line 54) | _logCategory(category: string, color: FormatKeys, msg: string) {
method _verbose (line 59) | _verbose(msg: string) {
method _verboseInspect (line 63) | _verboseInspect(obj: any) {
method close (line 67) | close() {
method table (line 76) | table(head: Array<string>, body: Array<Row>) {
method step (line 104) | step(current: number, total: number, msg: string, emoji?: string) {
method inspect (line 115) | inspect(value: any) {
method list (line 128) | list(key: string, items: Array<string>, hints?: Object) {
method header (line 143) | header(pkg: Package) {
method footer (line 147) | footer(showPeakMemory?: boolean) {
method log (line 159) | log(msg: string, {force = false}: {force?: boolean} = {}) {
method _log (line 164) | _log(msg: string, {force = false}: {force?: boolean} = {}) {
method success (line 172) | success(msg: string) {
method error (line 176) | error(msg: string) {
method info (line 181) | info(msg: string) {
method command (line 185) | command(command: string) {
method warn (line 189) | warn(msg: string) {
method tree (line 195) | tree(key: string, trees: Trees, {force = false}: {force?: boolean} = {...
method activitySet (line 219) | activitySet(total: number, workers: number): ReporterSpinnerSet {
method activity (line 284) | activity(): ReporterSpinner {
method progress (line 310) | progress(count: number): () => void {
method stopProgress (line 339) | stopProgress() {
FILE: src/reporters/console/helpers/tree-helper.ts
type FormattedOutput (line 4) | type FormattedOutput = {
function sortTrees (line 13) | function sortTrees(trees: Trees): Trees {
function recurseTree (line 19) | function recurseTree(tree: Trees, prefix: string, recurseFunc: Function) {
function getFormattedOutput (line 28) | function getFormattedOutput(fmt: FormattedOutput): string {
function getNextIndentChar (line 34) | function getNextIndentChar(end: boolean): string {
function getLastIndentChar (line 38) | function getLastIndentChar(end: boolean): string {
function getSuffix (line 42) | function getSuffix(hint: any, formatter: any): string {
function formatColor (line 46) | function formatColor(color: string, strToFormat: string, formatter: any)...
FILE: src/reporters/console/progress-bar.ts
class ProgressBar (line 4) | class ProgressBar {
method constructor (line 5) | constructor(total: number, stdout: Stdout = process.stderr, callback?:...
method tick (line 26) | tick() {
method cancelTick (line 39) | cancelTick() {
method stop (line 46) | stop() {
method render (line 57) | render() {
FILE: src/reporters/console/spinner-progress.ts
class Spinner (line 4) | class Spinner {
method constructor (line 5) | constructor(stdout: Stdout = process.stderr, lineNumber: number = 0) {
method setPrefix (line 56) | setPrefix(prefix: string) {
method setText (line 59) | setText(text: string) {
method start (line 62) | start() {
method render (line 66) | render() {
method stop (line 79) | stop() {
FILE: src/reporters/console/util.ts
constant CLEAR_WHOLE_LINE (line 7) | const CLEAR_WHOLE_LINE = 0;
constant CLEAR_RIGHT_OF_CURSOR (line 8) | const CLEAR_RIGHT_OF_CURSOR = 1;
function clearLine (line 10) | function clearLine(stdout: Stdout) {
function toStartOfLine (line 25) | function toStartOfLine(stdout: Stdout) {
function writeOnNthLine (line 34) | function writeOnNthLine(stdout: Stdout, n: number, msg: string) {
function clearNthLine (line 53) | function clearNthLine(stdout: Stdout, n: number) {
FILE: src/reporters/format.ts
function formatFunction (line 1) | function formatFunction(...strs: Array<string>): string {
type FormatFunction (line 25) | type FormatFunction = (...strs: Array<string>) => string;
type FormatKeys (line 27) | type FormatKeys = keyof typeof defaultFormatter;
type Formatter (line 29) | type Formatter = {
FILE: src/reporters/json-reporter.ts
class JSONReporter (line 4) | class JSONReporter extends BaseReporter {
method constructor (line 5) | constructor(opts?: Object) {
method _dump (line 15) | _dump(type: string, data: any, error?: boolean) {
method _verbose (line 23) | _verbose(msg: string) {
method list (line 27) | list(type: string, items: Array<string>, hints?: Object) {
method tree (line 31) | tree(type: string, trees: Trees) {
method step (line 35) | step(current: number, total: number, message: string) {
method inspect (line 39) | inspect(value: any) {
method footer (line 43) | footer(showPeakMemory: boolean) {
method log (line 47) | log(msg: string) {
method command (line 51) | command(msg: string) {
method table (line 55) | table(head: Array<string>, body: Array<Array<string>>) {
method success (line 59) | success(msg: string) {
method error (line 63) | error(msg: string) {
method warn (line 67) | warn(msg: string) {
method info (line 71) | info(msg: string) {
method activitySet (line 75) | activitySet(total: number, workers: number): ReporterSpinnerSet {
method activity (line 115) | activity(): ReporterSpinner {
method _activity (line 119) | _activity(data: Object): ReporterSpinner {
method progress (line 141) | progress(total: number): () => void {
FILE: src/reporters/lang/en.ts
type LanguageKeys (line 443) | type LanguageKeys = keyof typeof messages;
FILE: src/reporters/noop-reporter.ts
class NoopReporter (line 5) | class NoopReporter extends BaseReporter {
method lang (line 6) | lang(key: LanguageKeys, ...args: Array<any>): string {
method verbose (line 9) | verbose(msg: string) {}
method verboseInspect (line 10) | verboseInspect(val: any) {}
method initPeakMemoryCounter (line 11) | initPeakMemoryCounter() {}
method checkPeakMemory (line 12) | checkPeakMemory() {}
method close (line 13) | close() {}
method getTotalTime (line 14) | getTotalTime(): number {
method list (line 17) | list(key: string, items: Array<string>, hints?: Object) {}
method tree (line 18) | tree(key: string, obj: Trees) {}
method step (line 19) | step(current: number, total: number, message: string, emoji?: string) {}
method error (line 20) | error(message: string) {}
method info (line 21) | info(message: string) {}
method warn (line 22) | warn(message: string) {}
method success (line 23) | success(message: string) {}
method log (line 24) | log(message: string) {}
method command (line 25) | command(command: string) {}
method inspect (line 26) | inspect(value: any) {}
method header (line 27) | header(pkg: Package) {}
method footer (line 28) | footer(showPeakMemory: boolean) {}
method table (line 29) | table(head: Array<string>, body: Array<Array<string>>) {}
method activity (line 31) | activity(): ReporterSpinner {
method activitySet (line 38) | activitySet(total: number, workers: number): ReporterSpinnerSet {
method progress (line 50) | progress(total: number): () => void {
method disableProgress (line 54) | disableProgress() {
FILE: src/reporters/types.ts
type Stdout (line 4) | type Stdout = Writable | WriteStream;
type Stdin (line 5) | type Stdin = Readable | ReadStream;
type Package (line 6) | type Package = {
type Tree (line 11) | type Tree = {
type Trees (line 19) | type Trees = Array<Tree>;
type ReporterSpinner (line 21) | type ReporterSpinner = {
type ReporterSpinnerSet (line 26) | type ReporterSpinnerSet = {
type ReporterSetSpinner (line 31) | type ReporterSetSpinner = {
FILE: src/types.ts
type CLIFunction (line 4) | type CLIFunction = (config: Config, reporter: Reporter, flags: Object, a...
type _CLIFunctionReturn (line 6) | type _CLIFunctionReturn = boolean;
type CLIFunctionReturn (line 7) | type CLIFunctionReturn = _CLIFunctionReturn | Promise<_CLIFunctionReturn>;
type PersonObject (line 10) | type PersonObject = {
type Dependencies (line 17) | type Dependencies = {
type Manifest (line 22) | type Manifest = {
type Dependency (line 110) | type Dependency = {
FILE: src/util/babel-plugin-import-rewrite.ts
function log (line 10) | function log(symbol: string, fileName: string, errors: string | Array<st...
function transform (line 20) | function transform({template, types: t}): any {
FILE: src/util/babel-validate-specifier.ts
function getLineCol (line 4) | function getLineCol(node: any): string {
function validateDynamicImportArguments (line 9) | function validateDynamicImportArguments(path): Set<string> {
FILE: src/util/blocking-queue.ts
class BlockingQueue (line 3) | class BlockingQueue {
method constructor (line 4) | constructor(alias: string, maxConcurrency: number = Infinity) {
method stillActive (line 38) | stillActive() {
method stuckTick (line 50) | stuckTick() {
method push (line 60) | push<T>(key: string, factory: () => Promise<T>): Promise<T> {
method shift (line 78) | shift(key: string) {
method maybePushConcurrencyQueue (line 128) | maybePushConcurrencyQueue(run: () => void) {
method shiftConcurrencyQueue (line 136) | shiftConcurrencyQueue() {
FILE: src/util/child.ts
function forwardSignalToSpawnedProcesses (line 18) | function forwardSignalToSpawnedProcesses(signal: string) {
type ProcessFn (line 24) | type ProcessFn = (
function spawn (line 31) | function spawn(
FILE: src/util/conversion.ts
constant FALSY_STRINGS (line 1) | const FALSY_STRINGS = new Set(['0', 'false']);
function boolify (line 3) | function boolify(val: string | number | boolean): boolean {
function boolifyWithDefault (line 7) | function boolifyWithDefault(val: string | number | boolean, defaultResul...
FILE: src/util/execute-lifecycle-script.ts
type LifecycleReturn (line 10) | type LifecycleReturn = Promise<{
function makeEnv (line 55) | async function makeEnv(): Promise<{[key: string]: string}> {
function executeLifecycleScript (line 235) | async function executeLifecycleScript({
FILE: src/util/fix-cmd-win-slashes.ts
function fixCmdWinSlashes (line 1) | function fixCmdWinSlashes(cmd: string): string {
FILE: src/util/fs.ts
function readJson (line 649) | async function readJson(loc: string): Promise<Object> {
function readJsonAndFile (line 653) | async function readJsonAndFile(
type WalkFiles (line 721) | type WalkFiles = Array<{
function walk (line 728) | async function walk(
function getEolFromFile (line 774) | async function getEolFromFile(path: string): Promise<string | void> {
function writeFilePreservingEol (line 792) | async function writeFilePreservingEol(path: string, data: string): Promi...
FILE: src/util/map.ts
function nullify (line 1) | function nullify<T>(obj?: T): T {
FILE: src/util/misc.ts
function sortAlpha (line 3) | function sortAlpha(a: string, b: string): number {
function sortOptionsByFlags (line 16) | function sortOptionsByFlags(a: any, b: any): number {
function entries (line 22) | function entries<T>(obj: {[key: string]: T}): Array<[string, T]> {
function removePrefix (line 32) | function removePrefix(pattern: string, prefix: string): string {
function removeSuffix (line 40) | function removeSuffix(pattern: string, suffix: string): string {
function addSuffix (line 48) | function addSuffix(pattern: string, suffix: string): string {
function hyphenate (line 56) | function hyphenate(str: string): string {
function compareSortedArrays (line 62) | function compareSortedArrays<T>(array1: Array<T>, array2: Array<T>): boo...
function sleep (line 74) | function sleep(ms: number): Promise<void> {
FILE: src/util/normalize-manifest/fix.ts
constant LICENSE_RENAMES (line 12) | const LICENSE_RENAMES = {
type Dict (line 17) | type Dict<T> = {
type WarnFunction (line 21) | type WarnFunction = (msg: string) => void;
FILE: src/util/normalize-manifest/for-publish.ts
function generatePublishManifest (line 4) | async function generatePublishManifest(
function generatePrettyManifest (line 77) | function generatePrettyManifest(manifest) {
FILE: src/util/normalize-manifest/index.ts
function warn (line 27) | function warn(msg: string) {
FILE: src/util/normalize-manifest/infer-license.ts
function clean (line 3) | function clean(str: string): string {
constant REGEXES (line 11) | const REGEXES: {[key: string]: Array<RegExp>} = {
function inferLicense (line 20) | function inferLicense(license: string): string | null {
FILE: src/util/normalize-manifest/util.ts
function isValidLicense (line 5) | function isValidLicense(license: string): boolean {
function stringifyPerson (line 9) | function stringifyPerson(person: any): any {
function parsePerson (line 32) | function parsePerson(person: any): PersonObject {
function normalizePerson (line 58) | function normalizePerson(person: any): any | PersonObject {
function extractDescription (line 62) | function extractDescription(readme: any): string {
FILE: src/util/normalize-manifest/validate.ts
function isValidName (line 22) | function isValidName(name: string): boolean {
function isValidScopedName (line 26) | function isValidScopedName(name: string): boolean {
function isValidPackageName (line 35) | function isValidPackageName(name: string): boolean {
type WarnFunction (line 39) | type WarnFunction = (msg: string) => void;
function cleanDependencies (line 98) | function cleanDependencies(info: Object, isRoot: boolean, reporter: Repo...
FILE: src/util/promise.ts
function wait (line 1) | function wait(delay: number): Promise<void> {
function promisify (line 7) | function promisify(fn: Function, firstData?: boolean): (...args: Array<a...
function queue (line 34) | function queue<T, U>(
FILE: src/util/signal-handler.ts
function forwardSignalAndExit (line 3) | function forwardSignalAndExit(signal: string) {
function handleSignals (line 10) | function handleSignals() {
Condensed preview — 135 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (576K chars).
[
{
"path": ".babelrc",
"chars": 96,
"preview": "{\n \"presets\": [],\n \"plugins\": [\n \"@babel/plugin-proposal-class-properties\"\n ]\n }\n"
},
{
"path": ".github/ISSUE_TEMPLATE.md",
"chars": 236,
"preview": "To create a new issue or search existing discussions, start here: \n👉 **https://www.pika.dev/packages/@pika/pack/discuss"
},
{
"path": ".gitignore",
"chars": 468,
"preview": "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/a"
},
{
"path": ".prettierrc",
"chars": 110,
"preview": "{\n \"singleQuote\": true,\n \"trailingComma\": \"all\",\n \"bracketSpacing\": false,\n \"printWidth\": 120\n }\n"
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 3350,
"preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, w"
},
{
"path": "CONTRIBUTING.md",
"chars": 915,
"preview": "# Contributing to @pika/pack\n\nAll contributions are welcome! \n\n## Building the Project\n\nIt is very cool being able to us"
},
{
"path": "LICENSE",
"chars": 3790,
"preview": "\"\"\"\nThe MIT License\n\nCopyright (c) 2019 Fred K. Schott\n\nPermission is hereby granted, free of charge, to any person obta"
},
{
"path": "README.md",
"chars": 3432,
"preview": "<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 alig"
},
{
"path": "checkpoint/LICENSE",
"chars": 3790,
"preview": "\"\"\"\nThe MIT License\n\nCopyright (c) 2019 Fred K. Schott\n\nPermission is hereby granted, free of charge, to any person obta"
},
{
"path": "checkpoint/README.md",
"chars": 3454,
"preview": "<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"
},
{
"path": "checkpoint/dist-node/index.bin.js",
"chars": 807,
"preview": "#!/usr/bin/env node\n'use strict';\n\nconst ver = process.versions.node;\nconst majorVer = parseInt(ver.split('.')[0], 10);\n"
},
{
"path": "checkpoint/dist-node/index.js",
"chars": 143670,
"preview": "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (e"
},
{
"path": "checkpoint/dist-src/commands/build.js",
"chars": 8545,
"preview": "import chalk from 'chalk';\nimport * as path from 'path';\nimport { DEFAULT_INDENT } from '../constants.js';\nimport * as f"
},
{
"path": "checkpoint/dist-src/config.js",
"chars": 2626,
"preview": "import * as path from 'path';\nimport * as constants from './constants.js';\nimport { MessageError } from '@pika/types';\ni"
},
{
"path": "checkpoint/dist-src/constants.js",
"chars": 4175,
"preview": "// import os from 'os';\n// import * as path from 'path';\n// import userHome from './util/user-home-dir.js';\n// import {g"
},
{
"path": "checkpoint/dist-src/errors.js",
"chars": 531,
"preview": "import { MessageError } from '@pika/types';\nexport class ProcessSpawnError extends MessageError {\n constructor(msg, c"
},
{
"path": "checkpoint/dist-src/index.js",
"chars": 4997,
"preview": "import * as path from 'path';\nimport chalk from 'chalk';\nimport * as fs from 'fs';\nimport invariant from 'invariant';\nim"
},
{
"path": "checkpoint/dist-src/reporters/base-reporter.js",
"chars": 5982,
"preview": "import { defaultFormatter } from './format.js';\nimport * as languages from './lang/index.js';\nimport * as isCI from 'is-"
},
{
"path": "checkpoint/dist-src/reporters/console/console-reporter.js",
"chars": 8897,
"preview": "import chalk from 'chalk';\nimport * as readline from 'readline';\nimport stripAnsi from 'strip-ansi';\nimport { inspect } "
},
{
"path": "checkpoint/dist-src/reporters/console/helpers/tree-helper.js",
"chars": 1022,
"preview": "// public\nexport function sortTrees(trees) {\n return trees.sort(function (tree1, tree2) {\n return tree1.name.l"
},
{
"path": "checkpoint/dist-src/reporters/console/progress-bar.js",
"chars": 1842,
"preview": "import { clearLine, toStartOfLine } from './util.js';\nexport default class ProgressBar {\n constructor(total, stdout ="
},
{
"path": "checkpoint/dist-src/reporters/console/spinner-progress.js",
"chars": 1831,
"preview": "import { writeOnNthLine, clearNthLine } from './util.js';\nexport default class Spinner {\n constructor(stdout = proces"
},
{
"path": "checkpoint/dist-src/reporters/console/util.js",
"chars": 1522,
"preview": "import * as tty from 'tty';\nimport * as readline from 'readline';\nimport chalk from 'chalk';\nconst CLEAR_WHOLE_LINE = 0;"
},
{
"path": "checkpoint/dist-src/reporters/format.js",
"chars": 574,
"preview": "function formatFunction(...strs) {\n return strs.join(' ');\n}\nexport const defaultFormatter = {\n bold: formatFuncti"
},
{
"path": "checkpoint/dist-src/reporters/index.js",
"chars": 246,
"preview": "export { default as ConsoleReporter } from './console/console-reporter';\nexport { default as JSONReporter } from './json"
},
{
"path": "checkpoint/dist-src/reporters/json-reporter.js",
"chars": 3422,
"preview": "import BaseReporter from './base-reporter.js';\nexport default class JSONReporter extends BaseReporter {\n constructor("
},
{
"path": "checkpoint/dist-src/reporters/lang/en.js",
"chars": 26122,
"preview": "const messages = {\n upToDate: 'Already up-to-date.',\n folderInSync: 'Folder in sync.',\n nothingToInstall: 'Noth"
},
{
"path": "checkpoint/dist-src/reporters/lang/index.js",
"chars": 41,
"preview": "import en from './en.js';\nexport { en };\n"
},
{
"path": "checkpoint/dist-src/reporters/noop-reporter.js",
"chars": 1164,
"preview": "import BaseReporter from './base-reporter.js';\nexport default class NoopReporter extends BaseReporter {\n lang(key, .."
},
{
"path": "checkpoint/dist-src/reporters/types.js",
"chars": 0,
"preview": ""
},
{
"path": "checkpoint/dist-src/types.js",
"chars": 0,
"preview": ""
},
{
"path": "checkpoint/dist-src/util/babel-plugin-import-rewrite.js",
"chars": 3057,
"preview": "// @flow\nimport * as nodeFs from 'fs';\nimport * as nodePath from 'path';\nimport * as url from 'url';\nimport chalk from '"
},
{
"path": "checkpoint/dist-src/util/babel-validate-specifier.js",
"chars": 698,
"preview": "// @flow\nimport chalk from 'chalk';\nfunction getLineCol(node) {\n const loc = node.loc.start;\n return chalk.dim(`[$"
},
{
"path": "checkpoint/dist-src/util/blocking-queue.js",
"chars": 3306,
"preview": "import map from './map.js';\nexport default class BlockingQueue {\n constructor(alias, maxConcurrency = Infinity) {\n "
},
{
"path": "checkpoint/dist-src/util/child.js",
"chars": 3006,
"preview": "/* global child_process$spawnOpts */\nimport * as constants from '../constants.js';\nimport BlockingQueue from './blocking"
},
{
"path": "checkpoint/dist-src/util/conversion.js",
"chars": 291,
"preview": "const FALSY_STRINGS = new Set(['0', 'false']);\nexport function boolify(val) {\n return !FALSY_STRINGS.has(val.toString"
},
{
"path": "checkpoint/dist-src/util/execute-lifecycle-script.js",
"chars": 12090,
"preview": "import * as child from './child.js';\nimport { fixCmdWinSlashes } from './fix-cmd-win-slashes.js';\n// export const IGNORE"
},
{
"path": "checkpoint/dist-src/util/fix-cmd-win-slashes.js",
"chars": 1026,
"preview": "export function fixCmdWinSlashes(cmd) {\n function findQuotes(quoteSymbol) {\n const quotes = [];\n const "
},
{
"path": "checkpoint/dist-src/util/fs-normalized.js",
"chars": 6011,
"preview": "//\n// // This module serves as a wrapper for file operations that are inconsistant across node and OS versions.\n// impor"
},
{
"path": "checkpoint/dist-src/util/fs.js",
"chars": 24321,
"preview": "import { promisify } from 'util';\nimport _rimraf from 'rimraf';\nimport _mkdirp from 'mkdirp';\nimport _glob from 'glob';\n"
},
{
"path": "checkpoint/dist-src/util/map.js",
"chars": 501,
"preview": "export default function nullify(obj) {\n if (Array.isArray(obj)) {\n for (const item of obj) {\n nulli"
},
{
"path": "checkpoint/dist-src/util/misc.js",
"chars": 1902,
"preview": "/* @flow */\nimport _camelCase from 'camelcase';\nexport function sortAlpha(a, b) {\n // sort alphabetically in a determ"
},
{
"path": "checkpoint/dist-src/util/normalize-manifest/fix.js",
"chars": 10951,
"preview": "import { MANIFEST_FIELDS } from '../../constants.js';\nimport { isValidLicense } from './util.js';\nimport { normalizePers"
},
{
"path": "checkpoint/dist-src/util/normalize-manifest/for-publish.js",
"chars": 1537,
"preview": "export async function generatePublishManifest(manifest, config, _dists) {\n const { name, version, description, keywor"
},
{
"path": "checkpoint/dist-src/util/normalize-manifest/index.js",
"chars": 1056,
"preview": "import validate from './validate.js';\nimport fix from './fix.js';\nimport * as path from 'path';\nexport default (async fu"
},
{
"path": "checkpoint/dist-src/util/normalize-manifest/infer-license.js",
"chars": 996,
"preview": "import LICENSES from './licenses.js';\nfunction clean(str) {\n return str.replace(/[^A-Za-z\\s]/g, ' ').replace(/[\\s]+/g"
},
{
"path": "checkpoint/dist-src/util/normalize-manifest/licenses.js",
"chars": 17997,
"preview": "export default ({\n 'Apache-2.0': new RegExp('(licensed under the apache license version the license you may not use t"
},
{
"path": "checkpoint/dist-src/util/normalize-manifest/typos.js",
"chars": 631,
"preview": "export default {\n autohr: 'author',\n autor: 'author',\n contributers: 'contributors',\n depdenencies: 'depende"
},
{
"path": "checkpoint/dist-src/util/normalize-manifest/util.js",
"chars": 2113,
"preview": "import validateLicense from 'validate-npm-package-license';\nexport function isValidLicense(license) {\n return !!licen"
},
{
"path": "checkpoint/dist-src/util/normalize-manifest/validate.js",
"chars": 4395,
"preview": "import { MessageError } from '@pika/types';\nimport typos from './typos.js';\nimport isBuiltinModule from 'is-builtin-modu"
},
{
"path": "checkpoint/dist-src/util/promise.js",
"chars": 1653,
"preview": "export function wait(delay) {\n return new Promise(resolve => {\n setTimeout(resolve, delay);\n });\n}\nexport f"
},
{
"path": "checkpoint/dist-src/util/signal-handler.js",
"chars": 478,
"preview": "import { forwardSignalToSpawnedProcesses } from './child.js';\nfunction forwardSignalAndExit(signal) {\n forwardSignalT"
},
{
"path": "checkpoint/dist-types/commands/build.d.ts",
"chars": 586,
"preview": "import Config, { BuildFlags } from '../config.js';\nimport { Reporter } from '../reporters/index.js';\nexport declare func"
},
{
"path": "checkpoint/dist-types/config.d.ts",
"chars": 747,
"preview": "import { Manifest } from './types.js';\nimport BaseReporter from './reporters/base-reporter.js';\nexport interface BuildFl"
},
{
"path": "checkpoint/dist-types/constants.d.ts",
"chars": 569,
"preview": "/// <reference types=\"node\" />\nexport declare const DEPENDENCY_TYPES: string[];\nexport declare const RESOLUTIONS = \"reso"
},
{
"path": "checkpoint/dist-types/errors.d.ts",
"chars": 576,
"preview": "import { MessageError } from '@pika/types';\nexport declare class ProcessSpawnError extends MessageError {\n constructo"
},
{
"path": "checkpoint/dist-types/index.d.ts",
"chars": 60,
"preview": "export declare function cli(args: string[]): Promise<void>;\n"
},
{
"path": "checkpoint/dist-types/reporters/base-reporter.d.ts",
"chars": 2521,
"preview": "/// <reference types=\"node\" />\nimport { ReporterSpinnerSet, Trees, Stdout, Stdin, Package, ReporterSpinner } from './typ"
},
{
"path": "checkpoint/dist-types/reporters/console/console-reporter.d.ts",
"chars": 1607,
"preview": "import BaseReporter, { ReporterOptions } from '../base-reporter.js';\nimport { FormatKeys } from '../format.js';\nimport {"
},
{
"path": "checkpoint/dist-types/reporters/console/helpers/tree-helper.d.ts",
"chars": 400,
"preview": "import { Trees } from '../../types.js';\nexport declare type FormattedOutput = {\n prefix: string;\n hint: any;\n c"
},
{
"path": "checkpoint/dist-types/reporters/console/progress-bar.d.ts",
"chars": 520,
"preview": "/// <reference types=\"node\" />\nimport { Stdout } from '../types.js';\nexport default class ProgressBar {\n constructor("
},
{
"path": "checkpoint/dist-types/reporters/console/spinner-progress.d.ts",
"chars": 493,
"preview": "/// <reference types=\"node\" />\nimport { Stdout } from '../types.js';\nexport default class Spinner {\n constructor(stdo"
},
{
"path": "checkpoint/dist-types/reporters/console/util.d.ts",
"chars": 313,
"preview": "import { Stdout } from '../types.js';\nexport declare function clearLine(stdout: Stdout): void;\nexport declare function t"
},
{
"path": "checkpoint/dist-types/reporters/format.d.ts",
"chars": 1352,
"preview": "declare function formatFunction(...strs: Array<string>): string;\nexport declare const defaultFormatter: {\n bold: type"
},
{
"path": "checkpoint/dist-types/reporters/index.d.ts",
"chars": 246,
"preview": "export { default as ConsoleReporter } from './console/console-reporter';\nexport { default as JSONReporter } from './json"
},
{
"path": "checkpoint/dist-types/reporters/json-reporter.d.ts",
"chars": 1039,
"preview": "import { ReporterSpinnerSet, Trees, ReporterSpinner } from './types.js';\nimport BaseReporter from './base-reporter.js';\n"
},
{
"path": "checkpoint/dist-types/reporters/lang/en.d.ts",
"chars": 11144,
"preview": "declare const messages: {\n upToDate: string;\n folderInSync: string;\n nothingToInstall: string;\n resolvingPac"
},
{
"path": "checkpoint/dist-types/reporters/lang/index.d.ts",
"chars": 41,
"preview": "import en from './en.js';\nexport { en };\n"
},
{
"path": "checkpoint/dist-types/reporters/noop-reporter.d.ts",
"chars": 1207,
"preview": "import BaseReporter from './base-reporter.js';\nimport { LanguageKeys } from './lang/en.js';\nimport { Package, ReporterSp"
},
{
"path": "checkpoint/dist-types/reporters/types.d.ts",
"chars": 861,
"preview": "/// <reference types=\"node\" />\nimport { Writable, Readable } from 'stream';\nimport { WriteStream, ReadStream } from 'fs'"
},
{
"path": "checkpoint/dist-types/types.d.ts",
"chars": 2147,
"preview": "import { Reporter } from './reporters/index.js';\nimport Config from './config.js';\nexport declare type CLIFunction = (co"
},
{
"path": "checkpoint/dist-types/util/babel-plugin-import-rewrite.d.ts",
"chars": 104,
"preview": "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",
"chars": 80,
"preview": "export declare function validateDynamicImportArguments(path: any): Set<string>;\n"
},
{
"path": "checkpoint/dist-types/util/blocking-queue.d.ts",
"chars": 781,
"preview": "/// <reference types=\"node\" />\nexport default class BlockingQueue {\n constructor(alias: string, maxConcurrency?: numb"
},
{
"path": "checkpoint/dist-types/util/child.d.ts",
"chars": 673,
"preview": "/// <reference types=\"node\" />\nimport BlockingQueue from './blocking-queue.js';\nimport { ChildProcess, SpawnOptions } fr"
},
{
"path": "checkpoint/dist-types/util/conversion.d.ts",
"chars": 183,
"preview": "export declare function boolify(val: string | number | boolean): boolean;\nexport declare function boolifyWithDefault(val"
},
{
"path": "checkpoint/dist-types/util/execute-lifecycle-script.d.ts",
"chars": 547,
"preview": "/// <reference types=\"node\" />\nexport declare type LifecycleReturn = Promise<{\n cwd: string;\n command: string;\n "
},
{
"path": "checkpoint/dist-types/util/fix-cmd-win-slashes.d.ts",
"chars": 63,
"preview": "export declare function fixCmdWinSlashes(cmd: string): string;\n"
},
{
"path": "checkpoint/dist-types/util/fs-normalized.d.ts",
"chars": 0,
"preview": ""
},
{
"path": "checkpoint/dist-types/util/fs.d.ts",
"chars": 1667,
"preview": "/// <reference types=\"node\" />\nexport declare const unlink: (path: string) => Promise<void>;\nexport declare const glob: "
},
{
"path": "checkpoint/dist-types/util/map.d.ts",
"chars": 48,
"preview": "export default function nullify<T>(obj?: T): T;\n"
},
{
"path": "checkpoint/dist-types/util/misc.d.ts",
"chars": 725,
"preview": "export declare function sortAlpha(a: string, b: string): number;\nexport declare function sortOptionsByFlags(a: any, b: a"
},
{
"path": "checkpoint/dist-types/util/normalize-manifest/fix.d.ts",
"chars": 298,
"preview": "import { Reporter } from '../../reporters/index.js';\ndeclare type Dict<T> = {\n [key: string]: T;\n};\ndeclare type Warn"
},
{
"path": "checkpoint/dist-types/util/normalize-manifest/for-publish.d.ts",
"chars": 236,
"preview": "import Config from '../../config';\nexport declare function generatePublishManifest(manifest: any, config: Config, _dists"
},
{
"path": "checkpoint/dist-types/util/normalize-manifest/index.d.ts",
"chars": 216,
"preview": "import { Manifest } from '../../types.js';\nimport Config from '../../config.js';\ndeclare const _default: (info: any, mod"
},
{
"path": "checkpoint/dist-types/util/normalize-manifest/infer-license.d.ts",
"chars": 70,
"preview": "export default function inferLicense(license: string): string | null;\n"
},
{
"path": "checkpoint/dist-types/util/normalize-manifest/licenses.d.ts",
"chars": 176,
"preview": "declare const _default: {\n 'Apache-2.0': RegExp;\n 'BSD-2-Clause': RegExp;\n 'BSD-3-Clause': RegExp;\n MIT: Reg"
},
{
"path": "checkpoint/dist-types/util/normalize-manifest/typos.d.ts",
"chars": 526,
"preview": "declare const _default: {\n autohr: string;\n autor: string;\n contributers: string;\n depdenencies: string;\n "
},
{
"path": "checkpoint/dist-types/util/normalize-manifest/util.d.ts",
"chars": 375,
"preview": "import { PersonObject } from '../../types.js';\nexport declare function isValidLicense(license: string): boolean;\nexport "
},
{
"path": "checkpoint/dist-types/util/normalize-manifest/validate.d.ts",
"chars": 402,
"preview": "import { Reporter } from '../../reporters/index.js';\nexport declare function isValidPackageName(name: string): boolean;\n"
},
{
"path": "checkpoint/dist-types/util/promise.d.ts",
"chars": 306,
"preview": "export declare function wait(delay: number): Promise<void>;\nexport declare function promisify(fn: Function, firstData?: "
},
{
"path": "checkpoint/dist-types/util/signal-handler.d.ts",
"chars": 47,
"preview": "export default function handleSignals(): void;\n"
},
{
"path": "checkpoint/package.json",
"chars": 1379,
"preview": "{\n \"name\": \"@pika/pack\",\n \"description\": \"package building, reimagined.\",\n \"version\": \"0.4.0\",\n \"license\": \"MIT\",\n "
},
{
"path": "package.json",
"chars": 1696,
"preview": "{\n \"name\": \"@pika/pack\",\n \"description\": \"package building, reimagined.\",\n \"version\": \"0.6.0\",\n \"license\": \"MIT\",\n "
},
{
"path": "src/commands/build.ts",
"chars": 8104,
"preview": "import {BuilderOptions} from '@pika/types';\nimport chalk from 'chalk';\nimport * as path from 'path';\nimport Config, {Bui"
},
{
"path": "src/config.ts",
"chars": 3005,
"preview": "declare function __non_webpack_require__(m: string): any;\n\nimport * as path from 'path';\nimport * as constants from './c"
},
{
"path": "src/constants.ts",
"chars": 4200,
"preview": "// import os from 'os';\n// import * as path from 'path';\n// import userHome from './util/user-home-dir.js';\n// import {g"
},
{
"path": "src/errors.ts",
"chars": 655,
"preview": "import {MessageError} from '@pika/types';\n\nexport class ProcessSpawnError extends MessageError {\n constructor(msg: stri"
},
{
"path": "src/index.ts",
"chars": 4830,
"preview": "import * as path from 'path';\nimport * as kleur from 'kleur';\nimport * as fs from 'fs';\nimport invariant from 'invariant"
},
{
"path": "src/reporters/base-reporter.ts",
"chars": 6588,
"preview": "import {ReporterSpinnerSet, Trees, Stdout, Stdin, Package, ReporterSpinner} from './types';\nimport {LanguageKeys} from '"
},
{
"path": "src/reporters/console/console-reporter.ts",
"chars": 8489,
"preview": "import chalk from 'chalk';\nimport * as readline from 'readline';\nimport stripAnsi from 'strip-ansi';\nimport {inspect} fr"
},
{
"path": "src/reporters/console/helpers/tree-helper.ts",
"chars": 1309,
"preview": "// types\nimport {Trees} from '../../types.js';\n\nexport type FormattedOutput = {\n prefix: string;\n hint: any;\n color: "
},
{
"path": "src/reporters/console/progress-bar.ts",
"chars": 1949,
"preview": "import {Stdout} from '../types.js';\nimport {clearLine, toStartOfLine} from './util.js';\n\nexport default class ProgressBa"
},
{
"path": "src/reporters/console/spinner-progress.ts",
"chars": 1939,
"preview": "import {Stdout} from '../types.js';\nimport {writeOnNthLine, clearNthLine} from './util.js';\n\nexport default class Spinne"
},
{
"path": "src/reporters/console/util.ts",
"chars": 1496,
"preview": "import * as tty from 'tty';\nimport {Stdout} from '../types.js';\n\nimport * as readline from 'readline';\nimport chalk from"
},
{
"path": "src/reporters/format.ts",
"chars": 1147,
"preview": "function formatFunction(...strs: Array<string>): string {\n return strs.join(' ');\n}\n\nexport const defaultFormatter = {\n"
},
{
"path": "src/reporters/index.ts",
"chars": 238,
"preview": "export {default as ConsoleReporter} from './console/console-reporter';\nexport {default as JSONReporter} from './json-rep"
},
{
"path": "src/reporters/json-reporter.ts",
"chars": 3296,
"preview": "import {ReporterSpinnerSet, Trees, ReporterSpinner} from './types.js';\nimport BaseReporter from './base-reporter.js';\n\ne"
},
{
"path": "src/reporters/lang/en.ts",
"chars": 25667,
"preview": "const messages = {\n upToDate: 'Already up-to-date.',\n folderInSync: 'Folder in sync.',\n nothingToInstall: 'Nothing to"
},
{
"path": "src/reporters/lang/index.ts",
"chars": 39,
"preview": "import en from './en.js';\nexport {en};\n"
},
{
"path": "src/reporters/noop-reporter.ts",
"chars": 1436,
"preview": "import BaseReporter from './base-reporter.js';\nimport {LanguageKeys} from './lang/en.js';\nimport {Package, ReporterSpinn"
},
{
"path": "src/reporters/types.ts",
"chars": 738,
"preview": "import {Writable, Readable} from 'stream';\nimport {WriteStream, ReadStream} from 'fs';\n\nexport type Stdout = Writable | "
},
{
"path": "src/types.ts",
"chars": 2306,
"preview": "import {Reporter} from './reporters/index.js';\nimport Config from './config.js';\n\nexport type CLIFunction = (config: Con"
},
{
"path": "src/util/babel-plugin-import-rewrite.ts",
"chars": 2604,
"preview": "// @flow\nimport * as nodeFs from 'fs';\nimport * as nodePath from 'path';\nimport * as url from 'url';\nimport chalk from '"
},
{
"path": "src/util/babel-validate-specifier.ts",
"chars": 699,
"preview": "// @flow\nimport chalk from 'chalk';\n\nfunction getLineCol(node: any): string {\n const loc = node.loc.start;\n return cha"
},
{
"path": "src/util/blocking-queue.ts",
"chars": 3316,
"preview": "import map from './map.js';\n\nexport default class BlockingQueue {\n constructor(alias: string, maxConcurrency: number = "
},
{
"path": "src/util/child.ts",
"chars": 3217,
"preview": "/* global child_process$spawnOpts */\n\nimport * as constants from '../constants.js';\nimport BlockingQueue from './blockin"
},
{
"path": "src/util/conversion.ts",
"chars": 370,
"preview": "const FALSY_STRINGS = new Set(['0', 'false']);\n\nexport function boolify(val: string | number | boolean): boolean {\n ret"
},
{
"path": "src/util/execute-lifecycle-script.ts",
"chars": 12603,
"preview": "import {StdioOptions} from 'child_process';\nimport Config from '../config.js';\nimport {MessageError} from '@pika/types';"
},
{
"path": "src/util/fix-cmd-win-slashes.ts",
"chars": 1009,
"preview": "export function fixCmdWinSlashes(cmd: string): string {\n function findQuotes(quoteSymbol: string): {from: number; to: n"
},
{
"path": "src/util/fs-normalized.ts",
"chars": 6032,
"preview": "//\n\n// // This module serves as a wrapper for file operations that are inconsistant across node and OS versions.\n\n// imp"
},
{
"path": "src/util/fs.ts",
"chars": 26132,
"preview": "import {promisify} from 'util';\nimport _rimraf from 'rimraf';\nimport _mkdirp from 'mkdirp';\nimport _glob from 'glob';\n\ne"
},
{
"path": "src/util/map.ts",
"chars": 451,
"preview": "export default function nullify<T>(obj?: T): T {\n if (Array.isArray(obj)) {\n for (const item of obj) {\n nullify"
},
{
"path": "src/util/misc.ts",
"chars": 1836,
"preview": "/* @flow */\n\nexport function sortAlpha(a: string, b: string): number {\n // sort alphabetically in a deterministic way\n "
},
{
"path": "src/util/normalize-manifest/fix.ts",
"chars": 10147,
"preview": "import {MANIFEST_FIELDS} from '../../constants.js';\nimport {Reporter} from '../../reporters/index.js';\nimport {isValidLi"
},
{
"path": "src/util/normalize-manifest/for-publish.ts",
"chars": 1616,
"preview": "import {Manifest} from '../../types';\nimport Config from '../../config';\n\nexport async function generatePublishManifest("
},
{
"path": "src/util/normalize-manifest/index.ts",
"chars": 1118,
"preview": "import {Manifest} from '../../types.js';\nimport Config from '../../config.js';\nimport validate from './validate.js';\nimp"
},
{
"path": "src/util/normalize-manifest/infer-license.ts",
"chars": 1016,
"preview": "import LICENSES from './licenses.js';\n\nfunction clean(str: string): string {\n return str\n .replace(/[^A-Za-z\\s]/g, '"
},
{
"path": "src/util/normalize-manifest/licenses.ts",
"chars": 18050,
"preview": "export default {\n 'Apache-2.0': new RegExp(\n '(licensed under the apache license version the license you may not use"
},
{
"path": "src/util/normalize-manifest/typos.ts",
"chars": 593,
"preview": "export default {\n autohr: 'author',\n autor: 'author',\n contributers: 'contributors',\n depdenencies: 'dependencies',\n"
},
{
"path": "src/util/normalize-manifest/util.ts",
"chars": 2137,
"preview": "import {PersonObject} from '../../types.js';\n\nimport validateLicense from 'validate-npm-package-license';\n\nexport functi"
},
{
"path": "src/util/normalize-manifest/validate.ts",
"chars": 4291,
"preview": "import {Reporter} from '../../reporters/index.js';\nimport {MessageError} from '@pika/types';\nimport typos from './typos."
},
{
"path": "src/util/promise.ts",
"chars": 1508,
"preview": "export function wait(delay: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, delay);"
},
{
"path": "src/util/signal-handler.ts",
"chars": 470,
"preview": "import {forwardSignalToSpawnedProcesses} from './child.js';\n\nfunction forwardSignalAndExit(signal: string) {\n forwardSi"
},
{
"path": "tsconfig.json",
"chars": 197,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"module\": \"esnext\",\n \"moduleResolution\": \"node\",\n \"esModuleIn"
}
]
About this extraction
This page contains the full source code of the snowpackjs/pack GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 135 files (536.7 KB), approximately 132.1k tokens, and a symbol index with 682 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.